memstead_base/engine/mutation/rename/mod.rs
1//! `Engine::rename_entity` — change an entity's slug, move its file
2//! on the backend, and rewrite the in-memory store.
3//!
4//! The module is cut by the phases every mutation shares, one file
5//! each, in the order a rename runs them: [`validate`] gates the call
6//! and derives the new identity; [`compose`] renders the renamed
7//! entity and, once [`resolve`] has found who refers to it and where
8//! the engine may write, every referrer's rewrite; [`stage`] puts one
9//! mem's part of the rename into its backend's pending buffer;
10//! [`commit`] lands the commits, the provenance and the store
11//! application, and shapes the outcome.
12
13mod commit;
14mod compose;
15mod resolve;
16mod stage;
17#[cfg(test)]
18mod tests;
19mod validate;
20
21use std::sync::Arc;
22
23use indexmap::IndexMap;
24use memstead_schema::TypeDefinition;
25
26use crate::entity::id::SlugDerivation;
27use crate::entity::{Entity, EntityId};
28use crate::ops::WarningHint;
29use crate::vcs::{Actor, ClientId, CommitContext};
30
31use super::super::{Engine, EngineError, RenameEntityArgs, RenameEntityOutcome};
32
33/// What the validate phase ends in.
34enum RenameValidation {
35 /// The new title derives the slug the entity has: nothing to do,
36 /// and the outcome says so.
37 Noop(RenameEntityOutcome),
38 Proceed(Box<ValidatedRename>),
39}
40
41/// A rename that passed its gates: the entity as it stands and the
42/// identity it moves to.
43struct ValidatedRename {
44 id: EntityId,
45 new_id: EntityId,
46 mem: String,
47 mount_idx: usize,
48 new_title: String,
49 derivation: SlugDerivation,
50 entity: Entity,
51 type_def: Arc<TypeDefinition>,
52}
53
54/// The entities that refer to the renamed one, by where a rewrite can
55/// land. Each list is sorted by id, so the writes of a rename replay
56/// in one order across runs.
57struct RenameReferrers {
58 same_mem: Vec<EntityId>,
59 cross_mem_write: Vec<EntityId>,
60 /// In a read-only mem: left as they are; the old id stays behind as
61 /// a stub that holds their edges.
62 readonly: Vec<EntityId>,
63}
64
65/// One referrer's rewrite: its file as it will be written, and its
66/// sections before and after. A wiki-link retarget moves marked bytes
67/// without being an authorship event, so the origin marks of an
68/// adopted body are recomputed over the new bytes in the same commit;
69/// unfollowed, ordinary housekeeping would serve a contributor's
70/// untouched sentences as the workspace's own.
71struct ReferrerRewrite {
72 id: EntityId,
73 markdown: String,
74 file_path: String,
75 type_def: Arc<TypeDefinition>,
76 before: IndexMap<String, String>,
77 after: IndexMap<String, String>,
78}
79
80/// One peer mem's part of a rename: its mount and its referrers'
81/// rewrites, which land in one commit of that mem. The peer mem's own
82/// record is the one that holds its referrers' marks.
83struct PeerMemPlan {
84 mount_idx: usize,
85 mem: String,
86 rewrites: Vec<ReferrerRewrite>,
87}
88
89/// A rename computed up to, and not including, its first write.
90struct PreparedRename {
91 id: EntityId,
92 new_id: EntityId,
93 mem: String,
94 mount_idx: usize,
95 new_title: String,
96 derivation: SlugDerivation,
97 type_def: Arc<TypeDefinition>,
98 /// The renamed entity as it will be written.
99 markdown: String,
100 old_file_path: String,
101 new_file_path: String,
102 /// The renamed entity's sections before and after its links to
103 /// itself were retargeted.
104 before_sections: IndexMap<String, String>,
105 after_sections: IndexMap<String, String>,
106 same_mem: Vec<ReferrerRewrite>,
107 peers: std::collections::BTreeMap<String, PeerMemPlan>,
108 readonly_referrers: Vec<EntityId>,
109}
110
111impl Engine {
112 /// Positional + CommitContext wrapper around
113 /// [`Self::rename_entity`].
114 pub fn rename_entity_with_ctx(
115 &mut self,
116 old_id: &EntityId,
117 new_title: &str,
118 expected_hash: crate::ExpectedHash,
119 ctx: &CommitContext<'_>,
120 ) -> Result<RenameEntityOutcome, EngineError> {
121 let args = RenameEntityArgs {
122 id: old_id.clone(),
123 expected_hash,
124 new_title: new_title.to_string(),
125 };
126 self.rename_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
127 }
128
129 /// Rename an entity by changing its title — the slug, id, and
130 /// on-disk file path follow.
131 ///
132 /// **Same-mem referrers and self-references are rewritten
133 /// atomically.** The renaming entity is treated as the first
134 /// referrer of itself: every entry in its own `relationships`
135 /// list whose target equals the old id is updated to point at
136 /// the new id, and every `[[<old-slug>]]` token in its own
137 /// section bodies is rewritten to the new slug (respecting
138 /// fenced-code and inline-code masking). Every other entity in
139 /// the same mem that pointed at the old id (via an explicit
140 /// relation or an inline body wiki-link) gets the same two-
141 /// surface rewrite. All rewrites land in one per-mem commit.
142 /// Cross-mem referrers in other Write mounts get the same
143 /// rewrite (colon-form body links and relationship rows), each
144 /// peer mem in its own commit pinned to the parent the scan saw,
145 /// gated by the cross-mem link policy; a ReadOnly-mount referrer
146 /// is left as it is and reported as a residual stub.
147 ///
148 /// The peer mems commit first and the renamed entity's own mem
149 /// last. If a commit fails after another landed, the call returns
150 /// `RENAME_PARTIAL_FAILURE`; the entity is then still under the id
151 /// and the hash the caller named, and the identical call completes
152 /// the rename.
153 pub fn rename_entity(
154 &mut self,
155 args: RenameEntityArgs,
156 actor: Actor,
157 client: Option<&ClientId>,
158 note: Option<&str>,
159 ) -> Result<RenameEntityOutcome, EngineError> {
160 // A short id resolves (or refuses) before anything reads its mem.
161 let mut args = args;
162
163 // A rename learns what it writes by reading the workspace: who
164 // refers to the entity, in which mems. So it takes every
165 // writable mount's lock, reloads every mem and loads the
166 // deferred ones before it looks for a referrer; a referrer in a
167 // mem that was never loaded is rewritten like any other, and no
168 // peer's rewrite is computed from a view older than its lock.
169 let (_write_lock, reloaded) = self.lock_workspace_for_write_if(true)?;
170 // A bare slug is resolved under the lock, against the reloaded
171 // view: which mem carries a slug is a fact about every mem.
172 let (resolved, short_hint) = self.resolve_entity_id(&args.id)?;
173 args.id = resolved;
174 let id = &args.id;
175 let mem = id.mem().to_string();
176 let mut drift_warnings: Vec<WarningHint> = short_hint.into_iter().collect();
177 drift_warnings.extend(reloaded);
178 let mount_idx = self.writable_mount_index(&mem)?;
179
180 let validated = match self.validate_rename(&args, mount_idx)? {
181 RenameValidation::Noop(outcome) => return Ok(outcome),
182 RenameValidation::Proceed(validated) => *validated,
183 };
184 let prepared = self.prepare_rename(validated)?;
185 self.commit_prepared_rename(prepared, drift_warnings, actor, client, note)
186 }
187
188 /// Everything a rename computes before it writes: the renamed
189 /// entity, who refers to it, and every referrer's rewrite, in that
190 /// order.
191 fn prepare_rename(&self, validated: ValidatedRename) -> Result<PreparedRename, EngineError> {
192 let (next, markdown) = self.compose_renamed_entity(&validated)?;
193 let referrers = self.resolve_rename_referrers(&validated.id, &validated.mem)?;
194 let (same_mem, peers) = self.compose_referrer_rewrites(&validated, &referrers)?;
195 let ValidatedRename {
196 id,
197 new_id,
198 mem,
199 mount_idx,
200 new_title,
201 derivation,
202 entity,
203 type_def,
204 } = validated;
205 Ok(PreparedRename {
206 id,
207 new_id,
208 mem,
209 mount_idx,
210 new_title,
211 derivation,
212 type_def,
213 markdown,
214 old_file_path: entity.file_path,
215 new_file_path: next.file_path,
216 before_sections: entity.sections,
217 after_sections: next.sections,
218 same_mem,
219 peers,
220 readonly_referrers: referrers.readonly,
221 })
222 }
223}