rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Workspace checkpoints of a session's turns, and rewinding to one.
//!
//! A turn's file writes are captured through the tool set's checkpoint
//! tracker between [`SessionRuntime::begin_workspace_checkpoint`] and
//! [`SessionRuntime::finalize_workspace_checkpoint`], for the sessions a
//! person prompts; a subagent's writes belong to its parent's turn. A
//! rewind restores the files a turn changed and moves the conversation to
//! the node before it (`tree.rs`).

use super::{build::SessionRole, SelectNodeError, SessionRuntime};
use crate::{
    app::{
        sdk_config::WorkspaceOptions,
        workspace_rewind::{plans_full_restore, restored_fully, PlannedRewind},
    },
    config::Config,
    permission::PermissionMode,
    session::{
        tree::NodeId,
        workspace_checkpoint::{
            CheckpointAppendError, CheckpointFileBudgetExceeded, CheckpointOutcome, RestoreAudit,
            RestorePlan, WorkspaceCheckpointStore,
        },
    },
};

/// What [`SessionRuntime::rewind_workspace`] did.
#[derive(Debug)]
pub(crate) struct WorkspaceRewind {
    /// The checkpoints it undid, oldest first.
    pub(crate) turns: Vec<NodeId>,
    /// What became of each path the checkpoints cover.
    pub(crate) audit: RestoreAudit,
    pub(crate) conversation: RewoundConversation,
}

/// Where the conversation stands after a rewind's files were restored.
#[derive(Debug)]
pub(crate) enum RewoundConversation {
    /// It continues from before the rewound turn, in this row of the tree.
    Moved { row: NodeId },
    /// Some path was not restored, so it stays where it was.
    Stayed,
    /// Every path was restored, but the conversation could not be moved.
    MoveFailed(SelectNodeError),
}

/// What [`SessionRuntime::rewind_workspace`] would do now, as
/// [`SessionRuntime::preview_rewind`] planned it.
#[derive(Debug)]
pub(crate) struct RewindPreview {
    /// The conversation's current node the plan was made against, which
    /// [`SessionRuntime::rewind_workspace`] may be held to.
    pub(crate) tip: NodeId,
    /// The checkpoints the rewind undoes, oldest first: the picked one, then
    /// every later one on the conversation's current path.
    pub(crate) turns: Vec<NodeId>,
    pub(crate) plan: RestorePlan,
    /// The row of the session's tree holding the node the conversation
    /// would continue from, when every file would go back; `None` when it
    /// would stay where it is.
    pub(crate) returns_to: Option<NodeId>,
}

/// A rewind planned against the workspace as it is, which nothing refused.
struct PlannedWorkspaceRewind {
    store: WorkspaceCheckpointStore,
    workspace: rho_sdk::Workspace,
    planned: PlannedRewind,
    /// The node before the checkpoint's turn.
    before: NodeId,
}

/// Why [`SessionRuntime::rewind_workspace`] changed nothing.
#[derive(Debug, thiserror::Error)]
pub(crate) enum RewindError {
    /// The session cannot rewind, or not to this checkpoint; the requester
    /// can tell why.
    #[error("{0:#}")]
    Refused(anyhow::Error),
    /// The checkpoints or the workspace could not be read or written.
    #[error("{0:#}")]
    Failed(anyhow::Error),
    /// The conversation moved on from the node the requester planned the
    /// rewind at, so it would undo what the requester did not see.
    #[error(
        "the conversation moved on from '{expected}' to '{now}' since the rewind was previewed; \
         preview it again"
    )]
    Moved { expected: NodeId, now: NodeId },
}

impl SessionRuntime {
    /// Whether this session's turns take workspace checkpoints.
    fn takes_checkpoints(&self) -> bool {
        match self.build.run.role {
            SessionRole::Interactive | SessionRole::Daemon | SessionRole::Run => {
                !self.checkpoints_paused
            }
            // Their writes are their parent's turn's, or no session's.
            SessionRole::Subagent { .. } | SessionRole::WorkflowNode => false,
        }
    }

    /// Opens the coming turn's checkpoint at the conversation's leaf, which
    /// the turn's checkpoint store has saved by now. Returns a notice when
    /// checkpoint storage failed, which pauses capture for the session and
    /// never the turn.
    pub(super) fn begin_workspace_checkpoint(&mut self) -> anyhow::Result<Option<String>> {
        if !self.takes_checkpoints() {
            return Ok(None);
        }
        let Some(stored) = self.storage.file() else {
            return Ok(None);
        };
        // One a turn that panicked left open would refuse this one.
        self.built.tools.checkpoint_tracker().discard_turn();
        match self
            .built
            .tools
            .checkpoint_tracker()
            .begin_turn(Some(stored))
        {
            Ok(()) => Ok(None),
            Err(error)
                if matches!(
                    error.downcast_ref::<CheckpointAppendError>(),
                    Some(CheckpointAppendError::Storage(_))
                ) =>
            {
                self.built.tools.checkpoint_tracker().discard_turn();
                self.checkpoints_paused = true;
                Ok(Some(format!(
                    "could not start workspace checkpoint: {error}; rewind paused for this session"
                )))
            }
            Err(error) => Err(error),
        }
    }

    /// Saves the ended turn's checkpoint against the conversation's leaf,
    /// and returns what to tell the session's clients. A full checkpoint
    /// budget pauses capture, not the conversation or earlier rewinds.
    pub(super) fn finalize_workspace_checkpoint(
        &mut self,
        outcome: CheckpointOutcome,
    ) -> Vec<String> {
        let tracker = self.built.tools.checkpoint_tracker().clone();
        let Some(stored) = self.storage.file() else {
            tracker.discard_turn();
            return Vec::new();
        };
        let saved = stored
            .active_checkpoint_target()
            .and_then(|target| match target {
                Some((node, revision)) => tracker.finalize_turn(node, revision, outcome),
                None => {
                    tracker.discard_turn();
                    Ok(None)
                }
            });
        match saved {
            Ok(None) => Vec::new(),
            Ok(Some(checkpoint)) => checkpoint
                .files
                .iter()
                .filter_map(|file| {
                    let CheckpointFileBudgetExceeded { asked, limit } =
                        file.capture_budget_exceeded()?;
                    Some(format!(
                        "workspace checkpoint skipped '{}': per-file capture budget is {limit} bytes, asked {asked} bytes; this file cannot be rewound",
                        file.path.display()
                    ))
                })
                .collect(),
            Err(error) => {
                tracing::warn!(%error, "failed to persist workspace checkpoint");
                tracker.discard_turn();
                match error.downcast::<CheckpointAppendError>() {
                    Ok(CheckpointAppendError::QuotaExceeded {
                        asked,
                        limit,
                        turn_bytes,
                    }) => {
                        self.checkpoints_paused = true;
                        vec![format!(
                            "workspace checkpoints paused: this session reached its {limit} bytes checkpoint budget (asked at least {asked} bytes; turn requested at least {turn_bytes} bytes); earlier turns stay rewindable"
                        )]
                    }
                    Ok(CheckpointAppendError::Storage(error)) | Err(error) => {
                        vec![format!("could not save workspace checkpoint: {error}")]
                    }
                }
            }
        }
    }

    /// What rewinding checkpoint `target` would do to the files as they are
    /// now, and so to the conversation, writing nothing. Refused as
    /// [`Self::rewind_workspace`] would be.
    pub(crate) fn preview_rewind(&self, target: &NodeId) -> Result<RewindPreview, RewindError> {
        let PlannedWorkspaceRewind {
            planned, before, ..
        } = self.plan_rewind(target, /*tip*/ None)?;
        let tip = planned.tip.clone();
        let returns_to = plans_full_restore(&planned.plan)
            .then(|| self.tree_row_of(&before))
            .transpose()
            .map_err(RewindError::Failed)?;
        Ok(RewindPreview {
            turns: planned.turns.turns().to_vec(),
            tip,
            plan: planned.plan,
            returns_to,
        })
    }

    /// Restores the files checkpoint `target`'s turn and every later turn
    /// on the conversation's current path changed, as one plan, and, when
    /// every one was restored, continues the conversation from before
    /// `target`'s turn. A session or checkpoint that cannot rewind, one off
    /// the current path included, is refused before a file is written;
    /// moving the conversation can still fail after, which
    /// [`RewoundConversation::MoveFailed`] says. With `tip`, the node a preview
    /// was planned at, a conversation that moved on since is
    /// [`RewindError::Moved`], before the checkpoint is looked at.
    // NEXT_MAJOR(rho-protocol): make tip required once SessionChange::RewindWorkspace is removed.
    pub(crate) async fn rewind_workspace(
        &mut self,
        target: &NodeId,
        tip: Option<&NodeId>,
        process_config: &Config,
    ) -> Result<WorkspaceRewind, RewindError> {
        let PlannedWorkspaceRewind {
            store,
            workspace,
            planned,
            before,
        } = self.plan_rewind(target, tip)?;
        // The row the preview said it returns to, read as the preview reads
        // it: before the conversation moves, and, failing, before a write.
        // A plan that keeps a path cannot restore fully, so needs none.
        let row = plans_full_restore(&planned.plan)
            .then(|| self.tree_row_of(&before))
            .transpose()
            .map_err(RewindError::Failed)?;
        let audit = planned
            .restore(&store, &workspace)
            .map_err(RewindError::Failed)?;
        let conversation = match row.filter(|_| restored_fully(&audit)) {
            Some(row) => match self.select_node(&before, process_config).await {
                Ok(()) => RewoundConversation::Moved { row },
                Err(error) => RewoundConversation::MoveFailed(error),
            },
            None => RewoundConversation::Stayed,
        };
        Ok(WorkspaceRewind {
            turns: planned.turns.turns().to_vec(),
            audit,
            conversation,
        })
    }

    /// Plans the rewind of checkpoint `target` against the workspace as it
    /// is, refusing a session or checkpoint that cannot rewind, and, with
    /// `tip`, a conversation whose current node is no longer `tip`.
    fn plan_rewind(
        &self,
        target: &NodeId,
        tip: Option<&NodeId>,
    ) -> Result<PlannedWorkspaceRewind, RewindError> {
        use RewindError::{Failed, Moved, Refused};
        if self.permission.mode == PermissionMode::Plan {
            return Err(Refused(anyhow::anyhow!(
                "workspace rewind is unavailable in plan permission mode"
            )));
        }
        let stored = self
            .storage
            .file()
            .ok_or_else(|| Refused(anyhow::anyhow!("the session has no saved conversation yet")))?;
        let store = stored
            .workspace_checkpoint_store()
            .map_err(Failed)?
            .ok_or_else(|| {
                Refused(anyhow::anyhow!(
                    "workspace rewind is unavailable for this session"
                ))
            })?;
        let workspace = WorkspaceOptions {
            root: self.permission.workspace_root.clone(),
        }
        .build_workspace(&self.added_dirs)
        .map_err(|error| Failed(error.into()))?;
        // A journal or tree that cannot be read is a failure, not a
        // checkpoint the session does not have.
        // The tip is compared in the same read as the plan, and before it: a
        // checkpoint another rewind or a selected node left off the branch
        // is the conversation having moved, not a bad checkpoint.
        let planned = stored
            .with_session_tree(|tree| {
                let now = tree.active_leaf_id();
                if let (Some(expected), Some(now)) = (tip, now) {
                    if expected != now {
                        return Ok(Err(Moved {
                            expected: expected.clone(),
                            now: now.clone(),
                        }));
                    }
                }
                Ok(
                    PlannedRewind::new(&store, &workspace, target, tree).map_err(|error| {
                        if error.refused() {
                            Refused(error.into())
                        } else {
                            Failed(error.into())
                        }
                    }),
                )
            })
            .map_err(Failed)??;
        let before = planned.turns.before().clone();
        // The node must still be there to return to once files changed.
        stored.history_for_node(&before).map_err(Refused)?;
        Ok(PlannedWorkspaceRewind {
            store,
            workspace,
            planned,
            before,
        })
    }
}

#[cfg(test)]
#[path = "workspace_rewind_tests.rs"]
mod tests;