Skip to main content

memstead_base/engine/mutation/
mem_sweep.rs

1//! Mem-rename content sweep — the referrer-rewrite half of
2//! `memstead mem rename`.
3//!
4//! Entity ids are derived from `(mount name, file path)`, so renaming a
5//! mount re-ids every entity in it for free; what the rename must
6//! rewrite by hand is every **textual** `<old>--<slug>` / `<old>:<slug>`
7//! reference across the workspace — cross-mem wiki-links and
8//! `## Relationships` entries in peer mems, full-id self-references in
9//! the renamed mem itself, and the renamed mem's anchors-sidecar keys.
10//!
11//! The sweep is a raw-text pass over each entity file
12//! ([`crate::entity::wikilink_rewrite::rewrite_mem_prefix`], sharing the
13//! parser's code-masking discipline) rather than a parse → mutate →
14//! regenerate round-trip: formatting outside the rewritten links stays
15//! byte-identical, and both link surfaces (bodies and the
16//! `## Relationships` section) are covered by the one pass because both
17//! are wiki-links.
18//!
19//! One commit per affected mem, every commit tagged with a shared
20//! `logical_operation_id`. Peer commits are parent-pinned
21//! (`commit_with_expected_parent`) so a concurrent sibling writer
22//! surfaces as [`EngineError::RenamePartialFailure`] rather than a
23//! silent overwrite. Read-only mounts cannot be rewritten — their stale
24//! references degrade to load-time stubs, which health surfaces.
25//!
26//! The sweep deliberately does NOT maintain the in-memory store — the
27//! orchestrator (`crate::mem_management::rename_mem`) reloads the engine
28//! after the storage-identity flip, and everything between the sweep
29//! and that reload happens inside one engine call.
30
31use std::path::Path;
32
33use crate::engine::{Engine, EngineError};
34
35/// Outcome of [`Engine::rewrite_mem_references`].
36#[derive(Debug, Clone)]
37pub struct MemSweepOutcome {
38    /// Mems whose entity files were rewritten and committed, in commit
39    /// order (the renamed mem itself first when it had self-references
40    /// or anchors, then peers sorted by name).
41    pub rewritten_mems: Vec<String>,
42    /// The shared `logical_operation_id` carried by every commit.
43    pub logical_operation_id: String,
44}
45
46impl Engine {
47    /// Rewrite every textual reference to mem `old_mem` so it carries
48    /// `new_mem` instead: cross-mem wiki-links and Relationships
49    /// entries in every writable peer mem, full-id self-references
50    /// inside `old_mem` itself, and `old_mem`'s anchors-sidecar keys
51    /// (`<old>--<slug>` → `<new>--<slug>`). One commit per affected
52    /// mem; unaffected mems get no commit. Idempotent: a second run
53    /// finds nothing left to rewrite and commits nothing — which is
54    /// exactly what makes an interrupted `mem rename` completable by
55    /// re-issuing it.
56    ///
57    /// Read-only mounts are skipped (no write access); their stale
58    /// references surface as load-time stubs on the next boot.
59    pub fn rewrite_mem_references(
60        &mut self,
61        old_mem: &str,
62        new_mem: &str,
63        note: Option<&str>,
64    ) -> Result<MemSweepOutcome, EngineError> {
65        // The sweep's answer scope is the whole workspace — every mem
66        // that references `old_mem` must be rewritten — so its load
67        // scope must match: a reference inside a deferred (lazy,
68        // unloaded) mem would otherwise survive the rename unrewritten
69        // (load-scope/answer-scope rule, flywheel W7/01).
70        self.ensure_mems_loaded(None);
71        let logical_op_id = crate::provenance::mint_logical_operation_id();
72
73        // Plan first, commit after: collect per-mem rewrite lists
74        // before any backend write so a read failure aborts cleanly.
75        // The renamed mem itself sweeps first (self-references +
76        // anchors move with the mem), then peers in name order.
77        let mut mem_order: Vec<usize> = Vec::new();
78        if let Some(own_idx) = self.mounts.iter().position(|m| {
79            m.mount.mem == old_mem && m.mount.capability == crate::workspace::MountCapability::Write
80        }) {
81            mem_order.push(own_idx);
82        }
83        let mut peer_idxs: Vec<usize> = self
84            .mounts
85            .iter()
86            .enumerate()
87            .filter(|(_, m)| {
88                m.mount.mem != old_mem
89                    && m.mount.capability == crate::workspace::MountCapability::Write
90            })
91            .map(|(i, _)| i)
92            .collect();
93        peer_idxs.sort_by(|a, b| self.mounts[*a].mount.mem.cmp(&self.mounts[*b].mount.mem));
94        mem_order.extend(peer_idxs);
95
96        let mut rewritten_mems: Vec<String> = Vec::new();
97        for mount_idx in mem_order {
98            let mem_name = self.mounts[mount_idx].mount.mem.clone();
99            let backend = self.mounts[mount_idx].backend.as_ref();
100
101            // Snapshot the head before planning so the commit is
102            // parent-pinned against concurrent sibling writers.
103            let head_snapshot = backend.current_head()?;
104
105            let mut changed: Vec<(std::path::PathBuf, String)> = Vec::new();
106            for rel_path in backend.list_entities()? {
107                let Some(bytes) = backend.read_entity(&rel_path)? else {
108                    continue;
109                };
110                let Ok(text) = String::from_utf8(bytes) else {
111                    // Undecodable file — boot already warns about it;
112                    // the sweep leaves it alone.
113                    continue;
114                };
115                let (rewritten, count) =
116                    crate::entity::wikilink_rewrite::rewrite_mem_prefix(&text, old_mem, new_mem);
117                if count > 0 {
118                    changed.push((rel_path, rewritten));
119                }
120            }
121
122            // The renamed mem's anchors sidecar: re-key every
123            // `<old>--<slug>` row to `<new>--<slug>` in the same
124            // commit as its content rewrites.
125            let mut anchors_changed = false;
126            let mut sidecar_bytes: Option<Vec<u8>> = None;
127            if mem_name == old_mem {
128                let sidecar_raw = backend.read_anchors_sidecar()?;
129                if let Some(raw) = sidecar_raw {
130                    let sidecar = crate::anchor::AnchorSidecar::from_bytes(&raw)
131                        .map_err(|e| EngineError::Mem(format!("anchors sidecar parse: {e}")))?;
132                    let prefix = format!("{old_mem}--");
133                    let mut next = crate::anchor::AnchorSidecar::default();
134                    for (entity_id, anchors) in &sidecar.entities {
135                        let new_key = match entity_id.strip_prefix(&prefix) {
136                            Some(rest) => {
137                                anchors_changed = true;
138                                format!("{new_mem}--{rest}")
139                            }
140                            None => entity_id.clone(),
141                        };
142                        next.set(&new_key, anchors.clone());
143                    }
144                    if anchors_changed {
145                        sidecar_bytes = Some(next.to_bytes());
146                    }
147                }
148            }
149
150            if changed.is_empty() && !anchors_changed {
151                continue;
152            }
153
154            for (rel_path, text) in &changed {
155                backend.write_entity(Path::new(rel_path), text.as_bytes())?;
156            }
157            // An adopted body's origin marks follow the same rewrite. The mem
158            // rename retargets cross-mem wiki-links inside section bodies, and
159            // a mark is a hash over those bytes, so an unfollowed mark stops
160            // matching and this mem's contributed bodies would be served as the
161            // workspace's own prose. Only entities the record marks are
162            // touched, and the after-sections come from the same rewrite
163            // function applied to the store's own section bodies, so nothing
164            // here re-parses a file the sweep deliberately treats as text.
165            let candidates: Vec<crate::entity::EntityId> = self
166                .store
167                .all_entities()
168                .filter(|e| e.mem == mem_name && !e.stub)
169                .map(|e| e.id.clone())
170                .collect();
171            for id in candidates {
172                let Some(entity) = self.store.get(&id) else {
173                    continue;
174                };
175                let mut after = entity.sections.clone();
176                let mut moved = false;
177                for body in after.values_mut() {
178                    // The SECTION form: the file form trims a leading
179                    // `---…---` block as frontmatter and leaves it unmasked,
180                    // which a section body must not have done to it. The two
181                    // passes have to mask alike, or this one rewrites a link
182                    // the file pass masked and the mark ends up hashing bytes
183                    // the file does not hold.
184                    let (rewritten, count) =
185                        crate::entity::wikilink_rewrite::rewrite_mem_prefix_in_section(
186                            body, old_mem, new_mem,
187                        );
188                    if count > 0 {
189                        *body = rewritten;
190                        moved = true;
191                    }
192                }
193                if moved {
194                    super::stage_proposal_marks_rehash(backend, &id, &entity.sections, &after)?;
195                }
196            }
197            if let Some(bytes) = sidecar_bytes {
198                backend.write_anchors_sidecar(&bytes)?;
199            }
200
201            let subject = format!(
202                "memstead: rename mem `{old_mem}` → `{new_mem}` (reference rewrite in `{mem_name}`)"
203            );
204            let mut ctx = self.session_commit_context(Some("mem rename"), note.map(String::from));
205            ctx.logical_operation_id = Some(logical_op_id.as_str());
206            let commit_result =
207                backend.commit_with_expected_parent(&subject, &ctx, head_snapshot.as_deref());
208            let write_id = match commit_result {
209                Ok(sha) => sha,
210                Err(crate::backend::BackendError::ParentMismatch { .. }) => {
211                    return Err(EngineError::RenamePartialFailure {
212                        committed_mems: rewritten_mems,
213                        failed_mem: mem_name,
214                        failure_cause: "drift".to_string(),
215                    });
216                }
217                Err(e) => return Err(e.into()),
218            };
219            self.record_self_write(mount_idx, &write_id);
220            // Same as the anchor backfill: a sweep has no per-operation
221            // response to carry the notice. The merge still protects the
222            // other writer's fields.
223            let _intervention_has_no_channel_here = self.stamp_mutation_versions(mount_idx);
224            rewritten_mems.push(mem_name);
225        }
226
227        Ok(MemSweepOutcome {
228            rewritten_mems,
229            logical_operation_id: logical_op_id,
230        })
231    }
232}