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