Skip to main content

memstead_base/engine/mutation/
rename.rs

1//! `Engine::rename_entity` — change an entity's slug, move its file
2//! on the backend, and rewrite the in-memory store.
3
4use std::path::Path;
5
6use crate::engine_fallback_type;
7use crate::entity::EntityId;
8use crate::entity::id::validate_and_derive_slug;
9use crate::entity::parser::parse_markdown;
10use crate::entity::store_builder::push_entities_into_store;
11use crate::ops::WarningHint;
12use crate::provenance::{Provenance, ProvenanceKind};
13use crate::vcs::{Actor, ClientId, CommitContext};
14use crate::workspace::MountCapability;
15
16use super::super::{Engine, EngineError, RenameEntityArgs, RenameEntityOutcome};
17use super::{make_stub, unknown_type_error};
18
19/// One entity whose marked sections a rename's wiki-link rewrite moves: its
20/// id, its sections before the rewrite, and after.
21type MarkRehash = (
22    EntityId,
23    indexmap::IndexMap<String, String>,
24    indexmap::IndexMap<String, String>,
25);
26
27impl Engine {
28    /// Positional + CommitContext wrapper around
29    /// [`Self::rename_entity`].
30    pub fn rename_entity_with_ctx(
31        &mut self,
32        old_id: &EntityId,
33        new_title: &str,
34        expected_hash: &str,
35        ctx: &CommitContext<'_>,
36    ) -> Result<RenameEntityOutcome, EngineError> {
37        let args = RenameEntityArgs {
38            id: old_id.clone(),
39            expected_hash: Some(expected_hash.to_string()),
40            new_title: new_title.to_string(),
41        };
42        self.rename_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
43    }
44
45    /// Rename an entity by changing its title — the slug, id, and
46    /// on-disk file path follow.
47    ///
48    /// **Same-mem referrers and self-references are rewritten
49    /// atomically.** The renaming entity is treated as the first
50    /// referrer of itself: every entry in its own `relationships`
51    /// list whose target equals the old id is updated to point at
52    /// the new id, and every `[[<old-slug>]]` token in its own
53    /// section bodies is rewritten to the new slug (respecting
54    /// fenced-code and inline-code masking). Every other entity in
55    /// the same mem that pointed at the old id (via an explicit
56    /// relation or an inline body wiki-link) gets the same two-
57    /// surface rewrite. All rewrites land in one per-mem commit.
58    /// Cross-mem referrers in other Write mounts get the same
59    /// rewrite (colon-form body links and relationship rows), each
60    /// peer mem in its own commit pinned to the parent the scan saw,
61    /// gated by the cross-mem link policy; a ReadOnly-mount referrer
62    /// is left as it is and reported as a residual stub.
63    pub fn rename_entity(
64        &mut self,
65        args: RenameEntityArgs,
66        actor: Actor,
67        client: Option<&ClientId>,
68        note: Option<&str>,
69    ) -> Result<RenameEntityOutcome, EngineError> {
70        // A short id resolves (or refuses) before anything reads its mem.
71        let mut args = args;
72        let (resolved, short_hint) = self.resolve_entity_id(&args.id)?;
73        args.id = resolved;
74        let id = &args.id;
75        let mem = id.mem().to_string();
76
77        let mount_idx = self
78            .mounts
79            .iter()
80            .position(|m| m.mount.mem == mem)
81            .ok_or_else(|| self.unknown_mem_error(&mem))?;
82        if self.mounts[mount_idx].mount.capability != MountCapability::Write {
83            return Err(EngineError::ReadOnlyMount(mem));
84        }
85
86        // Reload-before-operation: reload if a sibling advanced the
87        // mem ref so the `expected_hash` compare below runs against
88        // current truth. The drift notice rides the outcome's
89        // `warnings` (real-rename path).
90        let mut drift_warnings: Vec<WarningHint> = short_hint.into_iter().collect();
91        let _write_lock = self.lock_mems_for_write(&[&mem])?;
92        drift_warnings.extend(self.reload_if_stale(Some(&mem)));
93
94        let entity = self
95            .store
96            .get(id)
97            .ok_or_else(|| EngineError::NotFound { id: id.to_string() })?;
98
99        // Stub guard — stubs derive their title from the id and have
100        // no `entity_type` to validate against. Recovery is
101        // `memstead_create` (stub adoption). Item 02 realised the
102        // `STUB_NOT_RENAMABLE` code the description list had
103        // advertised since the strictness work landed.
104        if entity.stub {
105            return Err(EngineError::StubNotRenamable { id: id.to_string() });
106        }
107
108        if let Some(expected) = args.expected_hash.as_deref()
109            && entity.content_hash != expected
110        {
111            return Err(EngineError::HashMismatch {
112                id: id.to_string(),
113                current: entity.content_hash.clone(),
114                is_stub: entity.stub,
115            });
116        }
117
118        let derivation = validate_and_derive_slug(&args.new_title)?;
119        let new_slug = derivation.slug.clone();
120        let new_id = EntityId::new(&mem, &new_slug);
121        crate::entity::id::enforce_id_length(new_id.as_ref())?;
122
123        if new_id == *id {
124            // Title-with-same-slug: surface a Tier-2 warning rather
125            // than touching disk for nothing. Matches full's
126            // RenameResult slug-noop shape so autonomous skills
127            // can distinguish the silent no-op from a successful
128            // cosmetic rewrite via the typed warning code.
129            return Ok(RenameEntityOutcome {
130                old_id: id.clone(),
131                new_id: new_id.clone(),
132                old_path: entity.file_path.clone(),
133                new_path: entity.file_path.clone(),
134                content_hash: entity.content_hash.clone(),
135                write_id: String::new(),
136                warnings: vec![WarningHint::TitleNormalizedToSlugNoop {
137                    requested_title: args.new_title.clone(),
138                    current_slug: id.name().to_string(),
139                }],
140            });
141        }
142        if let Some(existing) = self.store.get(&new_id) {
143            return Err(EngineError::AlreadyExists {
144                id: new_id.to_string(),
145                existing_title: existing.title.clone(),
146                existing_is_stub: existing.stub,
147            });
148        }
149
150        let schema = self
151            .schemas
152            .get(&mem)
153            .expect("schema present for every registered mount");
154        let type_def = schema
155            .get_type(&entity.entity_type)
156            .ok_or_else(|| unknown_type_error(schema, &entity.entity_type))?;
157
158        let old_file_path = entity.file_path.clone();
159        let new_file_path = format!("{new_slug}.md");
160
161        let mut next = entity.clone();
162        next.id = new_id.clone();
163        next.title = args.new_title.clone();
164        next.file_path = new_file_path.clone();
165
166        // Self-reference rewrite, surface 1/2 — `relationships` list.
167        // Any explicit edge `<this> --<type>--> <old_id>` is repointed
168        // to `<this> --<type>--> <new_id>` so the regenerated
169        // `## Relationships` section reflects the new id rather than
170        // a relation that would re-emit a stub of the old slug at
171        // next read.
172        for rel in next.relationships.iter_mut() {
173            if rel.target == *id {
174                rel.target = new_id.clone();
175            }
176        }
177
178        // Self-reference rewrite, surface 2/2 — section bodies.
179        // Every `[[<old-slug>]]` token in the renaming entity's own
180        // section bodies becomes `[[<new-slug>]]`. Code-fenced and
181        // inline-code matches are preserved (the rewriter shares the
182        // masking discipline of `extract_inline_links`).
183        //
184        // The body parser admits both short form `[[slug]]` and
185        // full-id form `[[mem--slug]]` (same mem) as references to
186        // the same entity. The bare-slug rewriter only catches the
187        // first; `rewrite_cross_mem_slug` (which already powers the
188        // cross-mem Tier-2 rewrite) covers the second by matching
189        // `<mem>--<slug>` and `<mem>:<slug>` forms. Calling both
190        // here preserves the form the author wrote — short stays short,
191        // full-id stays full-id — just retargeted to the new slug.
192        let old_slug = id.name().to_string();
193        let new_slug_owned = new_slug.clone();
194        for body in next.sections.values_mut() {
195            let (rewritten, count) = crate::entity::wikilink_rewrite::rewrite_bare_slug(
196                body,
197                &old_slug,
198                &new_slug_owned,
199            );
200            if count > 0 {
201                *body = rewritten;
202            }
203            let (rewritten, count) = crate::entity::wikilink_rewrite::rewrite_cross_mem_slug(
204                body,
205                &mem,
206                &old_slug,
207                &new_slug_owned,
208            );
209            if count > 0 {
210                *body = rewritten;
211            }
212        }
213
214        // Every entity whose on-disk file the rename rewrites
215        // (the renaming entity itself plus every Write-mem referrer
216        // touched by the body/relationships rewrite cascade) gets
217        // `auto_timestamp` metadata fields stamped before
218        // `generate_markdown` so the new file carries the stamp.
219        // Pre-compute `today` once so all entities rewritten by this
220        // logical operation receive the same timestamp.
221        let today = self.now_iso();
222        super::auto_stamp_timestamps(&mut next, type_def.as_ref(), &today);
223
224        let markdown = super::render_for_write(&next, type_def.as_ref())?;
225
226        // Referrer collection. Walk every incoming edge — explicit
227        // relations and `EdgeSource::BodyLink` synthesised mirrors
228        // alike — and bucket each unique referrer by its mem's
229        // capability. Same-mem referrers are guaranteed Write (the
230        // mount-capability gate at the top of this fn refused the
231        // rename if the renaming mem itself isn't Write). Cross-
232        // mem referrers split into Write (rewriteable, subject to
233        // the `cross_mem_links` policy gate below) and ReadOnly
234        // (the engine has no write access; their handling lands with
235        // the rename-path residual-stub demotion in the next cut and
236        // is filtered out here).
237        let mut seen: std::collections::HashSet<EntityId> = std::collections::HashSet::new();
238        let mut same_mem_ids: Vec<EntityId> = Vec::new();
239        let mut cross_mem_ids: Vec<EntityId> = Vec::new();
240        for in_edge in self.store.incoming(id) {
241            if in_edge.from == *id || !seen.insert(in_edge.from.clone()) {
242                continue;
243            }
244            if in_edge.from.mem() == mem {
245                same_mem_ids.push(in_edge.from.clone());
246            } else {
247                cross_mem_ids.push(in_edge.from.clone());
248            }
249        }
250        // Prose-only referrers. Body wiki-links are not edge sources
251        // (every store edge originates from the auto-managed
252        // `## Relationships` section), so a hand-authored file carrying
253        // an inline `[[old-slug]]` with no relationship row has no
254        // incoming edge and the walk above cannot see it — its link
255        // would silently go stale. Scan section bodies with the same
256        // lenient extractor the load-time drift scan uses (code-fence
257        // and inline-code masking included), gated on a cheap substring
258        // probe so the store-wide pass stays proportional to actual
259        // mentions. Engine-written entities are covered either way:
260        // alias synthesis always emits the row on write.
261        for entity in self.store.all_entities() {
262            if entity.id == *id || entity.stub || seen.contains(&entity.id) {
263                continue;
264            }
265            let mentions = entity.sections.values().any(|body| {
266                body.contains(old_slug.as_str())
267                    && crate::entity::parser::extract_inline_links_lenient(body, entity.id.mem())
268                        .iter()
269                        .any(|t| t == id)
270            });
271            if !mentions {
272                continue;
273            }
274            seen.insert(entity.id.clone());
275            if entity.id.mem() == mem {
276                same_mem_ids.push(entity.id.clone());
277            } else {
278                cross_mem_ids.push(entity.id.clone());
279            }
280        }
281
282        // Cross-mem peers are partitioned by mount capability.
283        // Write peers feed the cross-mem rewrite plan; ReadOnly
284        // peers feed the residual-stub demotion path (the engine
285        // can't rewrite their on-disk markdown, so we materialise an
286        // in-memory stub at the OLD id that holds the surviving
287        // incoming edges from the ReadOnly mount — mirrors the
288        // delete-path's same-shaped demotion).
289        let mut cross_mem_write_ids: Vec<EntityId> = Vec::new();
290        let mut readonly_referrers: Vec<EntityId> = Vec::new();
291        for from_id in cross_mem_ids {
292            match self
293                .mount(from_id.mem())
294                .map(|m| m.capability)
295                .unwrap_or(MountCapability::Write)
296            {
297                MountCapability::Write => cross_mem_write_ids.push(from_id),
298                MountCapability::ReadOnly => readonly_referrers.push(from_id),
299            }
300        }
301        readonly_referrers.sort_by_key(|a| a.to_string());
302
303        // Pre-flight policy gate. Each propagated referrer rewrite
304        // is an edge of the form `referrer ∈ peer_mem → renamed ∈
305        // mem` — same direction as the original edge. The gate
306        // consults `cross_mem_link_allowed(peer_mem, mem)`,
307        // which is the direction the policy gates new edges with
308        // (forward-looking add-filter). A blocked peer aborts the
309        // rename up-front — no writes have happened yet, so the
310        // refusal is clean. This is the edge direction, not its
311        // inverse.
312        let mut blocked_counts: std::collections::BTreeMap<String, usize> =
313            std::collections::BTreeMap::new();
314        for from_id in &cross_mem_write_ids {
315            let peer_mem = from_id.mem().to_string();
316            if !self.cross_mem_link_allowed(&peer_mem, &mem) {
317                *blocked_counts.entry(peer_mem).or_insert(0) += 1;
318            }
319        }
320        if !blocked_counts.is_empty() {
321            let blocked_referrers: Vec<crate::engine::error::BlockedReferrer> = blocked_counts
322                .into_iter()
323                .map(|(peer_mem, count)| crate::engine::error::BlockedReferrer {
324                    from_mem: peer_mem,
325                    to_mem: mem.clone(),
326                    count,
327                })
328                .collect();
329            return Err(EngineError::RenameBlockedByCrossMemPolicy {
330                from_mem: mem.clone(),
331                blocked_referrers,
332            });
333        }
334
335        // Deterministic iteration order so the resulting per-mem
336        // pending-op replay is stable across runs (helpful for test
337        // snapshots and human reviewers).
338        same_mem_ids.sort_by_key(|a| a.to_string());
339        cross_mem_write_ids.sort_by_key(|a| a.to_string());
340
341        // ----- Same-mem rewrite plan -----
342        // (rewritten_markdown, file_path, type_def) per same-mem
343        // referrer — collected before any backend write so a
344        // per-referrer schema or rewrite failure aborts the rename
345        // before anything lands.
346        let mut same_mem_writes: Vec<(
347            String,
348            String,
349            std::sync::Arc<memstead_schema::TypeDefinition>,
350        )> = Vec::with_capacity(same_mem_ids.len());
351        // Whose marked sections this rename rewrites, before and after. A
352        // wiki-link retarget moves marked bytes without being an authorship
353        // event, so the marks are recomputed over the new bytes in the same
354        // commit; unfollowed, ordinary housekeeping would serve a
355        // contributor's untouched sentences as the workspace's own.
356        let mut same_mem_rehash: Vec<MarkRehash> = Vec::new();
357        for from_id in &same_mem_ids {
358            let Some(referrer) = self.store.get(from_id) else {
359                continue;
360            };
361            if referrer.stub {
362                continue;
363            }
364            let referrer_type_def = schema
365                .get_type(&referrer.entity_type)
366                .ok_or_else(|| unknown_type_error(schema, &referrer.entity_type))?;
367            let mut next_ref = referrer.clone();
368            for rel in next_ref.relationships.iter_mut() {
369                if rel.target == *id {
370                    rel.target = new_id.clone();
371                }
372            }
373            for body in next_ref.sections.values_mut() {
374                let (rewritten, count) = crate::entity::wikilink_rewrite::rewrite_bare_slug(
375                    body,
376                    &old_slug,
377                    &new_slug_owned,
378                );
379                if count > 0 {
380                    *body = rewritten;
381                }
382                // A same-mem referrer may also use
383                // full-id form `[[<mem>--<slug>]]` to point at the
384                // renaming entity — covered by the cross-mem helper
385                // which matches the `--` and `:` separator forms.
386                let (rewritten, count) = crate::entity::wikilink_rewrite::rewrite_cross_mem_slug(
387                    body,
388                    &mem,
389                    &old_slug,
390                    &new_slug_owned,
391                );
392                if count > 0 {
393                    *body = rewritten;
394                }
395            }
396            // Do NOT bump the referrer's `auto_timestamp` fields. A
397            // rename rewrites the referrer's body wiki-link to the new
398            // slug — a foreign-key change, not a semantic edit — so its
399            // `last_modified` staleness clock must NOT reset (a staleness
400            // audit would otherwise read every referrer of a renamed
401            // entity as freshly-touched). The referrer's content hash
402            // still changes (its body now holds the new slug); only the
403            // staleness clock is preserved by carrying the prior
404            // timestamp through from the cloned referrer. (Pre-fix this
405            // stamped the shared `today` for cross-entity consistency.)
406            let ref_markdown = super::render_for_write(&next_ref, referrer_type_def.as_ref())?;
407            same_mem_rehash.push((
408                from_id.clone(),
409                referrer.sections.clone(),
410                next_ref.sections.clone(),
411            ));
412            same_mem_writes.push((ref_markdown, next_ref.file_path.clone(), referrer_type_def));
413        }
414
415        // ----- Cross-mem rewrite plan -----
416        // Group cross-mem Write referrers by their mem so each
417        // peer mem's backend gets one commit. Each entry holds the
418        // peer mount index, the peer mem's schema, and the list of
419        // (markdown, file_path, type_def) for that mem's referrers.
420        struct PeerMemPlan {
421            mount_idx: usize,
422            mem: String,
423            writes: Vec<(
424                String,
425                String,
426                std::sync::Arc<memstead_schema::TypeDefinition>,
427            )>,
428            /// Whose marked sections this rewrite moves, before and after —
429            /// the peer mem's own record is the one that holds its marks.
430            rehash: Vec<MarkRehash>,
431        }
432        let mut peer_plans: std::collections::BTreeMap<String, PeerMemPlan> =
433            std::collections::BTreeMap::new();
434        for from_id in &cross_mem_write_ids {
435            let peer_mem = from_id.mem().to_string();
436            let peer_mount_idx = self
437                .mounts
438                .iter()
439                .position(|m| m.mount.mem == peer_mem)
440                .expect("peer mount present for collected referrer id");
441            let peer_schema = self
442                .schemas
443                .get(&peer_mem)
444                .expect("schema present for every registered mount");
445
446            let Some(referrer) = self.store.get(from_id) else {
447                continue;
448            };
449            if referrer.stub {
450                continue;
451            }
452            let referrer_type_def = peer_schema
453                .get_type(&referrer.entity_type)
454                .ok_or_else(|| unknown_type_error(peer_schema, &referrer.entity_type))?;
455            let before_sections = referrer.sections.clone();
456            let mut next_ref = referrer.clone();
457            for rel in next_ref.relationships.iter_mut() {
458                if rel.target == *id {
459                    rel.target = new_id.clone();
460                }
461            }
462            // Cross-mem referrers reference the renaming entity
463            // via the cross-mem wiki-link forms (`[[<mem>:<slug>]]`
464            // or the legacy `[[<mem>--<slug>]]`). The bare-slug
465            // form is reserved for same-mem refs and never appears
466            // here.
467            for body in next_ref.sections.values_mut() {
468                let (rewritten, count) = crate::entity::wikilink_rewrite::rewrite_cross_mem_slug(
469                    body,
470                    &mem,
471                    &old_slug,
472                    &new_slug_owned,
473                );
474                if count > 0 {
475                    *body = rewritten;
476                }
477            }
478            // A cross-mem Write peer is a referrer too — preserve its
479            // `last_modified` for the same reason as the same-mem case
480            // above (slug rewrite is a foreign-key change, not a semantic
481            // edit). Its content hash still changes; the staleness clock
482            // does not reset.
483            let ref_markdown = super::render_for_write(&next_ref, referrer_type_def.as_ref())?;
484
485            let plan_entry = peer_plans
486                .entry(peer_mem.clone())
487                .or_insert_with(|| PeerMemPlan {
488                    mount_idx: peer_mount_idx,
489                    mem: peer_mem.clone(),
490                    writes: Vec::new(),
491                    rehash: Vec::new(),
492                });
493            plan_entry
494                .writes
495                .push((ref_markdown, next_ref.file_path.clone(), referrer_type_def));
496            plan_entry
497                .rehash
498                .push((from_id.clone(), before_sections, next_ref.sections.clone()));
499        }
500
501        // ----- Apply: renaming entity's own mem first -----
502        // Mint a single `logical_operation_id` up front so every
503        // commit produced by this rename — source mem + every peer
504        // mem — carries the same correlation id in its provenance
505        // entry. Single-mem renames also tag with an id (it just
506        // maps to one commit); consumers branch on whether the id
507        // recurs to identify a multi-commit logical operation.
508        let logical_op_id = crate::provenance::mint_logical_operation_id();
509
510        let backend = self.mounts[mount_idx].backend.as_ref();
511        backend.write_entity(Path::new(&new_file_path), markdown.as_bytes())?;
512        backend.delete_entity(Path::new(&old_file_path))?;
513        for (ref_markdown, ref_file_path, _) in &same_mem_writes {
514            backend.write_entity(Path::new(ref_file_path), ref_markdown.as_bytes())?;
515        }
516        // Move the renamed entity's anchor row old_id → new_id in the SAME
517        // commit as the file move so entity + anchors rewind together and
518        // resolution finds every anchor under the new id (zero under the
519        // old). A no-op when the entity had no anchors (byte-identical).
520        super::stage_anchors_rename(backend, id, &new_id)?;
521        // An adopted body's origin marks follow the slug in the same commit,
522        // for the same reason the anchors do: the marks are keyed by slug and
523        // a rename moves the id while leaving the contributor's bytes alone.
524        // Following the key here is what lets the read path be exact instead
525        // of inferring a rename from matching content across slugs.
526        super::stage_proposal_marks_rename(backend, id, &new_id)?;
527        // The self-link rewrite moves the renamed entity's own marked bytes,
528        // under its NEW slug now that the marks have followed the key.
529        super::stage_proposal_marks_rehash(backend, &new_id, &entity.sections, &next.sections)?;
530        for (ref_id, before, after) in &same_mem_rehash {
531            super::stage_proposal_marks_rehash(backend, ref_id, before, after)?;
532        }
533        // The check ledger follows the id too. It is workspace state, not
534        // mem content, so it cannot ride the commit; it is carried before
535        // the commit so a ledger that refuses stops the rename the way a
536        // refused check stops a record, and a commit that then fails
537        // leaves at worst a carried line under an id that never came to
538        // be — never a renamed entity that lost its checks.
539        self.carry_checks_across_rename(id, &new_id)?;
540        let commit_subject = format!("memstead: rename {} → {new_id}", id);
541        let mut ctx = self.commit_context(
542            Some("rename_entity"),
543            actor,
544            client.cloned(),
545            note.map(String::from),
546        );
547        ctx.logical_operation_id = Some(logical_op_id.as_str());
548        let write_id = backend.commit(&commit_subject, &ctx)?;
549
550        backend.append_provenance(
551            &Provenance::new(
552                std::time::SystemTime::now(),
553                ProvenanceKind::Rename,
554                Some(new_id.to_string()),
555                actor,
556                client.cloned(),
557                note.map(String::from),
558            )
559            .with_role(self.current_role)
560            .with_identity(self.current_identity.clone())
561            .with_logical_operation_id(logical_op_id.clone()),
562        )?;
563
564        self.record_self_write(mount_idx, &write_id);
565        let stamp_warnings = self.stamp_mutation_versions(mount_idx);
566        let mut peer_stamp_warnings: Vec<WarningHint> = Vec::new();
567
568        // ----- Apply: cross-mem peer mems (parent-pinned) -----
569        // Snapshot every peer mem's current head before any peer
570        // writes begin. The snapshots are pinned through
571        // `commit_with_expected_parent`, so a sibling writer that
572        // advances a peer mem's head between snapshot and commit
573        // aborts the commit with `BackendError::ParentMismatch`. The
574        // engine layer maps this to `RENAME_PARTIAL_FAILURE` (the
575        // source mem has already committed by this point — its
576        // state is durable; only the failed peer's writes are lost).
577        // Folder and archive backends inherit the trait's default
578        // `commit_with_expected_parent` (which ignores the parent
579        // and delegates to `commit`); the git-branch backend
580        // overrides to check the per-mem branch tip.
581        let mut peer_snapshots: std::collections::BTreeMap<String, Option<String>> =
582            std::collections::BTreeMap::new();
583        for plan in peer_plans.values() {
584            let peer_backend = self.mounts[plan.mount_idx].backend.as_ref();
585            let snapshot = peer_backend.current_head()?;
586            peer_snapshots.insert(plan.mem.clone(), snapshot);
587        }
588
589        // Track which mems have already committed in this logical
590        // operation. On a peer-commit failure, the engine surfaces
591        // the partial-state envelope so the agent can decide whether
592        // to retry, reconcile, or accept.
593        let mut committed_mems: Vec<String> = vec![mem.clone()];
594        for plan in peer_plans.values() {
595            let peer_backend = self.mounts[plan.mount_idx].backend.as_ref();
596            for (ref_markdown, ref_file_path, _) in &plan.writes {
597                peer_backend.write_entity(Path::new(ref_file_path), ref_markdown.as_bytes())?;
598            }
599            // Each peer mem holds its own record, so its marks are carried
600            // into its own commit.
601            for (ref_id, before, after) in &plan.rehash {
602                super::stage_proposal_marks_rehash(peer_backend, ref_id, before, after)?;
603            }
604            let peer_commit_subject = format!(
605                "memstead: rename {} → {new_id} (cross-mem rewrite in `{}`)",
606                id, plan.mem
607            );
608            let mut peer_ctx = self.commit_context(
609                Some("rename_entity"),
610                actor,
611                client.cloned(),
612                note.map(String::from),
613            );
614            peer_ctx.logical_operation_id = Some(logical_op_id.as_str());
615            let expected = peer_snapshots.get(&plan.mem).cloned().unwrap_or(None);
616            let peer_commit_result = peer_backend.commit_with_expected_parent(
617                &peer_commit_subject,
618                &peer_ctx,
619                expected.as_deref(),
620            );
621            let peer_write_id = match peer_commit_result {
622                Ok(sha) => sha,
623                Err(crate::backend::BackendError::ParentMismatch { .. }) => {
624                    return Err(EngineError::RenamePartialFailure {
625                        committed_mems: std::mem::take(&mut committed_mems),
626                        failed_mem: plan.mem.clone(),
627                        failure_cause: "drift".to_string(),
628                    });
629                }
630                Err(e) => return Err(e.into()),
631            };
632            peer_backend.append_provenance(
633                &Provenance::new(
634                    std::time::SystemTime::now(),
635                    ProvenanceKind::Rename,
636                    Some(new_id.to_string()),
637                    actor,
638                    client.cloned(),
639                    note.map(String::from),
640                )
641                .with_role(self.current_role)
642                .with_identity(self.current_identity.clone())
643                .with_logical_operation_id(logical_op_id.clone()),
644            )?;
645            self.record_self_write(plan.mount_idx, &peer_write_id);
646            // Per peer mount, not only the source mem: a rename touches every
647            // pinned peer, and each one's config write can meet its own
648            // intervening writer.
649            peer_stamp_warnings.extend(self.stamp_mutation_versions(plan.mount_idx));
650            committed_mems.push(plan.mem.clone());
651        }
652
653        // ----- Re-parse and push -----
654        let parse_result = parse_markdown(&markdown, &new_file_path, type_def.as_ref(), &mem)
655            .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
656        let content_hash = parse_result.entity.content_hash.clone();
657
658        let mut parse_results = vec![parse_result];
659        for (ref_markdown, ref_file_path, ref_type_def) in &same_mem_writes {
660            let pr = parse_markdown(ref_markdown, ref_file_path, ref_type_def.as_ref(), &mem)
661                .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
662            parse_results.push(pr);
663        }
664        for plan in peer_plans.values() {
665            for (ref_markdown, ref_file_path, ref_type_def) in &plan.writes {
666                let pr = parse_markdown(
667                    ref_markdown,
668                    ref_file_path,
669                    ref_type_def.as_ref(),
670                    &plan.mem,
671                )
672                .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
673                parse_results.push(pr);
674            }
675        }
676
677        // Residual-stub demotion for ReadOnly cross-mem referrers.
678        // The engine can't rewrite ReadOnly-mount markdown, so the
679        // wiki-links there still point at the OLD slug after the
680        // rename. To keep `incoming(<new_id>)` aligned with what a
681        // fresh boot would produce (and to surface the dangling
682        // reference to the agent), we demote the OLD-id store entry
683        // to a stub instead of removing it outright. Its surviving
684        // `in_edges` from the ReadOnly mount remain valid — they
685        // point at the now-stub at the old id.
686        //
687        // When no ReadOnly referrers exist, the old entry is
688        // removed cleanly (the existing Write-path behaviour).
689        let mut outcome_warnings: Vec<WarningHint> = Vec::new();
690        outcome_warnings.extend(stamp_warnings);
691        outcome_warnings.extend(peer_stamp_warnings);
692        // Reload-before-operation drift notice, surfaced first.
693        outcome_warnings.append(&mut drift_warnings);
694        // Title↔slug divergence of the NEW title — same visibility
695        // contract as create's.
696        if !derivation.dropped_chars.is_empty() {
697            outcome_warnings.push(WarningHint::TitleCharsDroppedFromSlug {
698                title: args.new_title.trim().to_string(),
699                dropped_chars: derivation.dropped_chars.clone(),
700                slug: new_slug.clone(),
701            });
702        }
703        if readonly_referrers.is_empty() {
704            self.store.remove(id);
705        } else {
706            // Sever outgoing edges from the old id (the entity is
707            // gone — its body and relations live at the new id now)
708            // and replace the node with a stub at the same id. The
709            // in_edges from the ReadOnly mount survive untouched.
710            self.store.remove_edges_from(id);
711            self.store.upsert(
712                id.clone(),
713                make_stub(
714                    id,
715                    crate::entity::StubKind::Residual {
716                        since_commit: write_id.clone(),
717                        readonly_referrers: readonly_referrers.clone(),
718                    },
719                ),
720            );
721            outcome_warnings.push(WarningHint::ResidualStubForReadOnlyReferrers {
722                id: id.clone(),
723                referrers: readonly_referrers,
724            });
725        }
726
727        let fallback = engine_fallback_type();
728        // Incremental (flywheel W8/01): the touched set is the OLD id
729        // (its document must leave the index) plus every re-parsed
730        // entity — the renamed entity at its new id and each rewritten
731        // referrer.
732        let mut touched: Vec<crate::EntityId> = parse_results
733            .iter()
734            .map(|pr| pr.entity.id.clone())
735            .collect();
736        touched.push(id.clone());
737        push_entities_into_store(&mut self.store, parse_results, fallback.as_ref(), None);
738        crate::entity::store_builder::remap_alias_target_edge_sources(
739            &mut self.store,
740            &self.schemas,
741        );
742
743        self.invalidate_communities();
744        self.maintain_search_indexes(&touched);
745
746        // `require_notes` provenance nudge — single engine-level
747        // enforcement point. Only reached on the real-rename path; the
748        // slug-noop short-circuit returns early above with an empty
749        // `write_id` and never demands a note.
750        if let Some(w) = self.note_missing_warning("rename_entity", note) {
751            outcome_warnings.push(w);
752        }
753
754        Ok(RenameEntityOutcome {
755            old_id: id.clone(),
756            new_id,
757            old_path: old_file_path,
758            new_path: new_file_path,
759            content_hash,
760            write_id,
761            warnings: outcome_warnings,
762        })
763    }
764}
765
766#[cfg(test)]
767mod tests;