Skip to main content

memstead_base/engine/mutation/create/
mod.rs

1//! `Engine::create_entity` — write a new entity into a mount's
2//! backend and update the in-memory store.
3//!
4//! The module is cut by the phases every mutation shares, one file
5//! each, in the order a create runs them: [`resolve`] locates the
6//! mount, the schema and the type; [`validate`] gates the inputs and
7//! derives the identity; [`compose`] synthesises the entity, renders
8//! it and judges the composed state; [`stage`] puts the write and its
9//! sidecars into the backend's pending buffer; [`commit`] lands the
10//! commit, the provenance and the store application; [`outcome`]
11//! shapes what goes back on the wire. [`batch`] drives the same phases
12//! for `batch_create`, preparing every item first and committing once
13//! per mem.
14
15mod batch;
16mod commit;
17mod compose;
18mod outcome;
19mod resolve;
20mod stage;
21#[cfg(test)]
22mod tests;
23mod validate;
24
25use crate::entity::EntityId;
26use crate::ops::WarningHint;
27use crate::vcs::{Actor, ClientId, CommitContext};
28
29use super::super::{CreateEntityArgs, CreateEntityOutcome, Engine, EngineError};
30
31/// Everything a validated create needs to hit disk — the create-side
32/// twin of `PreparedUpdate`. Produced by `Engine::prepare_create`,
33/// consumed by `Engine::commit_prepared_create` (single item) and by
34/// `Engine::batch_create` (staged all-first, one commit per mem).
35pub(in crate::engine::mutation) struct PreparedCreate {
36    pub(in crate::engine::mutation) mount_idx: usize,
37    pub(in crate::engine::mutation) id: EntityId,
38    pub(in crate::engine::mutation) title: String,
39    pub(in crate::engine::mutation) mem: String,
40    pub(in crate::engine::mutation) file_path: String,
41    pub(in crate::engine::mutation) markdown: String,
42    pub(in crate::engine::mutation) anchors: Vec<crate::anchor::Anchor>,
43    pub(in crate::engine::mutation) warnings: Vec<WarningHint>,
44    pub(in crate::engine::mutation) type_guidance: std::collections::BTreeMap<String, Vec<String>>,
45    pub(in crate::engine::mutation) relations_declared:
46        Vec<crate::engine::outcomes::RelationDeclared>,
47    /// Inline-relation targets — the commit tail materialises
48    /// forward-reference stubs for the ones the store still lacks.
49    pub(in crate::engine::mutation) relation_targets: Vec<EntityId>,
50    pub(in crate::engine::mutation) type_def: std::sync::Arc<memstead_schema::TypeDefinition>,
51}
52
53/// Outcome of `Engine::prepare_create`: a dry-run completes at prepare
54/// time; a real write returns the staged material.
55pub(in crate::engine::mutation) enum CreatePrepareOutcome {
56    Done(CreateEntityOutcome),
57    Prepared(PreparedCreate),
58}
59
60impl Engine {
61    /// Create a new entity in `args.mem`. Six concerns wired here
62    /// in one shape regardless of which backend serves the mount:
63    ///
64    /// 1. **Capability gating** — rejects mounts with `ReadOnly`
65    ///    capability before reaching the backend.
66    /// 2. **Validator pipeline** — `validate_section_keys` +
67    ///    `parse_metadata_value` enforce the pinned schema's strictness;
68    ///    typed `ValidationError` lifts to `EngineError::Validation`.
69    /// 3. **Provenance** — a `Provenance` record routes through
70    ///    `backend.append_provenance` (folder writes JSONL, git-branch
71    ///    no-ops since the commit subject + trailers carry the same
72    ///    fields).
73    /// 4. **Write + commit atomicity** — `backend.write_entity` then
74    ///    `backend.commit` with the canonical `memstead: create <id>`
75    ///    subject so the git-branch backend's `read_provenance` can
76    ///    recover the kind.
77    /// 5. **Store update** — re-parse the freshly-generated markdown
78    ///    so the in-memory `Store` mirrors disk (including
79    ///    generator-determined `content_hash`).
80    /// 6. **Error envelope** — `BackendError::Sealed` lifts via the
81    ///    `Backend` variant so MCP callers see the typed payload
82    ///    intact; `HashMismatch` propagates likewise.
83    pub fn create_entity(
84        &mut self,
85        args: CreateEntityArgs,
86        actor: Actor,
87        client: Option<&ClientId>,
88        note: Option<&str>,
89    ) -> Result<CreateEntityOutcome, EngineError> {
90        // A create locks its own mem and the mems it refers to; one
91        // that declares a relation on an acyclic relationship takes the
92        // whole workspace, because its cycle guard walks edges in every
93        // mem.
94        let (_write_lock, drift_warnings) = {
95            let (mem, relations, sections) = (&args.mem, &args.relations, &args.sections);
96            let mut locked = crate::engine::write_lock::referred_mems(
97                mem,
98                relations.iter().map(|r| &r.target),
99                args.sections
100                    .values()
101                    .map(String::as_str)
102                    .chain(relations.iter().filter_map(|r| r.description.as_deref())),
103            );
104            locked.push(mem.clone());
105            self.lock_for_verb(
106                !args.dry_run,
107                &locked,
108                std::slice::from_ref(mem),
109                |engine| {
110                    engine.write_needs_full_load(
111                        mem,
112                        relations
113                            .iter()
114                            .map(|r| crate::engine::mutation::EdgeWrite {
115                                rel_type: &r.rel_type,
116                                target_mem: r.target.mem(),
117                                remove: false,
118                            }),
119                        sections.values().map(String::as_str),
120                    )
121                },
122            )?
123        };
124        // Declared relations on an ACYCLIC rel-type (or one in an
125        // `acyclic_sets` set, whose guard walks the set's UNION
126        // subgraph) run the same whole-subgraph cycle guard relate
127        // runs — full load first, or a cycle through a deferred mem's
128        // edge is invisible (see the relate path's comment for the
129        // demonstrated failure). Declared signals on the new entity's
130        // schema or any relation target's schema need the full load
131        // too: the threshold-crossing diff counts edges that can
132        // originate in any mem.
133        if self.write_needs_full_load(
134            &args.mem,
135            args.relations
136                .iter()
137                .map(|r| crate::engine::mutation::EdgeWrite {
138                    rel_type: &r.rel_type,
139                    target_mem: r.target.mem(),
140                    remove: false,
141                }),
142            args.sections.values().map(String::as_str),
143        ) {
144            self.ensure_mems_loaded(None);
145        }
146        match self.prepare_create(args, None, drift_warnings)? {
147            CreatePrepareOutcome::Done(outcome) => Ok(outcome),
148            CreatePrepareOutcome::Prepared(prepared) => {
149                self.commit_prepared_create(prepared, actor, client, note)
150            }
151        }
152    }
153
154    /// Validate a create and compute everything up to (but not
155    /// including) the disk write — the create-side prepare of the
156    /// prepare-all-then-commit split `batch_update` established. Runs
157    /// the resolve, validate and compose phases in that order.
158    /// Returns [`CreatePrepareOutcome::Done`] for a dry-run (its
159    /// outcome is complete), [`CreatePrepareOutcome::Prepared`] for a
160    /// real write the caller commits via
161    /// [`Self::commit_prepared_create`].
162    ///
163    /// `batch_skeleton_ids` is the batch path's staging set: ids the
164    /// current batch has pre-inserted as skeleton entities so
165    /// intra-batch references validate as REAL targets. A create whose
166    /// id is in the set skips the already-exists refusal (the skeleton
167    /// is this very entry's placeholder — batch-side identity checks
168    /// have already refused genuine duplicates). Single-item callers
169    /// pass `None`.
170    /// NOTE: the reload-before-operation drift probe is the CALLER's
171    /// job (single-item: `create_entity` probes its one mem; batch:
172    /// `batch_create` probes every touched mem once, up front). A probe
173    /// inside prepare would reload mid-batch and wipe the staged
174    /// skeletons.
175    pub(in crate::engine::mutation) fn prepare_create(
176        &mut self,
177        args: CreateEntityArgs,
178        batch_skeleton_ids: Option<&std::collections::HashSet<EntityId>>,
179        drift_warnings: Vec<WarningHint>,
180    ) -> Result<CreatePrepareOutcome, EngineError> {
181        let resolved = self.resolve_create(args)?;
182        let validated = self.validate_create(resolved, batch_skeleton_ids, drift_warnings)?;
183        self.compose_create(validated)
184    }
185
186    /// Cap on fully-detailed error envelopes in a refused batch's
187    /// report — bounded reporting for very large failing batches.
188    /// Entries beyond the cap still carry `action: "error"`; the
189    /// result's `errors_suppressed` counts them. Never a silent
190    /// truncation.
191    pub const BATCH_ERROR_REPORT_CAP: usize = 50;
192
193    /// CommitContext-bundling wrapper around [`Self::create_entity`].
194    /// Destructures `CommitContext` into `(actor, client, note)`
195    /// and delegates.
196    pub fn create_entity_with_ctx(
197        &mut self,
198        args: CreateEntityArgs,
199        ctx: &CommitContext<'_>,
200    ) -> Result<CreateEntityOutcome, EngineError> {
201        self.create_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
202    }
203}