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#[cfg(test)]
23mod tests;
24mod validate;
25
26use std::sync::Arc;
27
28use crate::engine::outcomes::RelationDeclared;
29use crate::entity::EntityId;
30use crate::ops::{ModifiedMetadata, ModifiedSections, WarningHint};
31use crate::vcs::{Actor, ClientId, CommitContext};
32
33use super::super::{Engine, EngineError, UpdateEntityArgs, UpdateEntityOutcome};
34
35/// Result of [`Engine::prepare_update`] — the validation + markdown
36/// step split out of the commit so the batch path can prepare every
37/// item before committing the whole set atomically.
38pub(in crate::engine::mutation) enum PrepareOutcome {
39 /// No commit is needed: the no-op short-circuit (content unchanged)
40 /// and the dry-run preview both return a finished outcome here.
41 Done(UpdateEntityOutcome),
42 /// A real change whose post-mutation markdown is ready to stage +
43 /// commit.
44 Prepared(PreparedUpdate),
45}
46
47/// Everything the commit step needs to stage one prepared update's
48/// disk write and build its outcome. Carries no commit SHA — that's
49/// produced when the (single or batched) commit lands.
50pub(in crate::engine::mutation) struct PreparedUpdate {
51 pub(in crate::engine::mutation) mount_idx: usize,
52 pub(in crate::engine::mutation) id: EntityId,
53 pub(in crate::engine::mutation) mem: String,
54 pub(in crate::engine::mutation) type_def: Arc<memstead_schema::TypeDefinition>,
55 pub(in crate::engine::mutation) file_path: String,
56 pub(in crate::engine::mutation) markdown: String,
57 /// Body wiki-link targets the entity had *before* this mutation —
58 /// the GC sweep scopes orphan-stub detection to these.
59 pub(in crate::engine::mutation) prev_body_targets: std::collections::HashSet<EntityId>,
60 pub(in crate::engine::mutation) modified_date: String,
61 pub(in crate::engine::mutation) modified_sections: ModifiedSections,
62 pub(in crate::engine::mutation) modified_metadata: ModifiedMetadata,
63 pub(in crate::engine::mutation) warnings: Vec<WarningHint>,
64 pub(in crate::engine::mutation) relations_declared: Vec<RelationDeclared>,
65 /// Validated anchors to merge into this entity's sidecar row — staged
66 /// into the same commit as the disk write on the commit step. Empty
67 /// when the update carried no `anchors[]`.
68 pub(in crate::engine::mutation) anchors: Vec<crate::anchor::Anchor>,
69 /// Validated explicit anchor removals, applied before the `anchors`
70 /// merge in the same staged write. Empty when the update carried no
71 /// `anchors_unset[]`.
72 pub(in crate::engine::mutation) anchor_unsets: Vec<crate::anchor::AnchorUnset>,
73 /// True when this update's *sole* delta is the anchors sidecar —
74 /// sections, metadata, and relationships are byte-identical to the
75 /// on-disk entity. Such a commit earns the distinct
76 /// `memstead: anchor <id>` subject (parsed `tool_verb == "anchor"`)
77 /// so an anchor-only refresh — which the `_hash` excludes and which
78 /// therefore produces zero entity deltas — is still observable to an
79 /// `--include-notes` reader. A content-changing update (even one that
80 /// also carries anchors) keeps the `memstead: update <id>` subject:
81 /// its content change already bumps `_hash` and surfaces as a delta,
82 /// so the anchor activity riding it is already visible.
83 pub(in crate::engine::mutation) anchor_only: bool,
84 /// Whether the anchors merge changes the sidecar: `None` when the
85 /// update carried no anchors or unsets, `Some(true)` when a row is
86 /// added, replaced or removed, `Some(false)` when every supplied row
87 /// restates what is stored (then nothing is staged).
88 pub(in crate::engine::mutation) anchors_changed: Option<bool>,
89 /// Whether the entity's content changed in this update: the anchors
90 /// merge then re-baselines a restated row (a sync repair's re-pin).
91 pub(in crate::engine::mutation) content_changed: bool,
92 /// The self-check gates this write passed, when it passed any: the
93 /// commit step carries their records to the post-write hash before
94 /// staging, so the gate that admitted the write still holds after it.
95 /// Boxed: the prepared write already rides inside enum variants sized
96 /// against their peers.
97 pub(in crate::engine::mutation) licensed_self_checks: Option<Box<LicensedSelfChecks>>,
98}
99
100/// The `transition_requires_self_check` gates a prepared write passed on
101/// a fresh independent record ([`Engine::licensed_self_check_kinds`]),
102/// with the hash those records are keyed to.
103pub(in crate::engine::mutation) struct LicensedSelfChecks {
104 /// The entity's `content_hash` before the write.
105 pub(in crate::engine::mutation) hash_before: String,
106 /// The passed gates' wire kinds, deduplicated.
107 pub(in crate::engine::mutation) kinds: Vec<String>,
108}
109
110impl Engine {
111 /// Update an entity's sections and/or metadata.
112 ///
113 /// Same six-concern shape as [`Engine::create_entity`]. Optimistic
114 /// locking via `args.expected_hash`: when `Some`, must match the
115 /// store's current `content_hash` or returns
116 /// [`EngineError::HashMismatch`]. The new engine's MCP-facing
117 /// callers should always pass the hash; `None` is the
118 /// `--force`-style escape hatch.
119 ///
120 /// Internally a two-step pipeline: [`Self::prepare_update`] runs
121 /// all validation and computes the post-mutation markdown without
122 /// committing, then [`Self::commit_prepared_update`] stages and
123 /// commits the result. The split lets [`Self::batch_update`]
124 /// prepare every item up front and commit the whole batch as one
125 /// atomic unit.
126 pub fn update_entity(
127 &mut self,
128 args: UpdateEntityArgs,
129 actor: Actor,
130 client: Option<&ClientId>,
131 note: Option<&str>,
132 ) -> Result<UpdateEntityOutcome, EngineError> {
133 // A short id resolves (or refuses) before anything reads its
134 // mem; the announcement leads the outcome's warnings.
135 let mut args = args;
136 let (resolved, short_hint) = self.resolve_entity_id(&args.id)?;
137 args.id = resolved;
138 let mut drift_warnings: Vec<WarningHint> = short_hint.into_iter().collect();
139 for r in &mut args.declare_relations {
140 let (target, hint) = self.resolve_entity_id(&r.target)?;
141 r.target = target;
142 drift_warnings.extend(hint);
143 }
144 // Reload-before-operation: probe the mem ref and reload if a
145 // sibling advanced it, so the `expected_hash` compare inside
146 // `prepare_update` runs against current truth. A stale hash for
147 // the targeted entity then trips a real `HASH_MISMATCH`; an
148 // unrelated concurrent write leaves this entity's hash intact
149 // and the update proceeds. The drift notice rides the outcome.
150 drift_warnings.extend(self.reload_if_stale(Some(args.id.mem())));
151 // Declared relations on an ACYCLIC rel-type (or one in an
152 // `acyclic_sets` set, whose guard walks the set's UNION
153 // subgraph) run the same whole-subgraph cycle guard relate
154 // runs — full load first, or a cycle through a deferred mem's
155 // edge is invisible (see the relate path's comment for the
156 // demonstrated failure). Declared signals on the entity's
157 // schema or any relation target's schema need the full load
158 // too: the threshold-crossing diff counts edges that can
159 // originate in any mem.
160 if args.declare_relations.iter().any(|r| {
161 self.schemas.get(args.id.mem()).is_some_and(|s| {
162 s.relationship_acyclic(&r.rel_type)
163 || s.acyclic_set_containing(&r.rel_type).is_some()
164 }) || self
165 .schemas
166 .get(r.target.mem())
167 .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
168 }) || self
169 .schemas
170 .get(args.id.mem())
171 .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
172 {
173 self.ensure_mems_loaded(None);
174 }
175 let mut outcome = match self.prepare_update(args)? {
176 PrepareOutcome::Done(outcome) => outcome,
177 PrepareOutcome::Prepared(prepared) => {
178 self.commit_prepared_update(prepared, actor, client, note)?
179 }
180 };
181 drift_warnings.append(&mut outcome.warnings);
182 outcome.warnings = drift_warnings;
183 Ok(outcome)
184 }
185
186 /// Validate an update and compute its post-mutation markdown
187 /// *without* committing — the resolve, validate and compose phases
188 /// in that order. Returns [`PrepareOutcome::Done`] for the
189 /// no-op / dry-run short-circuits (which never commit) and
190 /// [`PrepareOutcome::Prepared`] for a real change whose write the
191 /// caller stages + commits. May mutate the store in place via the
192 /// alias-synthesis auto-stub upsert; the batch path snapshots the
193 /// store before preparing so a refused batch can roll that back.
194 pub(in crate::engine::mutation) fn prepare_update(
195 &mut self,
196 args: UpdateEntityArgs,
197 ) -> Result<PrepareOutcome, EngineError> {
198 let resolved = self.resolve_update(args)?;
199 let validated = self.validate_update(resolved)?;
200 self.compose_update(validated)
201 }
202
203 /// CommitContext-bundling wrapper around [`Self::update_entity`].
204 /// See [`Self::create_entity_with_ctx`] for the rationale.
205 pub fn update_entity_with_ctx(
206 &mut self,
207 args: UpdateEntityArgs,
208 ctx: &CommitContext<'_>,
209 ) -> Result<UpdateEntityOutcome, EngineError> {
210 self.update_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
211 }
212}