use std::path::Path;
use crate::engine::error::{PartialItem, PartialMem};
use crate::engine::{Engine, EngineError};
use crate::entity::EntityId;
use crate::provenance::{Provenance, ProvenanceKind};
#[derive(Debug, Clone)]
pub struct MemSweepOutcome {
pub rewritten_mems: Vec<String>,
pub logical_operation_id: String,
pub warnings: Vec<crate::ops::WarningHint>,
}
impl Engine {
pub fn rewrite_mem_references(
&mut self,
old_mem: &str,
new_mem: &str,
note: Option<&str>,
) -> Result<MemSweepOutcome, EngineError> {
let (_write_lock, _reloaded) = self.lock_workspace_for_write_if(true)?;
let logical_op_id = crate::provenance::mint_logical_operation_id();
let mut mem_order: Vec<usize> = self
.mounts
.iter()
.enumerate()
.filter(|(_, m)| {
m.mount.mem != old_mem
&& m.mount.capability == crate::workspace::MountCapability::Write
})
.map(|(i, _)| i)
.collect();
mem_order.sort_by(|a, b| self.mounts[*a].mount.mem.cmp(&self.mounts[*b].mount.mem));
if let Some(own_idx) = self.mounts.iter().position(|m| {
m.mount.mem == old_mem && m.mount.capability == crate::workspace::MountCapability::Write
}) {
mem_order.push(own_idx);
}
let mut plans: Vec<SweepPlan> = Vec::new();
for mount_idx in mem_order {
if let Some(plan) = self.plan_mem_sweep(mount_idx, old_mem, new_mem)? {
plans.push(plan);
}
}
let mut commits: Vec<(usize, String)> = Vec::new();
for (at, plan) in plans.iter().enumerate() {
match self.land_mem_sweep(plan, old_mem, new_mem, &logical_op_id, note) {
Ok(write_id) => {
self.record_self_write(plan.mount_idx, &write_id);
let _intervention_has_no_channel_here =
self.stamp_mutation_versions(plan.mount_idx);
commits.push((plan.mount_idx, write_id));
}
Err(cause) => {
return Err(self.sweep_failed_at(&plans, at, commits, cause));
}
}
}
let warnings = self.level_committed_mounts(&commits);
Ok(MemSweepOutcome {
rewritten_mems: plans.iter().map(|p| p.mem.clone()).collect(),
logical_operation_id: logical_op_id,
warnings,
})
}
fn plan_mem_sweep(
&self,
mount_idx: usize,
old_mem: &str,
new_mem: &str,
) -> Result<Option<SweepPlan>, EngineError> {
let mem_name = self.mounts[mount_idx].mount.mem.clone();
let backend = self.mounts[mount_idx].backend.as_ref();
let head = backend.current_head()?;
let mut changed: Vec<(std::path::PathBuf, String)> = Vec::new();
for rel_path in backend.list_entities()? {
let Some(bytes) = backend.read_entity(&rel_path)? else {
continue;
};
let Ok(text) = String::from_utf8(bytes) else {
continue;
};
let (rewritten, count) =
crate::entity::wikilink_rewrite::rewrite_mem_prefix(&text, old_mem, new_mem);
if count > 0 {
changed.push((rel_path, rewritten));
}
}
let mut sidecar: Option<Vec<u8>> = None;
if mem_name == old_mem
&& let Some(raw) = backend.read_anchors_sidecar()?
{
let current = crate::anchor::AnchorSidecar::from_bytes(&raw)
.map_err(|e| EngineError::Mem(format!("anchors sidecar parse: {e}")))?;
let prefix = format!("{old_mem}--");
let mut anchors_changed = false;
let mut next = crate::anchor::AnchorSidecar::default();
for (entity_id, anchors) in ¤t.entities {
let new_key = match entity_id.strip_prefix(&prefix) {
Some(rest) => {
anchors_changed = true;
format!("{new_mem}--{rest}")
}
None => entity_id.clone(),
};
next.set(&new_key, anchors.clone());
}
if anchors_changed {
sidecar = Some(next.to_bytes());
}
}
if changed.is_empty() && sidecar.is_none() {
return Ok(None);
}
let mut rehash: Vec<MarkRehash> = Vec::new();
for entity in self
.store
.all_entities()
.filter(|e| e.mem == mem_name && !e.stub)
{
let mut after = entity.sections.clone();
let mut moved = false;
for body in after.values_mut() {
let (rewritten, count) =
crate::entity::wikilink_rewrite::rewrite_mem_prefix_in_section(
body, old_mem, new_mem,
);
if count > 0 {
*body = rewritten;
moved = true;
}
}
if moved {
rehash.push((entity.id.clone(), entity.sections.clone(), after));
}
}
Ok(Some(SweepPlan {
mount_idx,
mem: mem_name,
head,
changed,
sidecar,
rehash,
}))
}
fn land_mem_sweep(
&self,
plan: &SweepPlan,
old_mem: &str,
new_mem: &str,
logical_op_id: &str,
note: Option<&str>,
) -> Result<String, EngineError> {
let backend = self.mounts[plan.mount_idx].backend.as_ref();
for (rel_path, text) in &plan.changed {
backend.write_entity(Path::new(rel_path), text.as_bytes())?;
}
for (id, before, after) in &plan.rehash {
super::stage_proposal_marks_rehash(backend, id, before, after)?;
}
if let Some(bytes) = &plan.sidecar {
backend.write_anchors_sidecar(bytes)?;
}
let subject = format!(
"memstead: rename mem `{old_mem}` → `{new_mem}` (reference rewrite in `{}`)",
plan.mem
);
let mut ctx = self.session_commit_context(Some("mem rename"), note.map(String::from));
ctx.logical_operation_id = Some(logical_op_id);
let records: Vec<Provenance> = plan
.entity_ids()
.into_iter()
.map(|id| {
Provenance::new(
std::time::SystemTime::now(),
ProvenanceKind::Update,
Some(id.to_string()),
self.current_actor,
self.current_client.clone(),
note.map(String::from),
)
.with_role(self.current_role)
.with_identity(self.current_identity.clone())
.with_logical_operation_id(logical_op_id.to_string())
})
.collect();
self.commit_or_complete(
plan.mount_idx,
self.commit_staged_pinned(
plan.mount_idx,
&subject,
&ctx,
&records,
plan.head.as_deref(),
),
)
.map(|landed| landed.write_id)
}
fn sweep_failed_at(
&mut self,
plans: &[SweepPlan],
failed: usize,
commits: Vec<(usize, String)>,
cause: EngineError,
) -> EngineError {
let failed_mount = plans[failed].mount_idx;
let in_storage = super::landing::with_a_decided_commit(commits, failed_mount, &cause);
if in_storage.is_empty() || plans.len() < 2 {
return cause;
}
self.level_committed_mounts(&in_storage);
let landed_in = |mount_idx: usize| in_storage.iter().any(|(idx, _)| *idx == mount_idx);
let mems = plans
.iter()
.enumerate()
.map(|(at, plan)| {
let landed = landed_in(plan.mount_idx);
PartialMem {
mem: plan.mem.clone(),
landed,
error: (at == failed).then(|| cause.to_string()),
items: plan
.entity_ids()
.into_iter()
.map(|id| PartialItem {
current_hash: self.hash_now(&id),
id: id.to_string(),
landed,
})
.collect(),
}
})
.collect();
EngineError::RenamePartialFailure {
committed_mems: plans
.iter()
.filter(|p| landed_in(p.mount_idx))
.map(|p| p.mem.clone())
.collect(),
failed_mem: plans[failed].mem.clone(),
failure_cause: super::landing::failure_cause_of(&cause).to_string(),
mems,
}
}
}
type MarkRehash = (
EntityId,
indexmap::IndexMap<String, String>,
indexmap::IndexMap<String, String>,
);
struct SweepPlan {
mount_idx: usize,
mem: String,
head: Option<String>,
changed: Vec<(std::path::PathBuf, String)>,
sidecar: Option<Vec<u8>>,
rehash: Vec<MarkRehash>,
}
impl SweepPlan {
fn entity_ids(&self) -> Vec<EntityId> {
self.changed
.iter()
.map(|(rel_path, _)| {
crate::entity::id::file_path_to_id(&rel_path.to_string_lossy(), &self.mem)
})
.collect()
}
}