rpi-tools 0.34.0

Built-in agent tools (read/write/edit/bash/powershell) + ExecutionEnv, Rust port of pi harness tools
Documentation
//! Mirrors `packages/agent/src/harness/tools/file-mutation-queue.ts` — serializes
//! file-mutating operations per canonical path so concurrent edits to the same
//! path (or a symlink + its target) don't interleave.
//!
//! The TS uses a `WeakMap<ExecutionEnv, MutationQueueState>` keyed by env
//! instance. Rust has no per-instance map keyed by trait object, so each env
//! impl carries an `Arc<MutationQueueRegistry>` field and exposes it via the
//! [`MutatingEnv`] accessor trait. The mutation-dependent tools (write, edit)
//! hold `Arc<dyn MutatingEnv>`; read and bash don't need it.
//!
//! Cancellation while waiting preserves the queue order. A caller cancelled while waiting still acquires the lock and enters `fn`
//! with the cancelled token. The guard stays held until `fn` settles.

use std::collections::HashMap;
use std::sync::Arc;

use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;

use crate::env::ExecutionEnv;
use crate::error::{FileError, FileErrorCode};

/// Per-env registry of canonical-path → mutex. Stored as a field on each env
/// impl (behind `Arc` so clones share the same map).
#[derive(Default)]
pub struct MutationQueueRegistry {
    queues: Mutex<HashMap<String, Arc<Mutex<()>>>>,
}

impl MutationQueueRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Get (or lazily create) the mutex for `key`. The key is a canonical path
    /// string (from [`get_mutation_queue_key`]).
    async fn mutex_for(&self, key: &str) -> Arc<Mutex<()>> {
        let mut map = self.queues.lock().await;
        if let Some(m) = map.get(key) {
            m.clone()
        } else {
            let m = Arc::new(Mutex::new(()));
            map.insert(key.to_string(), m.clone());
            m
        }
    }
}

/// Accessor used by [`with_file_mutation_queue`] to reach the env's registry
/// AND its `ExecutionEnv` methods. Concrete env impls (`OsExecutionEnv`,
/// `InMemoryExecutionEnv`) implement this; the write/edit tools hold
/// `Arc<dyn MutatingEnv>`.
///
/// The `as_env` indirection avoids needing trait-upcasting (`dyn MutatingEnv`
/// → `dyn ExecutionEnv`, unstable before Rust 1.86); our min rust-version is
/// 1.78, so we expose the env explicitly.
pub trait MutatingEnv: Send + Sync {
    /// The underlying `ExecutionEnv` (for `FileSystem`/`Shell` calls).
    fn as_env(&self) -> &dyn ExecutionEnv;

    /// The registry holding per-canonical-path mutexes.
    fn mutation_registry(&self) -> &MutationQueueRegistry;
}

/// Compute the canonical-path queue key. A missing destination inherits the
/// canonical path of its nearest resolvable ancestor, so a create and a later
/// overwrite use the same queue even through a directory alias. Backends
/// without canonical paths fall back to their absolute paths.
pub async fn get_mutation_queue_key(
    env: &dyn ExecutionEnv,
    path: &str,
    cancel: Option<&CancellationToken>,
) -> Result<String, FileError> {
    let absolute = env.absolute_path(path, cancel).await?;
    let abs_str = absolute.to_string_lossy();
    match env.canonical_path(&abs_str, cancel).await {
        Ok(canonical) => return Ok(canonical.to_string_lossy().into_owned()),
        Err(e) if e.code == FileErrorCode::NotSupported => return Ok(abs_str.into_owned()),
        Err(e) if e.code == FileErrorCode::NotFound => {}
        Err(e) => return Err(e),
    }

    for ancestor in absolute.ancestors().skip(1) {
        match env
            .canonical_path(&ancestor.to_string_lossy(), cancel)
            .await
        {
            Ok(canonical) => {
                if let Ok(suffix) = absolute.strip_prefix(ancestor) {
                    return Ok(canonical.join(suffix).to_string_lossy().into_owned());
                }
                break;
            }
            Err(e) if e.code == FileErrorCode::NotFound => continue,
            Err(e) if e.code == FileErrorCode::Aborted => return Err(e),
            // Preserve the absolute fallback when an ancestor cannot be
            // resolved. The mutation will report any actual filesystem error.
            Err(_) => break,
        }
    }
    Ok(abs_str.into_owned())
}

/// Serialize `fn` per canonical-path key for `env`. The closure `f` runs while
/// holding the per-key `tokio::Mutex` guard; abort/cancel during the wait does
/// NOT skip the queue — `f` itself must observe the token and return
/// `Err(FileError::aborted())`.
///
/// The closure receives the cancellation token and holds the per-path guard
/// until the mutation settles.
pub async fn with_file_mutation_queue<F, R>(
    env: &dyn MutatingEnv,
    path: &str,
    cancel: &CancellationToken,
    f: F,
) -> Result<R, FileError>
where
    F: for<'a> FnOnce(
        &'a CancellationToken,
    ) -> futures::future::BoxFuture<'a, Result<R, FileError>>,
    R: Send + 'static,
{
    let key = get_mutation_queue_key(env.as_env(), path, Some(cancel)).await?;
    let mutex = env.mutation_registry().mutex_for(&key).await;
    // Acquisition of the per-key lock is NOT cancelable — we always wait for
    // our turn. `tokio::Mutex::lock` is a safe `.await` here.
    let _guard = mutex.lock().await;
    // Now that we hold the lock, run `f`. It may observe cancellation and
    // return Err(Aborted); the guard drops on return, releasing the next
    // waiter. Unwinding (if `f` panics) also drops the guard — but tool/env
    // code must never panic (plan §5.13).
    f(cancel).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(unix)]
    #[tokio::test]
    async fn missing_destination_shares_queue_through_directory_alias() {
        let temp = tempfile::tempdir().unwrap();
        let real = temp.path().join("real");
        std::fs::create_dir(&real).unwrap();
        std::os::unix::fs::symlink(&real, temp.path().join("alias")).unwrap();
        let env = crate::OsExecutionEnv::with_cwd(temp.path().to_path_buf());

        let alias_key = get_mutation_queue_key(&env, "alias/sub/new.txt", None)
            .await
            .unwrap();
        let real_key = get_mutation_queue_key(&env, "real/sub/new.txt", None)
            .await
            .unwrap();

        std::fs::create_dir(real.join("sub")).unwrap();
        std::fs::write(real.join("sub/new.txt"), "written").unwrap();
        let existing_key = get_mutation_queue_key(&env, "alias/sub/new.txt", None)
            .await
            .unwrap();

        assert_eq!(alias_key, real_key);
        assert_eq!(alias_key, existing_key);
    }

    #[tokio::test]
    async fn missing_destination_keeps_queue_key_when_created() {
        let temp = tempfile::tempdir().unwrap();
        let env = crate::OsExecutionEnv::with_cwd(temp.path().to_path_buf());
        let before = get_mutation_queue_key(&env, "sub/new.txt", None)
            .await
            .unwrap();

        std::fs::create_dir(temp.path().join("sub")).unwrap();
        std::fs::write(temp.path().join("sub/new.txt"), "written").unwrap();
        let after = get_mutation_queue_key(&env, "sub/new.txt", None)
            .await
            .unwrap();

        assert_eq!(before, after);
    }

    #[tokio::test]
    async fn registry_creates_and_reuses_mutex() {
        let reg = MutationQueueRegistry::new();
        let m1 = reg.mutex_for("/a/b").await;
        let m2 = reg.mutex_for("/a/b").await;
        assert!(Arc::ptr_eq(&m1, &m2));
        let m3 = reg.mutex_for("/c").await;
        assert!(!Arc::ptr_eq(&m1, &m3));
    }
}