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//! The sweep holds every writable mem's write lock and has reloaded
20//! every mem under it before it reads a file: it writes whichever mem
21//! holds a reference, and it learns which by reading them all.
22//!
23//! One commit per affected mem through the engine's one commit call,
24//! every commit tagged with a shared `logical_operation_id` and carrying
25//! one provenance record per rewritten entity, so a folder mem's ledger
26//! tells a sibling process what changed. The peers commit first, in
27//! name order, and the renamed mem itself last. Peer commits are
28//! parent-pinned (`commit_with_expected_parent`) against a writer that
29//! does not take the lock. A commit that fails after another landed
30//! surfaces as [`EngineError::RenamePartialFailure`], which states what
31//! landed mem by mem; a failure before any commit landed fails the
32//! sweep as a whole. Either way the mount still carries the old name,
33//! so the same `mem rename` sent again runs the sweep again, finds the
34//! landed mems done, and completes. Read-only mounts cannot be
35//! rewritten — their stale references degrade to load-time stubs,
36//! which health surfaces.
37//!
38//! Every mem the sweep committed is reloaded before it returns, on
39//! success and on failure: the engine serves what storage holds.
40
41use std::path::Path;
42
43use crate::engine::error::{PartialItem, PartialMem};
44use crate::engine::{Engine, EngineError};
45use crate::entity::EntityId;
46use crate::provenance::{Provenance, ProvenanceKind};
47
48/// Outcome of [`Engine::rewrite_mem_references`].
49#[derive(Debug, Clone)]
50pub struct MemSweepOutcome {
51    /// Mems whose entity files were rewritten and committed, in commit
52    /// order (peers sorted by name, then the renamed mem itself when it
53    /// had self-references or anchors).
54    pub rewritten_mems: Vec<String>,
55    /// The shared `logical_operation_id` carried by every commit.
56    pub logical_operation_id: String,
57    /// A `WRITE_FOLLOW_UP_FAILED` for every mem whose commit landed and
58    /// whose reload afterwards failed: the engine's view of it is
59    /// behind storage until its next operation reloads it.
60    pub warnings: Vec<crate::ops::WarningHint>,
61}
62
63impl Engine {
64    /// Rewrite every textual reference to mem `old_mem` so it carries
65    /// `new_mem` instead: cross-mem wiki-links and Relationships
66    /// entries in every writable peer mem, full-id self-references
67    /// inside `old_mem` itself, and `old_mem`'s anchors-sidecar keys
68    /// (`<old>--<slug>` → `<new>--<slug>`). One commit per affected
69    /// mem; unaffected mems get no commit. Idempotent: a second run
70    /// finds nothing left to rewrite and commits nothing — which is
71    /// exactly what makes an interrupted `mem rename` completable by
72    /// re-issuing it.
73    ///
74    /// Read-only mounts are skipped (no write access); their stale
75    /// references surface as load-time stubs on the next boot.
76    pub fn rewrite_mem_references(
77        &mut self,
78        old_mem: &str,
79        new_mem: &str,
80        note: Option<&str>,
81    ) -> Result<MemSweepOutcome, EngineError> {
82        // The sweep's answer scope is the whole workspace — every mem
83        // that references `old_mem` must be rewritten — so its lock and
84        // its load scope match: every writable mem is locked, every mem
85        // reloaded, and a deferred (lazy, unloaded) mem is loaded, or a
86        // reference inside it would survive the rename unrewritten.
87        let (_write_lock, _reloaded) = self.lock_workspace_for_write_if(true)?;
88        let logical_op_id = crate::provenance::mint_logical_operation_id();
89
90        // Peers in name order, the renamed mem itself last: its
91        // self-references and anchors move with the mem, and the mem's
92        // own part of a rename is the last thing to land.
93        let mut mem_order: Vec<usize> = self
94            .mounts
95            .iter()
96            .enumerate()
97            .filter(|(_, m)| {
98                m.mount.mem != old_mem
99                    && m.mount.capability == crate::workspace::MountCapability::Write
100            })
101            .map(|(i, _)| i)
102            .collect();
103        mem_order.sort_by(|a, b| self.mounts[*a].mount.mem.cmp(&self.mounts[*b].mount.mem));
104        if let Some(own_idx) = self.mounts.iter().position(|m| {
105            m.mount.mem == old_mem && m.mount.capability == crate::workspace::MountCapability::Write
106        }) {
107            mem_order.push(own_idx);
108        }
109
110        // Plan first, commit after: every mem's rewrite is computed
111        // before any backend write, so a read failure aborts cleanly.
112        let mut plans: Vec<SweepPlan> = Vec::new();
113        for mount_idx in mem_order {
114            if let Some(plan) = self.plan_mem_sweep(mount_idx, old_mem, new_mem)? {
115                plans.push(plan);
116            }
117        }
118
119        let mut commits: Vec<(usize, String)> = Vec::new();
120        for (at, plan) in plans.iter().enumerate() {
121            match self.land_mem_sweep(plan, old_mem, new_mem, &logical_op_id, note) {
122                Ok(write_id) => {
123                    self.record_self_write(plan.mount_idx, &write_id);
124                    // Same as the anchor backfill: a sweep has no per-operation
125                    // response to carry the notice. The merge still protects the
126                    // other writer's fields.
127                    let _intervention_has_no_channel_here =
128                        self.stamp_mutation_versions(plan.mount_idx);
129                    commits.push((plan.mount_idx, write_id));
130                }
131                Err(cause) => {
132                    return Err(self.sweep_failed_at(&plans, at, commits, cause));
133                }
134            }
135        }
136
137        // The engine's view follows what the sweep wrote.
138        let warnings = self.level_committed_mounts(&commits);
139        Ok(MemSweepOutcome {
140            rewritten_mems: plans.iter().map(|p| p.mem.clone()).collect(),
141            logical_operation_id: logical_op_id,
142            warnings,
143        })
144    }
145
146    /// What the sweep writes into one mem; `None` when the mem holds
147    /// no reference to `old_mem`. Reads storage and the store, writes
148    /// nothing.
149    fn plan_mem_sweep(
150        &self,
151        mount_idx: usize,
152        old_mem: &str,
153        new_mem: &str,
154    ) -> Result<Option<SweepPlan>, EngineError> {
155        let mem_name = self.mounts[mount_idx].mount.mem.clone();
156        let backend = self.mounts[mount_idx].backend.as_ref();
157
158        // The head the plan is computed from; the commit is pinned to
159        // it against a writer that does not take the lock.
160        let head = backend.current_head()?;
161
162        let mut changed: Vec<(std::path::PathBuf, String)> = Vec::new();
163        for rel_path in backend.list_entities()? {
164            let Some(bytes) = backend.read_entity(&rel_path)? else {
165                continue;
166            };
167            let Ok(text) = String::from_utf8(bytes) else {
168                // Undecodable file — boot already warns about it;
169                // the sweep leaves it alone.
170                continue;
171            };
172            let (rewritten, count) =
173                crate::entity::wikilink_rewrite::rewrite_mem_prefix(&text, old_mem, new_mem);
174            if count > 0 {
175                changed.push((rel_path, rewritten));
176            }
177        }
178
179        // The renamed mem's anchors sidecar: re-key every
180        // `<old>--<slug>` row to `<new>--<slug>` in the same
181        // commit as its content rewrites.
182        let mut sidecar: Option<Vec<u8>> = None;
183        if mem_name == old_mem
184            && let Some(raw) = backend.read_anchors_sidecar()?
185        {
186            let current = crate::anchor::AnchorSidecar::from_bytes(&raw)
187                .map_err(|e| EngineError::Mem(format!("anchors sidecar parse: {e}")))?;
188            let prefix = format!("{old_mem}--");
189            let mut anchors_changed = false;
190            let mut next = crate::anchor::AnchorSidecar::default();
191            for (entity_id, anchors) in &current.entities {
192                let new_key = match entity_id.strip_prefix(&prefix) {
193                    Some(rest) => {
194                        anchors_changed = true;
195                        format!("{new_mem}--{rest}")
196                    }
197                    None => entity_id.clone(),
198                };
199                next.set(&new_key, anchors.clone());
200            }
201            if anchors_changed {
202                sidecar = Some(next.to_bytes());
203            }
204        }
205
206        if changed.is_empty() && sidecar.is_none() {
207            return Ok(None);
208        }
209
210        // An adopted body's origin marks follow the same rewrite. The mem
211        // rename retargets cross-mem wiki-links inside section bodies, and
212        // a mark is a hash over those bytes, so an unfollowed mark stops
213        // matching and this mem's contributed bodies would be served as the
214        // workspace's own prose. Only entities the record marks are
215        // touched, and the after-sections come from the same rewrite
216        // function applied to the store's own section bodies, so nothing
217        // here re-parses a file the sweep deliberately treats as text.
218        let mut rehash: Vec<MarkRehash> = Vec::new();
219        for entity in self
220            .store
221            .all_entities()
222            .filter(|e| e.mem == mem_name && !e.stub)
223        {
224            let mut after = entity.sections.clone();
225            let mut moved = false;
226            for body in after.values_mut() {
227                // The SECTION form: the file form trims a leading
228                // `---…---` block as frontmatter and leaves it unmasked,
229                // which a section body must not have done to it. The two
230                // passes have to mask alike, or this one rewrites a link
231                // the file pass masked and the mark ends up hashing bytes
232                // the file does not hold.
233                let (rewritten, count) =
234                    crate::entity::wikilink_rewrite::rewrite_mem_prefix_in_section(
235                        body, old_mem, new_mem,
236                    );
237                if count > 0 {
238                    *body = rewritten;
239                    moved = true;
240                }
241            }
242            if moved {
243                rehash.push((entity.id.clone(), entity.sections.clone(), after));
244            }
245        }
246
247        Ok(Some(SweepPlan {
248            mount_idx,
249            mem: mem_name,
250            head,
251            changed,
252            sidecar,
253            rehash,
254        }))
255    }
256
257    /// Stage one mem's rewrite and commit it, pinned to the head the
258    /// plan was computed from. Returns the commit's id.
259    fn land_mem_sweep(
260        &self,
261        plan: &SweepPlan,
262        old_mem: &str,
263        new_mem: &str,
264        logical_op_id: &str,
265        note: Option<&str>,
266    ) -> Result<String, EngineError> {
267        let backend = self.mounts[plan.mount_idx].backend.as_ref();
268        for (rel_path, text) in &plan.changed {
269            backend.write_entity(Path::new(rel_path), text.as_bytes())?;
270        }
271        for (id, before, after) in &plan.rehash {
272            super::stage_proposal_marks_rehash(backend, id, before, after)?;
273        }
274        if let Some(bytes) = &plan.sidecar {
275            backend.write_anchors_sidecar(bytes)?;
276        }
277
278        let subject = format!(
279            "memstead: rename mem `{old_mem}` → `{new_mem}` (reference rewrite in `{}`)",
280            plan.mem
281        );
282        let mut ctx = self.session_commit_context(Some("mem rename"), note.map(String::from));
283        ctx.logical_operation_id = Some(logical_op_id);
284        // One record per rewritten entity: the ledger of a folder mem is
285        // how a sibling process learns what a commit changed.
286        let records: Vec<Provenance> = plan
287            .entity_ids()
288            .into_iter()
289            .map(|id| {
290                Provenance::new(
291                    std::time::SystemTime::now(),
292                    ProvenanceKind::Update,
293                    Some(id.to_string()),
294                    self.current_actor,
295                    self.current_client.clone(),
296                    note.map(String::from),
297                )
298                .with_role(self.current_role)
299                .with_identity(self.current_identity.clone())
300                .with_logical_operation_id(logical_op_id.to_string())
301            })
302            .collect();
303        self.commit_or_complete(
304            plan.mount_idx,
305            self.commit_staged_pinned(
306                plan.mount_idx,
307                &subject,
308                &ctx,
309                &records,
310                plan.head.as_deref(),
311            ),
312        )
313        .map(|landed| landed.write_id)
314    }
315
316    /// The report for a sweep that failed at `plans[failed]`. With
317    /// nothing committed the sweep failed as a whole and `cause` is the
318    /// report, and so it is for a sweep that writes one mem. With a
319    /// commit in storage (a mem that committed, or the failed mem when
320    /// its commit is decided and not applied) the report is the
321    /// partial-failure envelope, built after those mems were reloaded,
322    /// so every entry carries the hash its entity has now.
323    fn sweep_failed_at(
324        &mut self,
325        plans: &[SweepPlan],
326        failed: usize,
327        commits: Vec<(usize, String)>,
328        cause: EngineError,
329    ) -> EngineError {
330        let failed_mount = plans[failed].mount_idx;
331        let in_storage = super::landing::with_a_decided_commit(commits, failed_mount, &cause);
332        if in_storage.is_empty() || plans.len() < 2 {
333            return cause;
334        }
335        self.level_committed_mounts(&in_storage);
336        let landed_in = |mount_idx: usize| in_storage.iter().any(|(idx, _)| *idx == mount_idx);
337        let mems = plans
338            .iter()
339            .enumerate()
340            .map(|(at, plan)| {
341                let landed = landed_in(plan.mount_idx);
342                PartialMem {
343                    mem: plan.mem.clone(),
344                    landed,
345                    error: (at == failed).then(|| cause.to_string()),
346                    items: plan
347                        .entity_ids()
348                        .into_iter()
349                        .map(|id| PartialItem {
350                            current_hash: self.hash_now(&id),
351                            id: id.to_string(),
352                            landed,
353                        })
354                        .collect(),
355                }
356            })
357            .collect();
358        EngineError::RenamePartialFailure {
359            committed_mems: plans
360                .iter()
361                .filter(|p| landed_in(p.mount_idx))
362                .map(|p| p.mem.clone())
363                .collect(),
364            failed_mem: plans[failed].mem.clone(),
365            failure_cause: super::landing::failure_cause_of(&cause).to_string(),
366            mems,
367        }
368    }
369}
370
371/// One entity whose marked sections the sweep's rewrite moves: its id,
372/// its sections before the rewrite, and after.
373type MarkRehash = (
374    EntityId,
375    indexmap::IndexMap<String, String>,
376    indexmap::IndexMap<String, String>,
377);
378
379/// One mem's part of a sweep, computed before anything is written.
380struct SweepPlan {
381    mount_idx: usize,
382    mem: String,
383    /// The mem's head when the plan was computed.
384    head: Option<String>,
385    /// Entity files with their rewritten text.
386    changed: Vec<(std::path::PathBuf, String)>,
387    /// The re-keyed anchors sidecar, on the renamed mem itself.
388    sidecar: Option<Vec<u8>>,
389    rehash: Vec<MarkRehash>,
390}
391
392impl SweepPlan {
393    /// The entities whose files this plan rewrites.
394    fn entity_ids(&self) -> Vec<EntityId> {
395        self.changed
396            .iter()
397            .map(|(rel_path, _)| {
398                crate::entity::id::file_path_to_id(&rel_path.to_string_lossy(), &self.mem)
399            })
400            .collect()
401    }
402}