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,
},
};
pub(crate) struct PlannedRewind {
pub(crate) turns: RewoundTurns,
pub(crate) tip: NodeId,
current: BTreeMap<PathBuf, ObservedFileState>,
pub(crate) plan: RestorePlan,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum PlanRewindError {
#[error("workspace checkpoint '{0}' was not found")]
NotFound(NodeId),
#[error("workspace checkpoint '{0}' is not on the conversation's current branch")]
OffBranch(NodeId),
#[error("could not rewind workspace: checkpoint predates rewind boundaries")]
NoBoundary,
#[error(transparent)]
Failed(#[from] anyhow::Error),
}
impl PlanRewindError {
pub(crate) fn refused(&self) -> bool {
match self {
Self::NotFound(_) | Self::OffBranch(_) | Self::NoBoundary => true,
Self::Failed(_) => false,
}
}
}
impl PlannedRewind {
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()))?;
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();
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, ¤t)?;
Ok(Self {
turns,
tip: tree
.active_leaf_id()
.cloned()
.ok_or_else(|| PlanRewindError::NotFound(target.clone()))?,
current,
plan,
})
}
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)
},
))
}
}
pub(crate) fn plans_full_restore(plan: &RestorePlan) -> bool {
!plan
.entries
.iter()
.any(|entry| entry.classification.leaves_path())
}
pub(crate) fn restored_fully(audit: &RestoreAudit) -> bool {
!audit
.entries
.iter()
.any(|entry| entry.error.is_some() || entry.classification.leaves_path())
}
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")
}
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"
)
})
}
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",
}
}