memstead_base/engine/mutation/update/mod.rs
1//! `Engine::update_entity` and `Engine::batch_update` — rewrite an
2//! entity's sections / metadata in place, optimistically-locked.
3//!
4//! The module is cut by the phases every mutation shares, one file
5//! each, in the order an update runs them: [`resolve`] locates the
6//! mount and the entity and checks the optimistic lock; [`validate`]
7//! gates the payload against the schema; [`compose`] applies the
8//! delta, synthesises relations, renders the entity and judges the
9//! composed state; [`stage`] puts the write and its sidecars into the
10//! backend's pending buffer; [`commit`] lands the commit, the
11//! provenance and the store application; [`outcome`] shapes what goes
12//! back on the wire. [`batch`] drives the same phases for
13//! `batch_update`, preparing every item first and committing once per
14//! mem.
15
16mod batch;
17mod commit;
18mod compose;
19mod outcome;
20mod resolve;
21mod stage;
22/// The sections an update leaves behind where it writes them: the
23/// stored text with the call's text worked in the way the compose
24/// phase does it (a whole section replaces, an append joins with a
25/// newline, patches apply in order). A wiki-link in them is a
26/// reference the update may add, and it can be one that neither the
27/// stored text nor the call's text holds alone. A patch that does not
28/// apply is skipped here; the compose phase refuses it.
29pub(in crate::engine::mutation) fn update_result_texts(
30 engine: &Engine,
31 args: &UpdateEntityArgs,
32) -> Vec<String> {
33 let mut sections = engine
34 .store
35 .get(&args.id)
36 .map(|e| e.sections.clone())
37 .unwrap_or_default();
38 for (key, body) in &args.sections {
39 sections.insert(key.clone(), body.clone());
40 }
41 for (key, value) in &args.append_sections {
42 let existing = sections.get(key).cloned().unwrap_or_default();
43 let joined = if existing.trim().is_empty() {
44 value.clone()
45 } else {
46 format!("{existing}\n{value}")
47 };
48 sections.insert(key.clone(), joined);
49 }
50 for (key, patches) in &args.patch_sections {
51 for patch in patches {
52 let Some(existing) = sections.get(key).cloned() else {
53 continue;
54 };
55 let patched = if patch.all {
56 existing.replace(&patch.old, &patch.new)
57 } else {
58 existing.replacen(&patch.old, &patch.new, 1)
59 };
60 sections.insert(key.clone(), patched);
61 }
62 }
63 args.sections
64 .keys()
65 .chain(args.append_sections.keys())
66 .chain(args.patch_sections.keys())
67 .filter_map(|key| sections.get(key).cloned())
68 .collect()
69}
70
71#[cfg(test)]
72mod tests;
73mod validate;
74
75use std::sync::Arc;
76
77use crate::engine::outcomes::RelationDeclared;
78use crate::entity::EntityId;
79use crate::ops::{ModifiedMetadata, ModifiedSections, WarningHint};
80use crate::vcs::{Actor, ClientId, CommitContext};
81
82use super::super::{Engine, EngineError, UpdateEntityArgs, UpdateEntityOutcome};
83
84/// Result of [`Engine::prepare_update`] — the validation + markdown
85/// step split out of the commit so the batch path can prepare every
86/// item before committing the whole set atomically.
87pub(in crate::engine::mutation) enum PrepareOutcome {
88 /// No commit is needed: the no-op short-circuit (content unchanged)
89 /// and the dry-run preview both return a finished outcome here.
90 Done(UpdateEntityOutcome),
91 /// A real change whose post-mutation markdown is ready to stage +
92 /// commit.
93 Prepared(PreparedUpdate),
94}
95
96/// Everything the commit step needs to stage one prepared update's
97/// disk write and build its outcome. Carries no commit SHA — that's
98/// produced when the (single or batched) commit lands.
99pub(in crate::engine::mutation) struct PreparedUpdate {
100 pub(in crate::engine::mutation) mount_idx: usize,
101 pub(in crate::engine::mutation) id: EntityId,
102 pub(in crate::engine::mutation) mem: String,
103 pub(in crate::engine::mutation) type_def: Arc<memstead_schema::TypeDefinition>,
104 pub(in crate::engine::mutation) file_path: String,
105 pub(in crate::engine::mutation) markdown: String,
106 /// Body wiki-link targets the entity had *before* this mutation —
107 /// the GC sweep scopes orphan-stub detection to these.
108 pub(in crate::engine::mutation) prev_body_targets: std::collections::HashSet<EntityId>,
109 pub(in crate::engine::mutation) modified_date: String,
110 pub(in crate::engine::mutation) modified_sections: ModifiedSections,
111 pub(in crate::engine::mutation) modified_metadata: ModifiedMetadata,
112 pub(in crate::engine::mutation) warnings: Vec<WarningHint>,
113 pub(in crate::engine::mutation) relations_declared: Vec<RelationDeclared>,
114 /// Validated anchors to merge into this entity's sidecar row — staged
115 /// into the same commit as the disk write on the commit step. Empty
116 /// when the update carried no `anchors[]`.
117 pub(in crate::engine::mutation) anchors: Vec<crate::anchor::Anchor>,
118 /// Validated explicit anchor removals, applied before the `anchors`
119 /// merge in the same staged write. Empty when the update carried no
120 /// `anchors_unset[]`.
121 pub(in crate::engine::mutation) anchor_unsets: Vec<crate::anchor::AnchorUnset>,
122 /// True when this update's *sole* delta is the anchors sidecar —
123 /// sections, metadata, and relationships are byte-identical to the
124 /// on-disk entity. Such a commit earns the distinct
125 /// `memstead: anchor <id>` subject (parsed `tool_verb == "anchor"`)
126 /// so an anchor-only refresh — which the `_hash` excludes and which
127 /// therefore produces zero entity deltas — is still observable to an
128 /// `--include-notes` reader. A content-changing update (even one that
129 /// also carries anchors) keeps the `memstead: update <id>` subject:
130 /// its content change already bumps `_hash` and surfaces as a delta,
131 /// so the anchor activity riding it is already visible.
132 pub(in crate::engine::mutation) anchor_only: bool,
133 /// Whether the anchors merge changes the sidecar: `None` when the
134 /// update carried no anchors or unsets, `Some(true)` when a row is
135 /// added, replaced or removed, `Some(false)` when every supplied row
136 /// restates what is stored (then nothing is staged).
137 pub(in crate::engine::mutation) anchors_changed: Option<bool>,
138 /// Whether the entity's content changed in this update: the anchors
139 /// merge then re-baselines a restated row (a sync repair's re-pin).
140 pub(in crate::engine::mutation) content_changed: bool,
141 /// The self-check gates this write passed, when it passed any: the
142 /// commit step carries their records to the post-write hash before
143 /// staging, so the gate that admitted the write still holds after it.
144 /// Boxed: the prepared write already rides inside enum variants sized
145 /// against their peers.
146 pub(in crate::engine::mutation) licensed_self_checks: Option<Box<LicensedSelfChecks>>,
147}
148
149/// The `transition_requires_self_check` gates a prepared write passed on
150/// a fresh independent record of the stored content ([`Engine::gate_transition_forms`]),
151/// with the hash those records are keyed to.
152pub(in crate::engine::mutation) struct LicensedSelfChecks {
153 /// The entity's `content_hash` before the write.
154 pub(in crate::engine::mutation) hash_before: String,
155 /// The passed gates' wire kinds, deduplicated.
156 pub(in crate::engine::mutation) kinds: Vec<String>,
157}
158
159impl Engine {
160 /// Update an entity's sections and/or metadata.
161 ///
162 /// Same six-concern shape as [`Engine::create_entity`]. Optimistic
163 /// locking via `args.expected_hash`: when `Some`, must match the
164 /// store's current `content_hash` or returns
165 /// [`EngineError::HashMismatch`]. The new engine's MCP-facing
166 /// callers should always pass the hash; `None` is the
167 /// `--force`-style escape hatch.
168 ///
169 /// Internally a two-step pipeline: [`Self::prepare_update`] runs
170 /// all validation and computes the post-mutation markdown without
171 /// committing, then [`Self::commit_prepared_update`] stages and
172 /// commits the result. The split lets [`Self::batch_update`]
173 /// prepare every item up front and commit the whole batch as one
174 /// atomic unit.
175 pub fn update_entity(
176 &mut self,
177 args: UpdateEntityArgs,
178 actor: Actor,
179 client: Option<&ClientId>,
180 note: Option<&str>,
181 ) -> Result<UpdateEntityOutcome, EngineError> {
182 // The lock first, then the ids: a bare slug, on the entity or on
183 // a relation target, is resolved under the lock against the
184 // reloaded view, and a call that carries one takes the whole
185 // workspace for it. So does an update that declares a relation
186 // on an acyclic relationship, whose cycle guard walks edges in
187 // every mem. Otherwise the update locks its own mem; a stale
188 // hash for the targeted entity then trips a real
189 // `HASH_MISMATCH`, an unrelated concurrent write leaves this
190 // entity's hash intact. The announcements of resolved ids lead
191 // the outcome's warnings.
192 let mut args = args;
193 let named_mem = args.id.mem().to_string();
194 let short = named_mem.is_empty()
195 || args
196 .declare_relations
197 .iter()
198 .any(|r| r.target.mem().is_empty());
199 let (_write_lock, reloaded) = {
200 let declared = &args.declare_relations;
201 let update = &args;
202 // Its own mem, and the mems its result refers to.
203 self.lock_for_verb_referring(
204 !args.dry_run,
205 std::slice::from_ref(&named_mem),
206 |engine| {
207 let texts = update_result_texts(engine, update);
208 crate::engine::write_lock::referred_mems(
209 &named_mem,
210 declared.iter().map(|r| &r.target),
211 texts
212 .iter()
213 .map(String::as_str)
214 .chain(declared.iter().filter_map(|r| r.description.as_deref())),
215 )
216 },
217 |engine| {
218 short || {
219 let texts = update_result_texts(engine, update);
220 engine.write_needs_full_load(
221 &named_mem,
222 declared.iter().map(|r| crate::engine::mutation::EdgeWrite {
223 rel_type: &r.rel_type,
224 target_mem: r.target.mem(),
225 remove: false,
226 }),
227 texts.iter().map(String::as_str),
228 )
229 }
230 },
231 )?
232 };
233 let (resolved, short_hint) = self.resolve_entity_id(&args.id)?;
234 args.id = resolved;
235 let mut drift_warnings: Vec<WarningHint> = short_hint.into_iter().collect();
236 for r in &mut args.declare_relations {
237 let (target, hint) = self.resolve_entity_id(&r.target)?;
238 r.target = target;
239 drift_warnings.extend(hint);
240 }
241 drift_warnings.extend(reloaded);
242 // Declared relations on an ACYCLIC rel-type (or one in an
243 // `acyclic_sets` set, whose guard walks the set's UNION
244 // subgraph) run the same whole-subgraph cycle guard relate
245 // runs — full load first, or a cycle through a deferred mem's
246 // edge is invisible (see the relate path's comment for the
247 // demonstrated failure). Declared signals on the entity's
248 // schema or any relation target's schema need the full load
249 // too: the threshold-crossing diff counts edges that can
250 // originate in any mem.
251 let result_texts = update_result_texts(self, &args);
252 if self.write_needs_full_load(
253 args.id.mem(),
254 args.declare_relations
255 .iter()
256 .map(|r| crate::engine::mutation::EdgeWrite {
257 rel_type: &r.rel_type,
258 target_mem: r.target.mem(),
259 remove: false,
260 }),
261 result_texts.iter().map(String::as_str),
262 ) {
263 self.ensure_mems_loaded(None);
264 }
265 let stubs_before = self.stub_ids();
266 let rehearsal = args.dry_run;
267 let landed = self.prepare_update(args).and_then(|p| match p {
268 PrepareOutcome::Done(outcome) => Ok(outcome),
269 PrepareOutcome::Prepared(prepared) => {
270 self.commit_prepared_update(prepared, actor, client, note)
271 }
272 });
273 self.drop_stubs_of_an_unlanded_write(&stubs_before, &landed, rehearsal);
274 let mut outcome = landed?;
275 drift_warnings.append(&mut outcome.warnings);
276 outcome.warnings = drift_warnings;
277 Ok(outcome)
278 }
279
280 /// Validate an update and compute its post-mutation markdown
281 /// *without* committing — the resolve, validate and compose phases
282 /// in that order. Returns [`PrepareOutcome::Done`] for the
283 /// no-op / dry-run short-circuits (which never commit) and
284 /// [`PrepareOutcome::Prepared`] for a real change whose write the
285 /// caller stages + commits. May mutate the store in place via the
286 /// alias-synthesis auto-stub upsert; the batch path snapshots the
287 /// store before preparing so a refused batch can roll that back.
288 pub(in crate::engine::mutation) fn prepare_update(
289 &mut self,
290 args: UpdateEntityArgs,
291 ) -> Result<PrepareOutcome, EngineError> {
292 let resolved = self.resolve_update(args)?;
293 let validated = self.validate_update(resolved)?;
294 self.compose_update(validated)
295 }
296
297 /// CommitContext-bundling wrapper around [`Self::update_entity`].
298 /// See [`Self::create_entity_with_ctx`] for the rationale.
299 pub fn update_entity_with_ctx(
300 &mut self,
301 args: UpdateEntityArgs,
302 ctx: &CommitContext<'_>,
303 ) -> Result<UpdateEntityOutcome, EngineError> {
304 self.update_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
305 }
306}