Skip to main content

adk_devtools/
workspace.rs

1//! The sandboxed workspace that scopes every developer-tool operation.
2
3use std::collections::HashMap;
4use std::path::{Component, Path, PathBuf};
5use std::sync::{Arc, Mutex};
6use std::time::Duration;
7
8use adk_core::ToolContext;
9#[cfg(not(any(unix, windows)))]
10use tokio::io::AsyncWriteExt;
11
12#[cfg(windows)]
13use crate::beneath::{remove_beneath, replace_beneath, write_beneath};
14use crate::error::DevToolError;
15use crate::read_ledger::{InMemoryReadLedger, ReadLedger, ReadScope};
16
17/// A workspace roots every file/search/shell operation at a directory and
18/// enforces a small capability policy.
19///
20/// All paths supplied to the tools are resolved relative to [`root`](Self::root)
21/// and rejected if they escape it. Mutating operations require
22/// [`is_writable`](Self::is_writable); `bash` requires [`bash_allowed`](Self::bash_allowed).
23///
24/// The workspace also records the sha256 of every file read and of every file its tools
25/// write, so that `edit_file` can require a prior `read_file` and refuse to edit a file
26/// that changed since (spec 3.1 §7.26, §10 D7). The record is kept per session and agent,
27/// taken from the tool call's context, so one session or agent reading a file does not let
28/// another edit it. Records live in a [`ReadLedger`], in memory unless
29/// [`with_read_ledger`](Self::with_read_ledger) names a persistent one.
30///
31/// `Workspace` is cheap to clone. Clones share the read records, which stay
32/// separated by session and agent; calls whose context names no session share one
33/// record, kept in memory.
34#[derive(Clone)]
35pub struct Workspace {
36    root: PathBuf,
37    writable: bool,
38    allow_bash: bool,
39    bash_timeout: Duration,
40    max_output_bytes: usize,
41    read_ledger: Arc<dyn ReadLedger>,
42    /// Reads by calls that name no session, by record path.
43    unscoped_reads: Arc<Mutex<HashMap<String, String>>>,
44    /// Whether `bash` inherits the parent process environment.
45    inherit_env: bool,
46    /// Variables passed through when the environment is not inherited.
47    env_allowlist: Vec<String>,
48    /// Whether `bash` kills the command's process group once the shell exits.
49    kill_group_on_exit: bool,
50    /// Files that `grep` and `glob` skip and `read_file` refuses.
51    exclude: Vec<glob::Pattern>,
52}
53
54/// The most bytes of a `bash` command's output its output file keeps unless
55/// [`Workspace::max_output_bytes`] says otherwise: 64 MiB (spec 3.1 §10 D10).
56///
57/// # Example
58///
59/// ```rust
60/// assert_eq!(adk_devtools::DEFAULT_MAX_OUTPUT_BYTES, 64 * 1024 * 1024);
61/// ```
62pub const DEFAULT_MAX_OUTPUT_BYTES: usize = 64 * 1024 * 1024;
63
64/// Environment variables `bash` receives by default.
65///
66/// The parent environment of an agent process routinely holds provider API keys, and a
67/// model-directed command could read them with `env`. Only variables tools genuinely
68/// need to function are passed through, and none of them is a credential.
69pub const DEFAULT_ENV_ALLOWLIST: &[&str] =
70    &["PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "TERM", "USER", "SHELL"];
71
72/// File patterns a new [`Workspace`] excludes: environment files, private keys and
73/// certificate bundles.
74///
75/// `grep` and `glob` skip matching files and `read_file` refuses them with
76/// [`DevToolError::Excluded`]. A pattern matches a path relative to the root, or any
77/// one of its components, ignoring case. Implements spec 3.1 §10 D5.
78///
79/// # Example
80///
81/// ```rust
82/// use adk_devtools::{DEFAULT_EXCLUDE_GLOBS, Workspace};
83///
84/// assert!(DEFAULT_EXCLUDE_GLOBS.contains(&".env"));
85/// let ws = Workspace::new("./my-repo");
86/// assert!(ws.is_excluded(std::path::Path::new("config/.env")));
87/// ```
88pub const DEFAULT_EXCLUDE_GLOBS: &[&str] =
89    &[".env", ".env.*", "*.pem", "*.key", "id_rsa*", "id_ed25519*", "*.p12", "*.pfx"];
90
91/// Exclusion patterns match regardless of case, since `.ENV` names `.env` on a
92/// case-insensitive file system, and `*` never crosses a `/`.
93const EXCLUDE_MATCH: glob::MatchOptions = glob::MatchOptions {
94    case_sensitive: false,
95    require_literal_separator: true,
96    require_literal_leading_dot: false,
97};
98
99impl Workspace {
100    /// Create a read-write workspace rooted at `root`, with `bash` disabled.
101    ///
102    /// `bash` runs model-written commands on the host, outside the path containment the file
103    /// tools enforce, so it is off until [`allow_bash`](Self::allow_bash) enables it. If `root`
104    /// exists it is canonicalized so containment checks are robust.
105    ///
106    /// # Example
107    ///
108    /// ```rust
109    /// use adk_devtools::Workspace;
110    ///
111    /// let files_only = Workspace::new("./my-repo");
112    /// assert!(!files_only.bash_allowed());
113    ///
114    /// let with_shell = Workspace::new("./my-repo").allow_bash(true);
115    /// assert!(with_shell.bash_allowed());
116    /// ```
117    pub fn new(root: impl Into<PathBuf>) -> Self {
118        let root = root.into();
119        let root = std::fs::canonicalize(&root).unwrap_or(root);
120        Self {
121            root,
122            writable: true,
123            allow_bash: false,
124            bash_timeout: Duration::from_secs(120),
125            max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
126            read_ledger: Arc::new(InMemoryReadLedger::new()),
127            unscoped_reads: Arc::default(),
128            inherit_env: false,
129            env_allowlist: DEFAULT_ENV_ALLOWLIST.iter().map(|k| (*k).to_string()).collect(),
130            kill_group_on_exit: true,
131            exclude: compile_excludes(DEFAULT_EXCLUDE_GLOBS.iter().map(|glob| (*glob).to_string())),
132        }
133    }
134
135    /// Create a read-only workspace (no writes, no bash) — useful for
136    /// exploration / plan modes.
137    pub fn read_only(root: impl Into<PathBuf>) -> Self {
138        let mut ws = Self::new(root);
139        ws.writable = false;
140        ws.allow_bash = false;
141        ws
142    }
143
144    /// Set whether mutating file operations are permitted.
145    pub fn writable(mut self, yes: bool) -> Self {
146        self.writable = yes;
147        self
148    }
149
150    /// Set whether the `bash` tool is permitted. Off by default.
151    ///
152    /// Commands run with the workspace root as their working directory, which is not a sandbox:
153    /// they can reach absolute paths and the network.
154    pub fn allow_bash(mut self, yes: bool) -> Self {
155        self.allow_bash = yes;
156        self
157    }
158
159    /// Set the timeout applied to `bash` commands, and the most a call may request.
160    pub fn bash_timeout(mut self, timeout: Duration) -> Self {
161        self.bash_timeout = timeout;
162        self
163    }
164
165    /// Set the most bytes of a `bash` command's output an
166    /// [`OutputStore`](crate::OutputStore) file keeps: the disk bound (default
167    /// [`DEFAULT_MAX_OUTPUT_BYTES`], 64 MiB; spec 3.1 §10 D10). The result itself carries at
168    /// most [`INLINE_OUTPUT_CHARS`](crate::INLINE_OUTPUT_CHARS) characters whatever this
169    /// is, and memory holds only the start and end of each stream.
170    ///
171    /// # Example
172    ///
173    /// ```rust
174    /// use adk_devtools::Workspace;
175    ///
176    /// let ws = Workspace::new(".").allow_bash(true).max_output_bytes(8 * 1024 * 1024);
177    /// assert_eq!(ws.max_output(), 8 * 1024 * 1024);
178    /// ```
179    pub fn max_output_bytes(mut self, bytes: usize) -> Self {
180        self.max_output_bytes = bytes;
181        self
182    }
183
184    /// Pass the whole parent environment to `bash`.
185    ///
186    /// Off by default, because the parent environment of an agent process routinely
187    /// holds provider API keys and a model-directed command can read them with `env`.
188    /// Enable it only when the commands you run genuinely need the caller's environment
189    /// and you accept that exposure.
190    #[must_use]
191    pub fn inherit_env(mut self, yes: bool) -> Self {
192        self.inherit_env = yes;
193        self
194    }
195
196    /// Replace the variables `bash` receives when the environment is not inherited.
197    ///
198    /// Defaults to [`DEFAULT_ENV_ALLOWLIST`]. Adding a variable that holds a credential
199    /// re-exposes it.
200    #[must_use]
201    pub fn env_allowlist<I, S>(mut self, keys: I) -> Self
202    where
203        I: IntoIterator<Item = S>,
204        S: Into<String>,
205    {
206        self.env_allowlist = keys.into_iter().map(Into::into).collect();
207        self
208    }
209
210    /// Set whether `bash` kills the rest of the command's process group once the
211    /// shell exits. On by default.
212    ///
213    /// With it on, a process the command leaves running in the background — `sleep 300 &`,
214    /// a dev server — is killed when the call returns, and the call does not wait for
215    /// it to close its output. Turn it off only when commands must leave processes
216    /// running; a timeout or a cancelled call still kills the group. Implements spec 3.1
217    /// §10 D3.
218    ///
219    /// # Example
220    ///
221    /// ```rust
222    /// use adk_devtools::Workspace;
223    ///
224    /// let ws = Workspace::new("./my-repo").allow_bash(true);
225    /// assert!(ws.kills_bash_group_on_exit());
226    ///
227    /// let keeps_servers = ws.bash_kill_group_on_exit(false);
228    /// assert!(!keeps_servers.kills_bash_group_on_exit());
229    /// ```
230    #[must_use]
231    pub fn bash_kill_group_on_exit(mut self, yes: bool) -> Self {
232        self.kill_group_on_exit = yes;
233        self
234    }
235
236    /// Whether `bash` kills the command's process group once the shell exits.
237    ///
238    /// Set with [`bash_kill_group_on_exit`](Self::bash_kill_group_on_exit); spec 3.1 §10 D3.
239    pub fn kills_bash_group_on_exit(&self) -> bool {
240        self.kill_group_on_exit
241    }
242
243    /// Keep read records in `ledger` instead of process memory (spec 3.1 §10 D7).
244    ///
245    /// A host that resumes a session in another process — a held edit approved from a new
246    /// process, a crash-resumed run, a kernel process moved between workers — persists the
247    /// records with the session, so the read that preceded an edit is still known. Clones
248    /// made after this call share `ledger`.
249    ///
250    /// # Example
251    ///
252    /// ```rust
253    /// use std::sync::Arc;
254    ///
255    /// use adk_devtools::{InMemoryReadLedger, Workspace};
256    ///
257    /// let ws = Workspace::new("./my-repo").with_read_ledger(Arc::new(InMemoryReadLedger::new()));
258    /// assert!(ws.is_writable());
259    /// ```
260    #[must_use]
261    pub fn with_read_ledger(mut self, ledger: Arc<dyn ReadLedger>) -> Self {
262        self.read_ledger = ledger;
263        self
264    }
265
266    /// Replace the file patterns `grep` and `glob` skip and `read_file` refuses.
267    ///
268    /// Defaults to [`DEFAULT_EXCLUDE_GLOBS`]; an empty list turns exclusion off. Each
269    /// pattern is a glob matched, ignoring case, against the path relative to the
270    /// root and against each of its components, so `.env` also excludes
271    /// `config/.env` and `secrets/**` everything under `secrets/`. A pattern that is
272    /// not a valid glob matches its literal text. Implements spec 3.1 §10 D5.
273    ///
274    /// # Example
275    ///
276    /// ```rust
277    /// use std::path::Path;
278    ///
279    /// use adk_devtools::Workspace;
280    ///
281    /// let ws = Workspace::new("./my-repo").exclude_globs(["secrets/**".to_string()]);
282    /// assert!(ws.is_excluded(Path::new("secrets/prod/token.txt")));
283    /// assert!(!ws.is_excluded(Path::new(".env")));
284    ///
285    /// let everything = Workspace::new("./my-repo").exclude_globs([]);
286    /// assert!(!everything.is_excluded(Path::new(".env")));
287    /// ```
288    #[must_use]
289    pub fn exclude_globs(mut self, globs: impl IntoIterator<Item = String>) -> Self {
290        self.exclude = compile_excludes(globs);
291        self
292    }
293
294    /// Whether `path` matches one of the exclusion patterns.
295    ///
296    /// `path` is relative to the root, or an absolute path inside it. The check is
297    /// lexical; `read_file` also checks the path a symlink resolves to. A harness
298    /// uses it to require approval before a read. Implements spec 3.1 §10 D5.
299    ///
300    /// # Example
301    ///
302    /// ```rust
303    /// use std::path::Path;
304    ///
305    /// use adk_devtools::Workspace;
306    ///
307    /// let ws = Workspace::new("./my-repo");
308    /// assert!(ws.is_excluded(Path::new("deploy/server.KEY")));
309    /// assert!(!ws.is_excluded(Path::new("src/keys.rs")));
310    /// ```
311    pub fn is_excluded(&self, path: &Path) -> bool {
312        if self.exclude.is_empty() {
313            return false;
314        }
315        let relative = path.strip_prefix(&self.root).unwrap_or(path);
316        self.exclude.iter().any(|pattern| {
317            pattern.matches_path_with(relative, EXCLUDE_MATCH)
318                || relative.components().any(|component| match component {
319                    Component::Normal(name) => {
320                        pattern.matches_with(&name.to_string_lossy(), EXCLUDE_MATCH)
321                    }
322                    Component::Prefix(_)
323                    | Component::RootDir
324                    | Component::CurDir
325                    | Component::ParentDir => false,
326                })
327        })
328    }
329
330    /// Whether `bash` inherits the parent environment.
331    pub fn inherits_env(&self) -> bool {
332        self.inherit_env
333    }
334
335    /// The variables `bash` receives, resolved from the current process.
336    ///
337    /// Empty when the environment is inherited, in which case the caller must not clear
338    /// it.
339    pub fn bash_env(&self) -> Vec<(String, String)> {
340        if self.inherit_env {
341            return Vec::new();
342        }
343        self.env_allowlist
344            .iter()
345            .filter_map(|key| std::env::var(key).ok().map(|value| (key.clone(), value)))
346            .collect()
347    }
348
349    /// The workspace root.
350    pub fn root(&self) -> &Path {
351        &self.root
352    }
353
354    /// Whether mutating file operations are permitted.
355    pub fn is_writable(&self) -> bool {
356        self.writable
357    }
358
359    /// Whether the `bash` tool is permitted.
360    pub fn bash_allowed(&self) -> bool {
361        self.allow_bash
362    }
363
364    /// The default `bash` timeout.
365    pub fn bash_timeout_value(&self) -> Duration {
366        self.bash_timeout
367    }
368
369    /// The most bytes of a command's output its output file keeps.
370    pub fn max_output(&self) -> usize {
371        self.max_output_bytes
372    }
373
374    /// Resolve a user-supplied path against the root, rejecting any path that
375    /// escapes it, lexically or through a symlink. The target need not exist yet.
376    ///
377    /// The returned path is the lexical one. The file tools open the canonical target
378    /// the same check finds, following no symlink on it, so a link swapped onto the path
379    /// after the check fails the call (spec 3.1 §10 D4).
380    pub fn resolve(&self, path: &str) -> Result<PathBuf, DevToolError> {
381        self.resolve_target(path).map(|(normalized, _)| normalized)
382    }
383
384    /// Resolves `path` as [`resolve`](Self::resolve) does and also returns the canonical
385    /// target the check found: where every symlink on the path leads, with the components
386    /// that do not exist yet appended. The file tools open that target and nothing else
387    /// (spec 3.1 §10 D4).
388    pub(crate) fn resolve_target(&self, path: &str) -> Result<(PathBuf, PathBuf), DevToolError> {
389        let requested = Path::new(path);
390        let joined = if requested.is_absolute() {
391            requested.to_path_buf()
392        } else {
393            self.root.join(requested)
394        };
395        let normalized = normalize(&joined);
396        if !normalized.starts_with(&self.root) {
397            return Err(DevToolError::PathEscape(path.to_string()));
398        }
399        // A lexical check alone is not containment: a symlink sitting lexically
400        // under the root can point anywhere, and ordinary file I/O follows it.
401        let target = self.contained_target(&normalized, path)?;
402        Ok((normalized, target))
403    }
404
405    /// Returns the canonical target of `normalized`, rejecting one that reaches outside
406    /// the root by following a symlink.
407    ///
408    /// The deepest existing ancestor of the target is canonicalized, which resolves
409    /// every symlink along the way, and the result must still be inside the root.
410    /// That covers a symlinked final component and a symlinked parent directory, so
411    /// creation through a redirected directory is refused as well. A symlink whose
412    /// target stays inside the workspace is allowed, since repositories legitimately
413    /// contain internal links.
414    ///
415    /// A dangling or looping symlink anywhere on the path is refused, wherever it
416    /// points: canonicalization cannot see through it, and a write follows it and
417    /// creates its target.
418    ///
419    /// This is a check, not a lock: the file tools open the returned target without
420    /// following any symlink, so a link that appears after the check fails the open.
421    fn contained_target(
422        &self,
423        normalized: &Path,
424        requested: &str,
425    ) -> Result<PathBuf, DevToolError> {
426        let mut existing = normalized;
427        loop {
428            match std::fs::canonicalize(existing) {
429                Ok(canonical) => {
430                    if !canonical.starts_with(&self.root) {
431                        return Err(DevToolError::PathEscape(requested.to_string()));
432                    }
433                    // What lies below the deepest existing ancestor does not exist yet.
434                    let missing = normalized.strip_prefix(existing).unwrap_or(Path::new(""));
435                    return Ok(if missing.as_os_str().is_empty() {
436                        canonical
437                    } else {
438                        canonical.join(missing)
439                    });
440                }
441                Err(_) => {
442                    // An entry that exists but does not canonicalize is a symlink whose
443                    // target is missing or loops back on itself.
444                    if std::fs::symlink_metadata(existing).is_ok() {
445                        return Err(DevToolError::PathEscape(requested.to_string()));
446                    }
447                    // Nothing exists here yet, so step up to what does. A component
448                    // that does not exist cannot redirect anything.
449                    match existing.parent() {
450                        Some(parent) if parent.starts_with(&self.root) => existing = parent,
451                        _ => return Ok(normalized.to_path_buf()),
452                    }
453                }
454            }
455        }
456    }
457
458    /// Reads the UTF-8 file at `target`, a canonical target returned by
459    /// [`resolve_target`](Self::resolve_target), following no symlink on it.
460    ///
461    /// On Unix the file is opened beneath the root without following a symlink on any
462    /// component, so a link swapped onto the path after the check fails the read; and a
463    /// file with more than one hard link is refused, since another link to it can lie
464    /// outside the workspace (spec 3.1 §10 D4, §9.2 I28). On Windows the opened handle
465    /// is refused when it is a symlink or a junction, or when its final path is not the
466    /// checked target, and the same hard-link refusal applies (spec 3.2 §10 W6).
467    pub(crate) async fn read_contained(&self, target: &Path) -> Result<String, DevToolError> {
468        let bytes = self.read_contained_bytes(target).await?;
469        // The same error `read_to_string` reports, on every platform.
470        String::from_utf8(bytes).map_err(|_| {
471            DevToolError::Io(std::io::Error::new(
472                std::io::ErrorKind::InvalidData,
473                "stream did not contain valid UTF-8",
474            ))
475        })
476    }
477
478    /// Reads the bytes of the file at `target` under the rules of
479    /// [`read_contained`](Self::read_contained): the same no-follow open and hard-link
480    /// refusal, for content that is not text (spec 3.1 §10 D6, §9.2 I55).
481    pub(crate) async fn read_contained_bytes(
482        &self,
483        target: &Path,
484    ) -> Result<Vec<u8>, DevToolError> {
485        #[cfg(any(unix, windows))]
486        {
487            #[cfg(unix)]
488            use std::io::Read as _;
489            #[cfg(unix)]
490            use std::os::unix::fs::MetadataExt as _;
491
492            let relative = self.beneath_root(target)?;
493            let root = self.root.clone();
494            #[cfg(unix)]
495            let read =
496                tokio::task::spawn_blocking(move || -> std::io::Result<Result<Vec<u8>, u64>> {
497                    let dir = crate::beneath::open_root(&root)?;
498                    let opened = crate::beneath::open_beneath(&dir, &relative, libc::O_RDONLY, 0)?;
499                    let mut file = std::fs::File::from(opened);
500                    let meta = file.metadata()?;
501                    if meta.is_file() && meta.nlink() > 1 {
502                        return Ok(Err(meta.nlink()));
503                    }
504                    let mut contents = Vec::new();
505                    file.read_to_end(&mut contents)?;
506                    Ok(Ok(contents))
507                })
508                .await
509                .map_err(|error| {
510                    DevToolError::Other(format!("the read did not complete: {error}"))
511                })?;
512            #[cfg(windows)]
513            let read =
514                tokio::task::spawn_blocking(move || crate::beneath::read_beneath(&root, &relative))
515                    .await
516                    .map_err(|error| {
517                        DevToolError::Other(format!("the read did not complete: {error}"))
518                    })?;
519            match read {
520                Ok(Ok(contents)) => Ok(contents),
521                Ok(Err(links)) => Err(DevToolError::Other(format!(
522                    "'{}' has {links} hard links, and another link to it can lie outside the \
523                     workspace, so the file tools do not read it; copy it to a new file to read it",
524                    self.display(target)
525                ))),
526                Err(error) => Err(self.open_error(target, error)),
527            }
528        }
529        #[cfg(not(any(unix, windows)))]
530        {
531            Ok(tokio::fs::read(target).await?)
532        }
533    }
534
535    /// Writes `contents` to `target`, a canonical target returned by
536    /// [`resolve_target`](Self::resolve_target), creating the file and its missing
537    /// parent directories or truncating it, once `precondition` holds.
538    ///
539    /// On Unix the parent directory is opened by descriptor beneath the root, creating
540    /// what is missing, and the file relative to it, following no symlink on any
541    /// component: a symlink planted anywhere on the path after the check fails the
542    /// write instead of redirecting it (spec 3.1 §10 D4). The precondition is checked on
543    /// the descriptor the write goes through, so a file that changed is never written
544    /// (spec 3.1 §7.26, I66). A file with more than one hard link is replaced, keeping
545    /// its permissions, rather than truncated: truncating writes through every link,
546    /// including one outside the workspace.
547    ///
548    /// On Windows each directory on the path is opened, or created, without following a
549    /// link on it and held open until the write ends, and the file is opened without
550    /// truncation; the handle is refused when it is a symlink or a junction or when its
551    /// final path is not the checked target, the precondition is read through it, and it
552    /// is truncated only after those checks (spec 3.2 §10 W6).
553    pub(crate) async fn write_contained(
554        &self,
555        target: &Path,
556        contents: &[u8],
557        precondition: Precondition,
558    ) -> Result<(), DevToolError> {
559        #[cfg(any(unix, windows))]
560        {
561            let relative = self.beneath_root(target)?;
562            let Some(name) = relative.file_name().map(std::ffi::OsStr::to_os_string) else {
563                return Err(std::io::Error::from(std::io::ErrorKind::IsADirectory).into());
564            };
565            let root = self.root.clone();
566            let contents = contents.to_vec();
567            tokio::task::spawn_blocking(move || {
568                write_beneath(&root, &relative, &name, &contents, &precondition)
569            })
570            .await
571            .map_err(|error| DevToolError::Other(format!("the write did not complete: {error}")))?
572            .map_err(|error| self.open_error(target, error))
573        }
574        #[cfg(not(any(unix, windows)))]
575        {
576            let escape = || DevToolError::PathEscape(self.display(target));
577            let (Some(parent), Some(name)) = (target.parent(), target.file_name()) else {
578                return Err(escape());
579            };
580            tokio::fs::create_dir_all(parent).await?;
581            if !tokio::fs::canonicalize(parent).await?.join(name).starts_with(&self.root) {
582                return Err(escape());
583            }
584            let current = tokio::fs::read(target).await;
585            precondition
586                .check(current.as_deref().ok())
587                .map_err(|error| self.open_error(target, error))?;
588            let mut file = tokio::fs::OpenOptions::new()
589                .write(true)
590                .create(true)
591                .truncate(true)
592                .open(target)
593                .await?;
594            file.write_all(contents).await?;
595            file.flush().await?;
596            Ok(())
597        }
598    }
599
600    /// Writes `contents` to a temporary sibling of `target` and renames it into place,
601    /// once `precondition` holds, keeping an existing file's permissions (spec 3.1 §7.26
602    /// `apply_patch`).
603    ///
604    /// The parent directory and the target are opened as for
605    /// [`write_contained`](Self::write_contained), following no symlink; the rename
606    /// replaces the target in one step, so a reader never sees a partial file.
607    pub(crate) async fn replace_contained(
608        &self,
609        target: &Path,
610        contents: &[u8],
611        precondition: Precondition,
612    ) -> Result<(), DevToolError> {
613        #[cfg(any(unix, windows))]
614        {
615            let relative = self.beneath_root(target)?;
616            let Some(name) = relative.file_name().map(std::ffi::OsStr::to_os_string) else {
617                return Err(std::io::Error::from(std::io::ErrorKind::IsADirectory).into());
618            };
619            let root = self.root.clone();
620            let contents = contents.to_vec();
621            tokio::task::spawn_blocking(move || {
622                replace_beneath(&root, &relative, &name, &contents, &precondition)
623            })
624            .await
625            .map_err(|error| DevToolError::Other(format!("the write did not complete: {error}")))?
626            .map_err(|error| self.open_error(target, error))
627        }
628        #[cfg(not(any(unix, windows)))]
629        {
630            self.write_contained(target, contents, precondition).await
631        }
632    }
633
634    /// Removes the file `target` once `precondition` holds, following no symlink on the
635    /// path (spec 3.1 §7.26 `apply_patch`).
636    pub(crate) async fn remove_contained(
637        &self,
638        target: &Path,
639        precondition: Precondition,
640    ) -> Result<(), DevToolError> {
641        #[cfg(any(unix, windows))]
642        {
643            let relative = self.beneath_root(target)?;
644            let Some(name) = relative.file_name().map(std::ffi::OsStr::to_os_string) else {
645                return Err(std::io::Error::from(std::io::ErrorKind::IsADirectory).into());
646            };
647            let root = self.root.clone();
648            tokio::task::spawn_blocking(move || {
649                remove_beneath(&root, &relative, &name, &precondition)
650            })
651            .await
652            .map_err(|error| DevToolError::Other(format!("the removal did not complete: {error}")))?
653            .map_err(|error| self.open_error(target, error))
654        }
655        #[cfg(not(any(unix, windows)))]
656        {
657            let current = tokio::fs::read(target).await;
658            precondition
659                .check(current.as_deref().ok())
660                .map_err(|error| self.open_error(target, error))?;
661            Ok(tokio::fs::remove_file(target).await?)
662        }
663    }
664
665    /// `target` relative to the root, which every target the check returns lies under.
666    #[cfg(any(unix, windows))]
667    fn beneath_root(&self, target: &Path) -> Result<PathBuf, DevToolError> {
668        target
669            .strip_prefix(&self.root)
670            .map(Path::to_path_buf)
671            .map_err(|_| DevToolError::PathEscape(self.display(target)))
672    }
673
674    /// Reports a failed precondition as stale, an open that refused a symlink as an
675    /// escape, and any other failure as I/O.
676    fn open_error(&self, target: &Path, error: std::io::Error) -> DevToolError {
677        if let Some(stale) = error.get_ref().and_then(|inner| inner.downcast_ref::<StaleFile>()) {
678            return DevToolError::Stale { path: self.display(target), detail: stale.to_string() };
679        }
680        #[cfg(any(unix, windows))]
681        if crate::beneath::is_symlink_refusal(&error) {
682            return DevToolError::PathEscape(self.display(target));
683        }
684        DevToolError::Io(error)
685    }
686
687    /// Render a path relative to the root for display (falls back to the full path).
688    pub fn display(&self, path: &Path) -> String {
689        path.strip_prefix(&self.root).unwrap_or(path).display().to_string()
690    }
691
692    /// The key a read record names `resolved` by: its path relative to the root with `/`
693    /// separators, so a record written on one platform matches on another.
694    pub fn record_path(&self, resolved: &Path) -> String {
695        let relative = resolved.strip_prefix(&self.root).unwrap_or(resolved);
696        relative
697            .components()
698            .map(|component| component.as_os_str().to_string_lossy())
699            .collect::<Vec<_>>()
700            .join("/")
701    }
702
703    /// Records that the session and agent behind `ctx` saw `resolved` with content digest
704    /// `sha256`, by reading or writing it. A record that cannot be stored is logged and
705    /// skipped: the read succeeded, and a later edit then asks for another read.
706    pub(crate) async fn record_digest(&self, ctx: &dyn ToolContext, resolved: &Path, sha256: &str) {
707        let path = self.record_path(resolved);
708        let Some(scope) = ReadScope::of(ctx) else {
709            if let Ok(mut reads) = self.unscoped_reads.lock() {
710                reads.insert(path, sha256.to_string());
711            }
712            return;
713        };
714        if let Err(error) = self.read_ledger.record(&scope, &path, sha256).await {
715            tracing::warn!(file.path = %path, error = %error, "read record not stored");
716        }
717    }
718
719    /// The digest the session and agent behind `ctx` last saw `resolved` with.
720    ///
721    /// # Errors
722    ///
723    /// Returns [`DevToolError::Other`] when the ledger cannot be read, so an edit fails
724    /// closed instead of running unchecked.
725    pub(crate) async fn read_digest(
726        &self,
727        ctx: &dyn ToolContext,
728        resolved: &Path,
729    ) -> Result<Option<String>, DevToolError> {
730        let path = self.record_path(resolved);
731        let Some(scope) = ReadScope::of(ctx) else {
732            return Ok(self.unscoped_reads.lock().ok().and_then(|reads| reads.get(&path).cloned()));
733        };
734        self.read_ledger.digest(&scope, &path).await.map_err(|error| {
735            DevToolError::Other(format!(
736                "the read records are unavailable ({}), so '{path}' cannot be checked; try again",
737                error.message
738            ))
739        })
740    }
741
742    /// The key a read record and an `expect_sha256` map name `path` by, after the
743    /// containment check: its path relative to the root with `/` separators.
744    ///
745    /// # Errors
746    ///
747    /// Returns [`DevToolError::PathEscape`] for a path outside the root.
748    ///
749    /// # Example
750    ///
751    /// ```rust
752    /// let dir = tempfile::tempdir().unwrap();
753    /// let ws = adk_devtools::Workspace::new(dir.path());
754    /// assert_eq!(ws.record_key("./src/../src/lib.rs").unwrap(), "src/lib.rs");
755    /// assert!(ws.record_key("../outside").is_err());
756    /// ```
757    pub fn record_key(&self, path: &str) -> Result<String, DevToolError> {
758        let (resolved, _) = self.resolve_target(path)?;
759        Ok(self.record_path(&resolved))
760    }
761
762    /// Reads `path` for a reviewer under the file tools' rules — containment, no symlink
763    /// followed, excluded secret files refused — returning `None` when it does not exist
764    /// (spec 3.1 §7.26: a change set is composed over what the tools would read).
765    ///
766    /// # Errors
767    ///
768    /// Returns [`DevToolError::PathEscape`], [`DevToolError::Excluded`], or the read error.
769    ///
770    /// # Example
771    ///
772    /// ```rust,no_run
773    /// # async fn example() -> Result<(), adk_devtools::DevToolError> {
774    /// let ws = adk_devtools::Workspace::new("./my-repo");
775    /// let current = ws.read_for_review("src/lib.rs").await?;
776    /// # let _ = current;
777    /// # Ok(())
778    /// # }
779    /// ```
780    pub async fn read_for_review(&self, path: &str) -> Result<Option<Vec<u8>>, DevToolError> {
781        let (resolved, target) = self.resolve_target(path)?;
782        if self.is_excluded(&resolved) || self.is_excluded(&target) {
783            return Err(DevToolError::Excluded(self.display(&resolved)));
784        }
785        match self.read_contained_bytes(&target).await {
786            Ok(bytes) => Ok(Some(bytes)),
787            Err(DevToolError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
788                Ok(None)
789            }
790            Err(error) => Err(error),
791        }
792    }
793
794    /// Records the current content of `path` as what the session and agent behind `ctx`
795    /// last saw, for a host step that changes a file right after the agent wrote it — a
796    /// formatter hook — so the agent's next edit is not refused as stale (spec 3.1 §7.22,
797    /// §7.26).
798    ///
799    /// # Errors
800    ///
801    /// Returns the containment or read error for `path`.
802    ///
803    /// # Example
804    ///
805    /// ```rust,no_run
806    /// # async fn example(ws: adk_devtools::Workspace, ctx: &dyn adk_core::ToolContext) {
807    /// ws.record_current(ctx, "src/lib.rs").await.unwrap();
808    /// # }
809    /// ```
810    pub async fn record_current(
811        &self,
812        ctx: &dyn ToolContext,
813        path: &str,
814    ) -> Result<(), DevToolError> {
815        let (resolved, target) = self.resolve_target(path)?;
816        let bytes = self.read_contained_bytes(&target).await?;
817        self.record_digest(ctx, &resolved, &crate::read_ledger::sha256_hex(&bytes)).await;
818        Ok(())
819    }
820
821    /// Forgets the record of `resolved` for the session and agent behind `ctx`: the file
822    /// was deleted or moved away.
823    pub(crate) async fn forget_read(&self, ctx: &dyn ToolContext, resolved: &Path) {
824        let path = self.record_path(resolved);
825        let Some(scope) = ReadScope::of(ctx) else {
826            if let Ok(mut reads) = self.unscoped_reads.lock() {
827                reads.remove(&path);
828            }
829            return;
830        };
831        if let Err(error) = self.read_ledger.forget(&scope, &path).await {
832            tracing::warn!(file.path = %path, error = %error, "read record not removed");
833        }
834    }
835}
836
837/// What a write requires of the file it replaces (spec 3.1 §7.26, I66).
838#[derive(Clone, Debug, PartialEq, Eq)]
839pub(crate) enum Precondition {
840    /// Nothing: the file may be absent or hold anything.
841    Any,
842    /// The file must not exist.
843    Absent,
844    /// The file must exist with this lowercase hex sha256.
845    Sha256(String),
846}
847
848impl Precondition {
849    /// `expect_sha256` as a call states it: a digest, or `absent` for a file that must not
850    /// exist yet.
851    pub(crate) fn from_expect(expect: &str) -> Result<Self, DevToolError> {
852        let expect = expect.trim();
853        if expect.eq_ignore_ascii_case("absent") {
854            return Ok(Self::Absent);
855        }
856        let digest = expect.strip_prefix("sha256:").unwrap_or(expect).to_ascii_lowercase();
857        if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
858            return Err(DevToolError::Other(format!(
859                "expect_sha256 must be a 64-character hex sha256 or \"absent\"; got \"{expect}\""
860            )));
861        }
862        Ok(Self::Sha256(digest))
863    }
864
865    /// Checks the file's current content, `None` when it does not exist.
866    pub(crate) fn check(&self, current: Option<&[u8]>) -> std::io::Result<()> {
867        match (self, current) {
868            (Self::Any, _) | (Self::Absent, None) => Ok(()),
869            (Self::Absent, Some(_)) => Err(StaleFile::Exists.into()),
870            (Self::Sha256(_), None) => Err(StaleFile::Missing.into()),
871            (Self::Sha256(expected), Some(bytes)) => {
872                let found = crate::read_ledger::sha256_hex(bytes);
873                if found == *expected {
874                    Ok(())
875                } else {
876                    Err(StaleFile::Changed { expected: expected.clone(), found }.into())
877                }
878            }
879        }
880    }
881}
882
883/// Why a file failed its [`Precondition`]; carried inside an `io::Error` from the
884/// blocking write to [`Workspace::open_error`].
885#[derive(Debug)]
886pub(crate) enum StaleFile {
887    /// The file is gone.
888    Missing,
889    /// A file exists where none was expected.
890    Exists,
891    /// The content differs.
892    Changed { expected: String, found: String },
893}
894
895impl std::fmt::Display for StaleFile {
896    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
897        match self {
898            Self::Missing => f.write_str("it no longer exists"),
899            Self::Exists => f.write_str("a file exists there now, and the call expected none"),
900            Self::Changed { expected, found } => write!(
901                f,
902                "its sha256 is now {}…, and the call expected {}…",
903                &found[..12.min(found.len())],
904                &expected[..12.min(expected.len())]
905            ),
906        }
907    }
908}
909
910impl std::error::Error for StaleFile {}
911
912impl From<StaleFile> for std::io::Error {
913    fn from(stale: StaleFile) -> Self {
914        std::io::Error::other(stale)
915    }
916}
917
918/// Compiles exclusion globs; a pattern that does not parse matches its literal text.
919fn compile_excludes(globs: impl IntoIterator<Item = String>) -> Vec<glob::Pattern> {
920    globs
921        .into_iter()
922        .map(|glob| {
923            glob::Pattern::new(&glob).unwrap_or_else(|error| {
924                tracing::warn!(
925                    exclude.pattern = %glob,
926                    error = %error,
927                    "exclusion pattern is not a valid glob; matching it literally"
928                );
929                glob::Pattern::new(&glob::Pattern::escape(&glob))
930                    .expect("an escaped pattern is a valid glob")
931            })
932        })
933        .collect()
934}
935
936/// Opens the root, creating it when missing, and the directory `relative`'s parent beneath
937/// it, creating missing directories when `create` is set, following no symlink.
938#[cfg(unix)]
939fn open_parent_beneath(
940    root: &Path,
941    relative: &Path,
942    create: bool,
943) -> std::io::Result<std::os::fd::OwnedFd> {
944    let dir = match crate::beneath::open_root(root) {
945        // The root is trusted, so a workspace whose root does not exist yet creates it.
946        Err(error) if create && error.kind() == std::io::ErrorKind::NotFound => {
947            std::fs::create_dir_all(root)?;
948            crate::beneath::open_root(root)?
949        }
950        result => result?,
951    };
952    let parent_path = relative.parent().unwrap_or(Path::new(""));
953    let flags = libc::O_RDONLY | libc::O_DIRECTORY;
954    match crate::beneath::open_beneath(&dir, parent_path, flags, 0) {
955        Err(error) if create && error.kind() == std::io::ErrorKind::NotFound => {
956            crate::beneath::create_dirs_beneath(&dir, parent_path)
957        }
958        result => result,
959    }
960}
961
962/// Reads the entry `name` of `parent` without following a symlink and checks it against
963/// `precondition`; returns its metadata, or `None` when it does not exist.
964#[cfg(unix)]
965fn check_entry(
966    parent: &std::os::fd::OwnedFd,
967    name: &std::ffi::OsStr,
968    precondition: &Precondition,
969) -> std::io::Result<Option<std::fs::Metadata>> {
970    use std::io::Read as _;
971
972    match crate::beneath::open_entry(parent, name, libc::O_RDONLY, 0) {
973        Ok(mut file) => {
974            let meta = file.metadata()?;
975            if !matches!(precondition, Precondition::Any) {
976                let mut current = Vec::new();
977                file.read_to_end(&mut current)?;
978                precondition.check(Some(&current))?;
979            }
980            Ok(Some(meta))
981        }
982        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
983            precondition.check(None)?;
984            Ok(None)
985        }
986        Err(error) => Err(error),
987    }
988}
989
990/// Writes `contents` to the entry `name` of the directory `relative` beneath `root`
991/// once `precondition` holds (spec 3.1 §10 D4, §7.26).
992///
993/// The parent is opened by descriptor, creating missing directories, and the file
994/// relative to it, all without following a symlink. The precondition is read through the
995/// descriptor the write goes through. The file is truncated only after its link count is
996/// known, so a hard-linked file is replaced instead.
997#[cfg(unix)]
998fn write_beneath(
999    root: &Path,
1000    relative: &Path,
1001    name: &std::ffi::OsStr,
1002    contents: &[u8],
1003    precondition: &Precondition,
1004) -> std::io::Result<()> {
1005    use std::io::{Read as _, Seek as _, Write as _};
1006    use std::os::unix::fs::MetadataExt as _;
1007
1008    let parent = open_parent_beneath(root, relative, true)?;
1009    let opened = match precondition {
1010        Precondition::Any => {
1011            crate::beneath::open_entry(&parent, name, libc::O_WRONLY | libc::O_CREAT, 0o666)
1012        }
1013        Precondition::Absent => crate::beneath::open_entry(
1014            &parent,
1015            name,
1016            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL,
1017            0o666,
1018        ),
1019        Precondition::Sha256(_) => crate::beneath::open_entry(&parent, name, libc::O_RDWR, 0),
1020    };
1021    let mut file = match opened {
1022        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
1023            return Err(StaleFile::Exists.into());
1024        }
1025        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1026            return Err(StaleFile::Missing.into());
1027        }
1028        result => result?,
1029    };
1030    let meta = file.metadata()?;
1031    if let Precondition::Sha256(_) = precondition {
1032        let mut current = Vec::new();
1033        file.read_to_end(&mut current)?;
1034        precondition.check(Some(&current))?;
1035        file.rewind()?;
1036    }
1037    if meta.is_file() && meta.nlink() > 1 {
1038        drop(file);
1039        return replace_entry(&parent, name, Some(meta.permissions()), contents);
1040    }
1041    if meta.is_file() {
1042        file.set_len(0)?;
1043    }
1044    file.write_all(contents)?;
1045    file.flush()
1046}
1047
1048/// Writes `contents` to a temporary sibling of the entry `name` of the directory
1049/// `relative` beneath `root` and renames it over `name`, once `precondition` holds
1050/// (spec 3.1 §7.26 `apply_patch`).
1051#[cfg(unix)]
1052fn replace_beneath(
1053    root: &Path,
1054    relative: &Path,
1055    name: &std::ffi::OsStr,
1056    contents: &[u8],
1057    precondition: &Precondition,
1058) -> std::io::Result<()> {
1059    let parent = open_parent_beneath(root, relative, true)?;
1060    let existing = check_entry(&parent, name, precondition)?;
1061    replace_entry(&parent, name, existing.map(|meta| meta.permissions()), contents)
1062}
1063
1064/// Removes the entry `name` of the directory `relative` beneath `root` once
1065/// `precondition` holds, following no symlink (spec 3.1 §7.26 `apply_patch`).
1066#[cfg(unix)]
1067fn remove_beneath(
1068    root: &Path,
1069    relative: &Path,
1070    name: &std::ffi::OsStr,
1071    precondition: &Precondition,
1072) -> std::io::Result<()> {
1073    let parent = open_parent_beneath(root, relative, false)?;
1074    if check_entry(&parent, name, precondition)?.is_none() {
1075        return Err(std::io::Error::from(std::io::ErrorKind::NotFound));
1076    }
1077    crate::beneath::remove_entry(&parent, name)
1078}
1079
1080/// Writes `contents` to a new entry beside `name` in `parent` and renames it over
1081/// `name`, with `permissions` when given and the default mode otherwise.
1082#[cfg(unix)]
1083fn replace_entry(
1084    parent: &std::os::fd::OwnedFd,
1085    name: &std::ffi::OsStr,
1086    permissions: Option<std::fs::Permissions>,
1087    contents: &[u8],
1088) -> std::io::Result<()> {
1089    use std::io::Write as _;
1090
1091    let nanos = std::time::SystemTime::now()
1092        .duration_since(std::time::UNIX_EPOCH)
1093        .map(|elapsed| elapsed.as_nanos())
1094        .unwrap_or_default();
1095    let temp = std::ffi::OsString::from(format!(
1096        ".{}.{}.{nanos}.tmp",
1097        name.to_string_lossy(),
1098        std::process::id()
1099    ));
1100    let result = (|| {
1101        // A new file gets the mode `write_file` gives one; an existing file keeps its own.
1102        let mode = if permissions.is_some() { 0o600 } else { 0o666 };
1103        let mut file = crate::beneath::open_entry(
1104            parent,
1105            &temp,
1106            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL,
1107            mode,
1108        )?;
1109        file.write_all(contents)?;
1110        if let Some(permissions) = permissions {
1111            file.set_permissions(permissions)?;
1112        }
1113        crate::beneath::rename_entry(parent, &temp, name)
1114    })();
1115    if result.is_err() {
1116        let _ = crate::beneath::remove_entry(parent, &temp);
1117    }
1118    result
1119}
1120
1121/// Lexically normalize a path, resolving `.` and `..` without touching the
1122/// filesystem (so non-existent targets still normalize).
1123fn normalize(path: &Path) -> PathBuf {
1124    let mut out = PathBuf::new();
1125    for component in path.components() {
1126        match component {
1127            Component::ParentDir => {
1128                out.pop();
1129            }
1130            Component::CurDir => {}
1131            other => out.push(other.as_os_str()),
1132        }
1133    }
1134    out
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139    use super::*;
1140
1141    #[test]
1142    fn rejects_escape() {
1143        let dir = tempfile::tempdir().unwrap();
1144        let ws = Workspace::new(dir.path());
1145        assert!(ws.resolve("../etc/passwd").is_err());
1146        assert!(ws.resolve("ok/file.rs").is_ok());
1147    }
1148
1149    #[cfg(any(unix, windows))]
1150    #[tokio::test]
1151    async fn a_symlink_planted_after_resolve_is_not_followed() {
1152        let temp = tempfile::tempdir().unwrap();
1153        let root = temp.path().join("workspace");
1154        let outside = temp.path().join("outside");
1155        std::fs::create_dir_all(&root).unwrap();
1156        std::fs::create_dir_all(&outside).unwrap();
1157        std::fs::write(outside.join("existing.txt"), "host").unwrap();
1158        let ws = Workspace::new(&root);
1159
1160        for (name, target) in
1161            [("dangling", outside.join("planted.txt")), ("existing", outside.join("existing.txt"))]
1162        {
1163            let resolved = ws.resolve(name).expect("the path does not exist yet");
1164            let Some(()) = link(&target, &root.join(name)) else { return };
1165
1166            let result = ws.write_contained(&resolved, b"payload", Precondition::Any).await;
1167
1168            assert!(
1169                matches!(result, Err(DevToolError::PathEscape(_))),
1170                "a {name} link planted after resolve was followed: {result:?}"
1171            );
1172        }
1173        assert!(!outside.join("planted.txt").exists());
1174        assert_eq!(std::fs::read_to_string(outside.join("existing.txt")).unwrap(), "host");
1175    }
1176
1177    #[cfg(any(unix, windows))]
1178    #[tokio::test]
1179    async fn writing_a_hard_linked_file_leaves_the_other_link_unchanged() {
1180        #[cfg(unix)]
1181        use std::os::unix::fs::PermissionsExt;
1182
1183        let temp = tempfile::tempdir().unwrap();
1184        let root = temp.path().join("workspace");
1185        let outside = temp.path().join("outside.txt");
1186        std::fs::create_dir_all(&root).unwrap();
1187        std::fs::write(&outside, "host").unwrap();
1188        std::fs::hard_link(&outside, root.join("linked.txt")).unwrap();
1189        #[cfg(unix)]
1190        std::fs::set_permissions(root.join("linked.txt"), std::fs::Permissions::from_mode(0o640))
1191            .unwrap();
1192        let ws = Workspace::new(&root);
1193
1194        let resolved = ws.resolve("linked.txt").unwrap();
1195        ws.write_contained(&resolved, b"rewritten", Precondition::Any).await.unwrap();
1196
1197        assert_eq!(std::fs::read_to_string(root.join("linked.txt")).unwrap(), "rewritten");
1198        assert_eq!(std::fs::read_to_string(&outside).unwrap(), "host");
1199        #[cfg(unix)]
1200        {
1201            let mode = std::fs::metadata(root.join("linked.txt")).unwrap().permissions().mode();
1202            assert_eq!(mode & 0o7777, 0o640);
1203        }
1204        assert_eq!(std::fs::read_dir(&root).unwrap().count(), 1, "no temporary file is left");
1205    }
1206
1207    /// A workspace with `notes.md`, an `AGENTS.md` beside it, a `docs/` directory, and a
1208    /// host directory outside the root.
1209    #[cfg(any(unix, windows))]
1210    struct SwapFixture {
1211        _temp: tempfile::TempDir,
1212        root: PathBuf,
1213        outside: PathBuf,
1214    }
1215
1216    #[cfg(any(unix, windows))]
1217    fn swap_fixture() -> SwapFixture {
1218        let temp = tempfile::tempdir().unwrap();
1219        let root = temp.path().join("workspace");
1220        let outside = temp.path().join("outside");
1221        std::fs::create_dir_all(root.join("docs")).unwrap();
1222        std::fs::create_dir_all(&outside).unwrap();
1223        std::fs::write(root.join("notes.md"), "notes").unwrap();
1224        std::fs::write(root.join("docs/guide.md"), "guide").unwrap();
1225        std::fs::write(root.join("AGENTS.md"), "instructions").unwrap();
1226        std::fs::write(outside.join("secret.txt"), "host secret").unwrap();
1227        std::fs::write(outside.join("guide.md"), "host guide").unwrap();
1228        SwapFixture { _temp: temp, root, outside }
1229    }
1230
1231    /// Replaces `path` with a link to `target`, as a concurrent process would; `None`
1232    /// when [`link`] cannot make one.
1233    #[cfg(any(unix, windows))]
1234    fn swap_for_link(path: &Path, target: &Path) -> Option<()> {
1235        let staged = path.with_extension("swap");
1236        link(target, &staged)?;
1237        if path.is_dir() {
1238            std::fs::rename(path, path.with_extension("moved")).unwrap();
1239        }
1240        std::fs::rename(&staged, path).unwrap();
1241        Some(())
1242    }
1243
1244    /// Makes `at` a link to `target`: a symlink on Unix, and on Windows a junction to a
1245    /// directory or a symlink to anything else.
1246    ///
1247    /// `None` when Windows refuses the symlink because creating one needs Developer Mode
1248    /// or an elevated shell; the caller then skips its test. CI always has the privilege,
1249    /// so there the refusal fails the test instead.
1250    #[cfg(any(unix, windows))]
1251    fn link(target: &Path, at: &Path) -> Option<()> {
1252        #[cfg(unix)]
1253        std::os::unix::fs::symlink(target, at).unwrap();
1254        #[cfg(windows)]
1255        if target.is_dir() {
1256            junction(target, at);
1257        } else {
1258            return privileged(std::os::windows::fs::symlink_file(target, at));
1259        }
1260        Some(())
1261    }
1262
1263    /// Makes `at` a junction (a mount point) to the directory `target`, which needs no
1264    /// privilege.
1265    #[cfg(windows)]
1266    fn junction(target: &Path, at: &Path) {
1267        let made = std::process::Command::new("cmd")
1268            .args(["/C", "mklink", "/J"])
1269            .arg(at)
1270            .arg(target)
1271            .output()
1272            .unwrap();
1273        assert!(
1274            made.status.success(),
1275            "mklink /J failed: {}",
1276            String::from_utf8_lossy(&made.stdout)
1277        );
1278    }
1279
1280    /// `Some` when a Windows symlink was made, `None` when the process lacks the privilege
1281    /// outside CI.
1282    #[cfg(windows)]
1283    fn privileged(made: std::io::Result<()>) -> Option<()> {
1284        let not_held = windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32;
1285        match made {
1286            Ok(()) => Some(()),
1287            Err(error)
1288                if error.raw_os_error() == Some(not_held) && std::env::var_os("CI").is_none() =>
1289            {
1290                eprintln!("skipped: creating a symlink needs Developer Mode or an elevated shell");
1291                None
1292            }
1293            Err(error) => panic!("could not create a symlink: {error}"),
1294        }
1295    }
1296
1297    #[cfg(any(unix, windows))]
1298    #[tokio::test]
1299    async fn a_file_swapped_for_a_link_inside_the_root_after_the_check_is_not_written() {
1300        // The harness decides on the target a path resolves to; a link swapped in
1301        // afterwards must not carry the write to a protected file.
1302        let f = swap_fixture();
1303        let ws = Workspace::new(&f.root);
1304        let (_, target) = ws.resolve_target("notes.md").unwrap();
1305        let Some(()) = swap_for_link(&f.root.join("notes.md"), &f.root.join("AGENTS.md")) else {
1306            return;
1307        };
1308
1309        let result = ws.write_contained(&target, b"rewritten", Precondition::Any).await;
1310
1311        assert!(matches!(result, Err(DevToolError::PathEscape(_))), "{result:?}");
1312        assert_eq!(std::fs::read_to_string(f.root.join("AGENTS.md")).unwrap(), "instructions");
1313    }
1314
1315    #[cfg(any(unix, windows))]
1316    #[tokio::test]
1317    async fn a_file_swapped_for_a_link_outside_the_root_after_the_check_is_not_read() {
1318        let f = swap_fixture();
1319        let ws = Workspace::new(&f.root);
1320        let (_, target) = ws.resolve_target("notes.md").unwrap();
1321        let Some(()) = swap_for_link(&f.root.join("notes.md"), &f.outside.join("secret.txt"))
1322        else {
1323            return;
1324        };
1325
1326        let result = ws.read_contained(&target).await;
1327
1328        assert!(matches!(result, Err(DevToolError::PathEscape(_))), "{result:?}");
1329    }
1330
1331    #[cfg(any(unix, windows))]
1332    #[tokio::test]
1333    async fn a_directory_swapped_for_a_link_after_the_check_is_not_followed() {
1334        let f = swap_fixture();
1335        let ws = Workspace::new(&f.root);
1336        let (_, read_target) = ws.resolve_target("docs/guide.md").unwrap();
1337        let (_, write_target) = ws.resolve_target("docs/new.md").unwrap();
1338        swap_for_link(&f.root.join("docs"), &f.outside).unwrap();
1339
1340        let read = ws.read_contained(&read_target).await;
1341        let write = ws.write_contained(&write_target, b"planted", Precondition::Any).await;
1342
1343        assert!(matches!(read, Err(DevToolError::PathEscape(_))), "{read:?}");
1344        assert!(matches!(write, Err(DevToolError::PathEscape(_))), "{write:?}");
1345        assert!(!f.outside.join("new.md").exists(), "the write landed outside the root");
1346    }
1347
1348    #[cfg(any(unix, windows))]
1349    #[tokio::test]
1350    async fn a_missing_directory_planted_as_a_link_after_the_check_is_not_followed() {
1351        let f = swap_fixture();
1352        let ws = Workspace::new(&f.root);
1353        let (_, target) = ws.resolve_target("build/out/report.md").unwrap();
1354        link(&f.outside, &f.root.join("build")).unwrap();
1355
1356        let result = ws.write_contained(&target, b"planted", Precondition::Any).await;
1357
1358        assert!(matches!(result, Err(DevToolError::PathEscape(_))), "{result:?}");
1359        assert!(!f.outside.join("out").exists(), "a directory was created outside the root");
1360    }
1361
1362    #[cfg(any(unix, windows))]
1363    #[tokio::test]
1364    async fn the_checked_target_is_read_and_written_through_an_inside_link() {
1365        let f = swap_fixture();
1366        let Some(()) = link(&f.root.join("notes.md"), &f.root.join("alias.md")) else { return };
1367        let ws = Workspace::new(&f.root);
1368        let (lexical, target) = ws.resolve_target("alias.md").unwrap();
1369        assert_eq!(lexical, ws.root().join("alias.md"));
1370        assert_eq!(target, ws.root().join("notes.md"));
1371
1372        assert_eq!(ws.read_contained(&target).await.unwrap(), "notes");
1373        ws.write_contained(&target, b"updated", Precondition::Any).await.unwrap();
1374        assert_eq!(std::fs::read_to_string(f.root.join("notes.md")).unwrap(), "updated");
1375        let (_, created) = ws.resolve_target("new/dir/file.md").unwrap();
1376        ws.write_contained(&created, b"made", Precondition::Any).await.unwrap();
1377        assert_eq!(std::fs::read_to_string(f.root.join("new/dir/file.md")).unwrap(), "made");
1378    }
1379
1380    #[cfg(any(unix, windows))]
1381    #[tokio::test]
1382    async fn a_file_with_more_than_one_hard_link_is_not_read() {
1383        let f = swap_fixture();
1384        std::fs::hard_link(f.outside.join("secret.txt"), f.root.join("linked.txt")).unwrap();
1385        let ws = Workspace::new(&f.root);
1386        let (_, target) = ws.resolve_target("linked.txt").unwrap();
1387
1388        let result = ws.read_contained(&target).await;
1389
1390        let Err(DevToolError::Other(message)) = result else {
1391            panic!("a hard-linked file was read: {result:?}");
1392        };
1393        assert!(message.contains("2 hard links"), "{message}");
1394    }
1395
1396    #[cfg(windows)]
1397    #[tokio::test]
1398    async fn a_directory_swapped_for_a_directory_symlink_after_the_check_is_not_followed() {
1399        // `link` makes a junction for a directory; a directory symlink carries the other
1400        // name-surrogate tag.
1401        let f = swap_fixture();
1402        let ws = Workspace::new(&f.root);
1403        let (_, read_target) = ws.resolve_target("docs/guide.md").unwrap();
1404        let (_, write_target) = ws.resolve_target("docs/new.md").unwrap();
1405        let docs = f.root.join("docs");
1406        let staged = docs.with_extension("swap");
1407        let Some(()) = privileged(std::os::windows::fs::symlink_dir(&f.outside, &staged)) else {
1408            return;
1409        };
1410        std::fs::rename(&docs, docs.with_extension("moved")).unwrap();
1411        std::fs::rename(&staged, &docs).unwrap();
1412
1413        let read = ws.read_contained(&read_target).await;
1414        let write = ws.write_contained(&write_target, b"planted", Precondition::Any).await;
1415
1416        assert!(matches!(read, Err(DevToolError::PathEscape(_))), "{read:?}");
1417        assert!(matches!(write, Err(DevToolError::PathEscape(_))), "{write:?}");
1418        assert!(!f.outside.join("new.md").exists(), "the write landed outside the root");
1419    }
1420
1421    /// A WOF-compressed file is backed by `IO_REPARSE_TAG_WOF`, an in-place tag like a
1422    /// cloud placeholder's. A real placeholder needs a cloud sync provider registered and
1423    /// connected through the Cloud Filter API, which a unit test cannot stand up. WOF hides
1424    /// the reparse point from the handle, so the read and write take the ordinary path.
1425    #[cfg(windows)]
1426    #[tokio::test]
1427    async fn an_in_place_reparse_point_is_read_and_written() {
1428        use std::os::windows::ffi::OsStrExt as _;
1429        use windows_sys::Win32::Storage::FileSystem::{WOF_PROVIDER_FILE, WofIsExternalFile};
1430
1431        let f = swap_fixture();
1432        let packed = f.root.join("packed.txt");
1433        let text = "an in-place reparse point keeps its data with its filter\n".repeat(32_768);
1434        std::fs::write(&packed, &text).unwrap();
1435        let compact = std::process::Command::new("compact.exe")
1436            .args(["/C", "/EXE:XPRESS4K"])
1437            .arg(&packed)
1438            .output()
1439            .unwrap();
1440        // Whether the file is WOF-backed is asked of WOF itself.
1441        let wide: Vec<u16> = packed.as_os_str().encode_wide().chain(Some(0)).collect();
1442        let (mut external, mut provider) = (0, 0);
1443        // SAFETY: `wide` is NUL-terminated and the out-pointers are writable; no file
1444        // information is requested.
1445        let asked = unsafe {
1446            WofIsExternalFile(
1447                wide.as_ptr(),
1448                &raw mut external,
1449                &raw mut provider,
1450                std::ptr::null_mut(),
1451                std::ptr::null_mut(),
1452            )
1453        };
1454        assert!(
1455            asked >= 0 && external != 0 && provider == WOF_PROVIDER_FILE,
1456            "compact did not back the file with WOF: {}",
1457            String::from_utf8_lossy(&compact.stdout)
1458        );
1459        let ws = Workspace::new(&f.root);
1460        let (_, target) = ws.resolve_target("packed.txt").unwrap();
1461
1462        assert_eq!(ws.read_contained(&target).await.unwrap(), text);
1463        ws.write_contained(&target, b"rewritten", Precondition::Any).await.unwrap();
1464
1465        assert_eq!(std::fs::read_to_string(&packed).unwrap(), "rewritten");
1466    }
1467
1468    /// Sets a reparse point on the file `path` whose tag no filter on the volume serves: a
1469    /// third-party tag, neither a link nor a junction, whose file keeps its own data.
1470    /// Returns the tag.
1471    #[cfg(windows)]
1472    fn set_unserved_reparse_point(path: &Path) -> u32 {
1473        use std::os::windows::fs::OpenOptionsExt as _;
1474        use std::os::windows::io::AsRawHandle as _;
1475        use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
1476        use windows_sys::Win32::System::IO::DeviceIoControl;
1477        use windows_sys::Win32::System::Ioctl::FSCTL_SET_REPARSE_POINT;
1478
1479        // Bit 31 clear: not a Microsoft tag, so its buffer carries a GUID. Bit 29 clear: not
1480        // a name surrogate.
1481        const TAG: u32 = 0x0000_7ADC;
1482        let file = std::fs::OpenOptions::new()
1483            .write(true)
1484            .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
1485            .open(path)
1486            .unwrap();
1487        // REPARSE_GUID_DATA_BUFFER: the tag, the data's length, two reserved bytes, the
1488        // owner's GUID, then the data.
1489        let data = b"adk-devtools test placeholder";
1490        let mut buffer = Vec::new();
1491        buffer.extend_from_slice(&TAG.to_le_bytes());
1492        buffer.extend_from_slice(&(data.len() as u16).to_le_bytes());
1493        buffer.extend_from_slice(&[0, 0]);
1494        buffer.extend_from_slice(&[0x41; 16]);
1495        buffer.extend_from_slice(data);
1496        let mut returned = 0u32;
1497        // SAFETY: the handle is open; the input buffer is readable for its length; there is
1498        // no output buffer, and `returned` is writable.
1499        let set = unsafe {
1500            DeviceIoControl(
1501                file.as_raw_handle(),
1502                FSCTL_SET_REPARSE_POINT,
1503                buffer.as_ptr().cast(),
1504                buffer.len() as u32,
1505                std::ptr::null_mut(),
1506                0,
1507                &raw mut returned,
1508                std::ptr::null_mut(),
1509            )
1510        };
1511        assert_ne!(set, 0, "FSCTL_SET_REPARSE_POINT failed: {}", std::io::Error::last_os_error());
1512        TAG
1513    }
1514
1515    /// The reparse tag a handle opened on `path` itself reports, `None` for no reparse point.
1516    #[cfg(windows)]
1517    fn visible_reparse_tag(path: &Path) -> Option<u32> {
1518        use std::os::windows::fs::OpenOptionsExt as _;
1519        use std::os::windows::io::AsRawHandle as _;
1520        use windows_sys::Win32::Storage::FileSystem::{
1521            FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_TAG_INFO, FILE_FLAG_OPEN_REPARSE_POINT,
1522            FileAttributeTagInfo, GetFileInformationByHandleEx,
1523        };
1524
1525        let file = std::fs::OpenOptions::new()
1526            .read(true)
1527            .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
1528            .open(path)
1529            .unwrap();
1530        let mut tag = FILE_ATTRIBUTE_TAG_INFO::default();
1531        // SAFETY: `tag` is writable and the size passed is its own; the handle is open.
1532        let queried = unsafe {
1533            GetFileInformationByHandleEx(
1534                file.as_raw_handle(),
1535                FileAttributeTagInfo,
1536                (&raw mut tag).cast(),
1537                size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
1538            )
1539        };
1540        assert_ne!(queried, 0, "{}", std::io::Error::last_os_error());
1541        (tag.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0).then_some(tag.ReparseTag)
1542    }
1543
1544    /// An in-place reparse point the handle shows — neither a link nor a junction — passes
1545    /// the open's checks, and the file tools read and write its content through a reopen of
1546    /// the handle without `FILE_FLAG_OPEN_REPARSE_POINT`, which the tag's filter serves (spec
1547    /// 3.2 §10 W6). WOF hides its tag from the handle, so the test above takes the ordinary
1548    /// path; a third-party tag stays visible. No filter serves it, so the reopen fails: the
1549    /// read is refused and the write leaves the content in place rather than truncate it.
1550    #[cfg(windows)]
1551    #[tokio::test]
1552    async fn an_unserved_in_place_reparse_point_fails_closed_at_the_reopen() {
1553        use std::io::Read as _;
1554        use std::os::windows::fs::OpenOptionsExt as _;
1555        use windows_sys::Win32::Foundation::ERROR_STOPPED_ON_SYMLINK;
1556        use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
1557
1558        let f = swap_fixture();
1559        let path = f.root.join("placeholder.txt");
1560        std::fs::write(&path, "placeholder content").unwrap();
1561        let tag = set_unserved_reparse_point(&path);
1562        assert_eq!(visible_reparse_tag(&path), Some(tag), "the handle shows the tag");
1563        assert!(!crate::beneath::is_name_surrogate(tag));
1564        let ws = Workspace::new(&f.root);
1565        // `resolve_target` canonicalizes the path, which opens through the point and fails;
1566        // the tools open the canonical target it returns for an ordinary file.
1567        let target = ws.root().join("placeholder.txt");
1568
1569        let read = ws.read_contained(&target).await;
1570        let write = ws.write_contained(&target, b"rewritten", Precondition::Any).await;
1571
1572        // An `Io` error other than the link refusal: the open passed its checks, and the
1573        // reopen through the unserved tag failed.
1574        let stopped = Some(ERROR_STOPPED_ON_SYMLINK as i32);
1575        assert!(
1576            matches!(&read, Err(DevToolError::Io(error)) if error.raw_os_error() != stopped),
1577            "{read:?}"
1578        );
1579        assert!(
1580            matches!(&write, Err(DevToolError::Io(error)) if error.raw_os_error() != stopped),
1581            "{write:?}"
1582        );
1583        let mut content = String::new();
1584        std::fs::OpenOptions::new()
1585            .read(true)
1586            .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
1587            .open(&path)
1588            .unwrap()
1589            .read_to_string(&mut content)
1590            .unwrap();
1591        assert_eq!(content, "placeholder content", "the refused write truncated the file");
1592    }
1593
1594    /// A tool context that names a session and an agent.
1595    struct ScopeCtx {
1596        session: String,
1597        agent: String,
1598    }
1599
1600    impl ScopeCtx {
1601        fn new(session: &str, agent: &str) -> Self {
1602            Self { session: session.to_string(), agent: agent.to_string() }
1603        }
1604    }
1605
1606    #[async_trait::async_trait]
1607    impl adk_core::ReadonlyContext for ScopeCtx {
1608        fn invocation_id(&self) -> &str {
1609            "invocation"
1610        }
1611        fn agent_name(&self) -> &str {
1612            &self.agent
1613        }
1614        fn user_id(&self) -> &str {
1615            "user"
1616        }
1617        fn app_name(&self) -> &str {
1618            "app"
1619        }
1620        fn session_id(&self) -> &str {
1621            &self.session
1622        }
1623        fn branch(&self) -> &str {
1624            ""
1625        }
1626        fn user_content(&self) -> &adk_core::Content {
1627            static CONTENT: std::sync::OnceLock<adk_core::Content> = std::sync::OnceLock::new();
1628            CONTENT.get_or_init(|| adk_core::Content::new("user").with_text("hi"))
1629        }
1630    }
1631
1632    #[async_trait::async_trait]
1633    impl adk_core::CallbackContext for ScopeCtx {
1634        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
1635            None
1636        }
1637    }
1638
1639    #[async_trait::async_trait]
1640    impl ToolContext for ScopeCtx {
1641        fn function_call_id(&self) -> &str {
1642            "call"
1643        }
1644        fn actions(&self) -> adk_core::EventActions {
1645            adk_core::EventActions::default()
1646        }
1647        fn set_actions(&self, _actions: adk_core::EventActions) {}
1648        async fn search_memory(
1649            &self,
1650            _query: &str,
1651        ) -> adk_core::Result<Vec<adk_core::MemoryEntry>> {
1652            Ok(vec![])
1653        }
1654    }
1655
1656    #[tokio::test]
1657    async fn read_tracking() {
1658        let dir = tempfile::tempdir().unwrap();
1659        let ws = Workspace::new(dir.path());
1660        let ctx = ScopeCtx::new("session", "agent");
1661        let p = ws.resolve("a.txt").unwrap();
1662        assert_eq!(ws.read_digest(&ctx, &p).await.unwrap(), None);
1663        ws.record_digest(&ctx, &p, "d1").await;
1664        assert_eq!(ws.read_digest(&ctx, &p).await.unwrap().as_deref(), Some("d1"));
1665        ws.forget_read(&ctx, &p).await;
1666        assert_eq!(ws.read_digest(&ctx, &p).await.unwrap(), None);
1667    }
1668
1669    #[tokio::test]
1670    async fn clones_keep_reads_apart_by_session_and_agent() {
1671        let dir = tempfile::tempdir().unwrap();
1672        let ws = Workspace::new(dir.path());
1673        let other = ws.clone();
1674        let p = ws.resolve("a.txt").unwrap();
1675
1676        ws.record_digest(&ScopeCtx::new("one", "coder"), &p, "d1").await;
1677
1678        let seen = |session: &str, agent: &str| {
1679            let (other, p, ctx) = (other.clone(), p.clone(), ScopeCtx::new(session, agent));
1680            async move { other.read_digest(&ctx, &p).await.unwrap() }
1681        };
1682        assert_eq!(seen("one", "coder").await.as_deref(), Some("d1"), "clones share a scope");
1683        assert_eq!(seen("two", "coder").await, None, "another session read it");
1684        assert_eq!(seen("one", "reviewer").await, None, "another agent read it");
1685    }
1686
1687    #[tokio::test]
1688    async fn calls_without_a_session_share_one_record() {
1689        let dir = tempfile::tempdir().unwrap();
1690        let ws = Workspace::new(dir.path());
1691        let p = ws.resolve("a.txt").unwrap();
1692
1693        ws.record_digest(&ScopeCtx::new("", "first"), &p, "d1").await;
1694
1695        let unscoped = ws.clone().read_digest(&ScopeCtx::new("", "second"), &p).await.unwrap();
1696        assert_eq!(unscoped.as_deref(), Some("d1"));
1697        assert_eq!(ws.read_digest(&ScopeCtx::new("session", "first"), &p).await.unwrap(), None);
1698    }
1699
1700    #[tokio::test]
1701    async fn the_least_recently_used_scope_is_evicted_at_capacity() {
1702        use crate::read_ledger::READ_SCOPE_CAPACITY;
1703
1704        let dir = tempfile::tempdir().unwrap();
1705        let ledger = Arc::new(InMemoryReadLedger::new());
1706        let ws = Workspace::new(dir.path()).with_read_ledger(ledger.clone());
1707        let p = ws.resolve("a.txt").unwrap();
1708        for session in 0..READ_SCOPE_CAPACITY {
1709            ws.record_digest(&ScopeCtx::new(&format!("s{session}"), "agent"), &p, "d").await;
1710        }
1711        // Touch the oldest scope so the second oldest is the one evicted.
1712        assert!(ws.read_digest(&ScopeCtx::new("s0", "agent"), &p).await.unwrap().is_some());
1713
1714        ws.record_digest(&ScopeCtx::new("newest", "agent"), &p, "d").await;
1715
1716        assert!(
1717            ws.read_digest(&ScopeCtx::new("s0", "agent"), &p).await.unwrap().is_some(),
1718            "a recently used scope was evicted"
1719        );
1720        assert!(
1721            ws.read_digest(&ScopeCtx::new("s1", "agent"), &p).await.unwrap().is_none(),
1722            "the oldest scope was kept"
1723        );
1724        assert_eq!(ledger.scopes(), READ_SCOPE_CAPACITY);
1725    }
1726
1727    #[test]
1728    fn record_paths_use_forward_slashes_relative_to_the_root() {
1729        let dir = tempfile::tempdir().unwrap();
1730        let ws = Workspace::new(dir.path());
1731        let p = ws.resolve("src/nested/a.rs").unwrap();
1732        assert_eq!(ws.record_path(&p), "src/nested/a.rs");
1733    }
1734
1735    #[cfg(any(unix, windows))]
1736    #[tokio::test]
1737    async fn a_write_checks_its_precondition_on_the_file_it_writes() {
1738        let dir = tempfile::tempdir().unwrap();
1739        let ws = Workspace::new(dir.path());
1740        std::fs::write(dir.path().join("a.txt"), "one").unwrap();
1741        let (_, target) = ws.resolve_target("a.txt").unwrap();
1742        let one = crate::read_ledger::sha256_hex(b"one");
1743
1744        let stale = ws
1745            .write_contained(
1746                &target,
1747                b"two",
1748                Precondition::Sha256(crate::read_ledger::sha256_hex(b"x")),
1749            )
1750            .await;
1751        assert!(matches!(&stale, Err(DevToolError::Stale { .. })), "{stale:?}");
1752        assert_eq!(std::fs::read_to_string(dir.path().join("a.txt")).unwrap(), "one");
1753
1754        ws.write_contained(&target, b"two", Precondition::Sha256(one.clone())).await.unwrap();
1755        assert_eq!(std::fs::read_to_string(dir.path().join("a.txt")).unwrap(), "two");
1756
1757        let exists = ws.write_contained(&target, b"three", Precondition::Absent).await;
1758        assert!(matches!(&exists, Err(DevToolError::Stale { .. })), "{exists:?}");
1759        let (_, fresh) = ws.resolve_target("fresh.txt").unwrap();
1760        let missing = ws.write_contained(&fresh, b"x", Precondition::Sha256(one)).await;
1761        assert!(matches!(&missing, Err(DevToolError::Stale { .. })), "{missing:?}");
1762        assert!(!dir.path().join("fresh.txt").exists(), "a stale write creates nothing");
1763        ws.write_contained(&fresh, b"x", Precondition::Absent).await.unwrap();
1764        assert_eq!(std::fs::read_to_string(dir.path().join("fresh.txt")).unwrap(), "x");
1765    }
1766
1767    #[cfg(any(unix, windows))]
1768    #[tokio::test]
1769    async fn replace_and_remove_check_their_precondition() {
1770        let dir = tempfile::tempdir().unwrap();
1771        let ws = Workspace::new(dir.path());
1772        std::fs::write(dir.path().join("a.txt"), "one").unwrap();
1773        let (_, target) = ws.resolve_target("a.txt").unwrap();
1774        let one = crate::read_ledger::sha256_hex(b"one");
1775
1776        let stale = ws.replace_contained(&target, b"two", Precondition::Absent).await;
1777        assert!(matches!(&stale, Err(DevToolError::Stale { .. })), "{stale:?}");
1778        ws.replace_contained(&target, b"two", Precondition::Sha256(one.clone())).await.unwrap();
1779        assert_eq!(std::fs::read_to_string(dir.path().join("a.txt")).unwrap(), "two");
1780
1781        let stale = ws.remove_contained(&target, Precondition::Sha256(one)).await;
1782        assert!(matches!(&stale, Err(DevToolError::Stale { .. })), "{stale:?}");
1783        let two = crate::read_ledger::sha256_hex(b"two");
1784        ws.remove_contained(&target, Precondition::Sha256(two)).await.unwrap();
1785        assert!(!dir.path().join("a.txt").exists());
1786        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "no temporary file is left");
1787    }
1788
1789    #[test]
1790    fn expect_sha256_takes_a_digest_or_absent() {
1791        let digest = "A".repeat(64);
1792        assert_eq!(
1793            Precondition::from_expect(&digest).unwrap(),
1794            Precondition::Sha256("a".repeat(64))
1795        );
1796        assert_eq!(
1797            Precondition::from_expect(&format!("sha256:{digest}")).unwrap(),
1798            Precondition::Sha256("a".repeat(64))
1799        );
1800        assert_eq!(Precondition::from_expect("absent").unwrap(), Precondition::Absent);
1801        assert!(Precondition::from_expect("abc").is_err());
1802    }
1803
1804    #[test]
1805    fn secret_patterns_are_excluded_by_default() {
1806        let dir = tempfile::tempdir().unwrap();
1807        let ws = Workspace::new(dir.path());
1808        for secret in [
1809            ".env",
1810            "config/.env",
1811            ".env.production",
1812            "certs/server.pem",
1813            "tls.KEY",
1814            ".ssh/id_rsa",
1815            "keys/id_rsa.pub",
1816            "id_ed25519",
1817            "bundle.p12",
1818            "bundle.pfx",
1819            ".ENV",
1820        ] {
1821            assert!(ws.is_excluded(Path::new(secret)), "{secret} was not excluded");
1822            assert!(ws.is_excluded(&dir.path().join(secret)), "absolute {secret} was not excluded");
1823        }
1824        for ordinary in ["src/main.rs", "environment.md", "keys.rs", "README.md", ".envrc"] {
1825            assert!(!ws.is_excluded(Path::new(ordinary)), "{ordinary} was excluded");
1826        }
1827    }
1828
1829    #[test]
1830    fn exclusion_patterns_can_be_replaced_or_cleared() {
1831        let dir = tempfile::tempdir().unwrap();
1832        let custom = Workspace::new(dir.path()).exclude_globs(["secrets/**".to_string()]);
1833        assert!(custom.is_excluded(Path::new("secrets/prod/token.txt")));
1834        assert!(!custom.is_excluded(Path::new(".env")));
1835
1836        let cleared = Workspace::new(dir.path()).exclude_globs([]);
1837        assert!(!cleared.is_excluded(Path::new(".env")));
1838
1839        let literal = Workspace::new(dir.path()).exclude_globs(["[unclosed".to_string()]);
1840        assert!(literal.is_excluded(Path::new("dir/[unclosed")));
1841    }
1842}