rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Rewinding a workspace to a checkpoint: the steps every host of a
//! session shares, over the workspace its tools write through, and how the
//! result reads.
//!
//! A rewind undoes the picked turn and every later turn on the
//! conversation's current path as one plan. A checkpoint
//! path is restored only where the workspace would let a tool write it now,
//! and is checked again right before each write.

use std::{
    collections::{BTreeMap, HashMap},
    path::{Path, PathBuf},
};

use rho_sdk::Workspace;

use crate::session::{
    tree::{NodeId, SessionTree},
    workspace_checkpoint::{
        plan_restore, AuditResult, FileCheckpoint, ObservedFileState, RestoreAudit,
        RestoreClassification, RestorePlan, RewoundTurns, UnsupportedPath, UntrackedEffectKind,
        WorkspaceCheckpoint, WorkspaceCheckpointStore,
    },
};

/// A rewind of a turn and every later turn on the conversation's current
/// path, planned against the workspace as it is.
pub(crate) struct PlannedRewind {
    pub(crate) turns: RewoundTurns,
    /// The conversation's current node, the branch's tip, that the plan was
    /// made against.
    pub(crate) tip: NodeId,
    /// What each of the turns' paths held when the plan was made.
    current: BTreeMap<PathBuf, ObservedFileState>,
    pub(crate) plan: RestorePlan,
}

/// Why [`PlannedRewind::new`] planned nothing.
#[derive(Debug, thiserror::Error)]
pub(crate) enum PlanRewindError {
    #[error("workspace checkpoint '{0}' was not found")]
    NotFound(NodeId),
    /// Its turn is not in the conversation a rewind would undo.
    #[error("workspace checkpoint '{0}' is not on the conversation's current branch")]
    OffBranch(NodeId),
    #[error("could not rewind workspace: checkpoint predates rewind boundaries")]
    NoBoundary,
    /// The checkpoints or the session's tree could not be read.
    #[error(transparent)]
    Failed(#[from] anyhow::Error),
}

impl PlanRewindError {
    /// Whether the requester asked for a rewind that cannot be, rather
    /// than one that failed.
    pub(crate) fn refused(&self) -> bool {
        match self {
            Self::NotFound(_) | Self::OffBranch(_) | Self::NoBoundary => true,
            Self::Failed(_) => false,
        }
    }
}

impl PlannedRewind {
    /// Plans the rewind of checkpoint `target` in `store` and of every
    /// later checkpoint on `tree`'s current branch; nothing is written.
    pub(crate) fn new(
        store: &WorkspaceCheckpointStore,
        workspace: &Workspace,
        target: &NodeId,
        tree: &SessionTree,
    ) -> Result<Self, PlanRewindError> {
        let path = tree.active_path()?;
        let place: HashMap<&NodeId, usize> = path
            .iter()
            .enumerate()
            .map(|(at, node)| (node.id(), at))
            .collect();
        let from = place.get(target).copied();
        let read = store.select(|summary| {
            from.is_some_and(|from| place.get(&summary.node_id).is_some_and(|&at| at >= from))
        })?;
        let Some(from) = from else {
            return Err(
                if read.listed.iter().any(|summary| &summary.node_id == target) {
                    PlanRewindError::OffBranch(target.clone())
                } else {
                    PlanRewindError::NotFound(target.clone())
                },
            );
        };
        let mut turns = read.selected;
        turns.sort_by_key(|turn| place.get(&turn.node_id).copied());
        let mut turns = turns.into_iter();
        let first = turns
            .next()
            .filter(|first| &first.node_id == target)
            .ok_or_else(|| PlanRewindError::NotFound(target.clone()))?;
        // Each checkpoint covers its turn's nodes on the path: those after
        // the node its turn began at, up to the one it ended on.
        let covered = |at: usize, turn: &WorkspaceCheckpoint| {
            let began = turn
                .before_node_id
                .as_ref()
                .and_then(|before| place.get(before));
            began.is_none_or(|&began| began < at)
                && place.get(&turn.node_id).is_some_and(|&end| at <= end)
        };
        let later: Vec<_> = turns.collect();
        // A turn ended on each node that records how; one no checkpoint
        // covers took none, as when capture paused.
        let uncaptured = path
            .iter()
            .enumerate()
            .skip(from + 1)
            .filter(|(at, node)| {
                node.turn_end().is_some() && !later.iter().any(|turn| covered(*at, turn))
            })
            .count();
        let turns =
            RewoundTurns::combine(first, later, uncaptured).ok_or(PlanRewindError::NoBoundary)?;
        let current = turns
            .paths()
            .map(|path| (path.to_path_buf(), observe(store, workspace, path)))
            .collect();
        let plan = plan_restore(&turns, &current)?;
        Ok(Self {
            turns,
            // The target is on the active path, which ends at the leaf.
            tip: tree
                .active_leaf_id()
                .cloned()
                .ok_or_else(|| PlanRewindError::NotFound(target.clone()))?,
            current,
            plan,
        })
    }

    /// Restores the planned paths, each checked against the plan again
    /// before its write. Fails before any write when the workspace no
    /// longer lets a planned path be written.
    pub(crate) fn restore(
        &self,
        store: &WorkspaceCheckpointStore,
        workspace: &Workspace,
    ) -> anyhow::Result<RestoreAudit> {
        for entry in &self.plan.entries {
            match entry.classification {
                RestoreClassification::Create
                | RestoreClassification::Modify
                | RestoreClassification::Delete => writable(workspace, &entry.path)?,
                RestoreClassification::Conflict
                | RestoreClassification::Unsupported
                | RestoreClassification::Skipped => {}
            }
        }
        Ok(store.restore(
            &self.turns,
            &self.current,
            |path| observe(store, workspace, path),
            |file: &FileCheckpoint, classification| {
                writable(workspace, &file.path)?;
                store.apply_restore(file, classification)
            },
        ))
    }
}

/// Whether `plan` would restore every path it covers or leave it as it
/// needs: what [`restored_fully`] then finds, unless a path changes, or
/// fails to write, in between.
pub(crate) fn plans_full_restore(plan: &RestorePlan) -> bool {
    !plan
        .entries
        .iter()
        .any(|entry| entry.classification.leaves_path())
}

/// Whether every path `audit` covers was restored or needed nothing.
pub(crate) fn restored_fully(audit: &RestoreAudit) -> bool {
    !audit
        .entries
        .iter()
        .any(|entry| entry.error.is_some() || entry.classification.leaves_path())
}

/// Fails unless `workspace` lets a tool write `path` as it is spelled.
fn writable(workspace: &Workspace, path: &Path) -> anyhow::Result<()> {
    let resolved = workspace.resolve_for_write(path)?;
    anyhow::ensure!(
        resolved.path() == path,
        "checkpoint path '{}' resolves to a different workspace path",
        path.display()
    );
    workspace.revalidate(&resolved)?;
    Ok(())
}

fn observe(
    store: &WorkspaceCheckpointStore,
    workspace: &Workspace,
    path: &Path,
) -> ObservedFileState {
    match writable(workspace, path) {
        Ok(()) => store.observe_path(path),
        Err(_) => ObservedFileState::Unsupported {
            reason: UnsupportedPath::Unreadable,
        },
    }
}

pub(crate) fn rewind_audit_text(
    audit: &RestoreAudit,
    workspace: &Path,
    conversation_selected: bool,
) -> String {
    let mut lines = vec![if conversation_selected {
        "workspace rewind audit; conversation restored to before the turn".into()
    } else {
        "workspace rewind audit; conversation state was not selected".into()
    }];
    for entry in &audit.entries {
        let result = match entry.result() {
            AuditResult::Written => "restored",
            AuditResult::Left => "skipped",
            AuditResult::Failed(error) => error,
        };
        lines.push(format!(
            "{}  {}  {result}",
            classification_label(entry.classification),
            rho_tools::compact_display_path(workspace, &entry.path.to_string_lossy())
        ));
    }
    if let Some(line) = uncaptured_line(audit.uncaptured_turns) {
        lines.push(line);
    }
    for limitation in &audit.limitations {
        lines.push(format!(
            "warning  {} effects from '{}' were not restored",
            limitation_label(&limitation.kind),
            limitation.source
        ));
    }
    lines.join("\n")
}

/// The warning that `turns` later turns took no checkpoint, when any did.
pub(crate) fn uncaptured_line(turns: usize) -> Option<String> {
    (turns > 0).then(|| {
        format!(
            "warning  {turns} later turn(s) took no workspace checkpoint; their file changes stay"
        )
    })
}

/// Names what a rewind does to a path in its notice; [`action_label`]
/// names the same on the wire, for a client's preview.
pub(crate) fn classification_label(classification: RestoreClassification) -> &'static str {
    match classification {
        RestoreClassification::Create => "create",
        RestoreClassification::Modify => "modify",
        RestoreClassification::Delete => "delete",
        RestoreClassification::Conflict => "conflict",
        RestoreClassification::Unsupported => "unsupported",
        RestoreClassification::Skipped => "skip",
    }
}

pub(crate) fn limitation_label(kind: &UntrackedEffectKind) -> &'static str {
    match kind {
        UntrackedEffectKind::ShellCommand => "shell",
        UntrackedEffectKind::UntrackedMutatingTool => "process",
        UntrackedEffectKind::ExternalEffect => "external",
    }
}

/// Names what a rewind would do to a file, as a daemon's preview tells it,
/// in [`classification_label`]'s words.
pub(crate) fn action_label(action: rho_protocol::RewindAction) -> &'static str {
    use rho_protocol::RewindAction;
    match action {
        RewindAction::Restore => "modify",
        RewindAction::Recreate => "create",
        RewindAction::Delete => "delete",
        RewindAction::Conflict => "conflict",
        RewindAction::Unsupported => "unsupported",
        RewindAction::Unchanged => "skip",
        _ => "unknown",
    }
}

/// Names an effect a rewind would not undo, as a daemon's preview tells
/// it. The wire tells processes and external effects apart from shell
/// commands only, so where [`limitation_label`] says "process" or
/// "external", this says "tool".
pub(crate) fn untracked_label(kind: rho_protocol::UntrackedEffectKind) -> &'static str {
    use rho_protocol::UntrackedEffectKind;
    match kind {
        UntrackedEffectKind::Shell => "shell",
        UntrackedEffectKind::Tool => "tool",
        _ => "other",
    }
}