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 let drift_warnings = self.reload_if_stale(Some(&args.mem));
91 // Declared relations on an ACYCLIC rel-type (or one in an
92 // `acyclic_sets` set, whose guard walks the set's UNION
93 // subgraph) run the same whole-subgraph cycle guard relate
94 // runs — full load first, or a cycle through a deferred mem's
95 // edge is invisible (see the relate path's comment for the
96 // demonstrated failure). Declared signals on the new entity's
97 // schema or any relation target's schema need the full load
98 // too: the threshold-crossing diff counts edges that can
99 // originate in any mem.
100 if args.relations.iter().any(|r| {
101 self.schemas.get(&args.mem).is_some_and(|s| {
102 s.relationship_acyclic(&r.rel_type)
103 || s.acyclic_set_containing(&r.rel_type).is_some()
104 }) || self
105 .schemas
106 .get(r.target.mem())
107 .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
108 }) || self
109 .schemas
110 .get(&args.mem)
111 .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
112 {
113 self.ensure_mems_loaded(None);
114 }
115 match self.prepare_create(args, None, drift_warnings)? {
116 CreatePrepareOutcome::Done(outcome) => Ok(outcome),
117 CreatePrepareOutcome::Prepared(prepared) => {
118 self.commit_prepared_create(prepared, actor, client, note)
119 }
120 }
121 }
122
123 /// Validate a create and compute everything up to (but not
124 /// including) the disk write — the create-side prepare of the
125 /// prepare-all-then-commit split `batch_update` established. Runs
126 /// the resolve, validate and compose phases in that order.
127 /// Returns [`CreatePrepareOutcome::Done`] for a dry-run (its
128 /// outcome is complete), [`CreatePrepareOutcome::Prepared`] for a
129 /// real write the caller commits via
130 /// [`Self::commit_prepared_create`].
131 ///
132 /// `batch_skeleton_ids` is the batch path's staging set: ids the
133 /// current batch has pre-inserted as skeleton entities so
134 /// intra-batch references validate as REAL targets. A create whose
135 /// id is in the set skips the already-exists refusal (the skeleton
136 /// is this very entry's placeholder — batch-side identity checks
137 /// have already refused genuine duplicates). Single-item callers
138 /// pass `None`.
139 /// NOTE: the reload-before-operation drift probe is the CALLER's
140 /// job (single-item: `create_entity` probes its one mem; batch:
141 /// `batch_create` probes every touched mem once, up front). A probe
142 /// inside prepare would reload mid-batch and wipe the staged
143 /// skeletons.
144 pub(in crate::engine::mutation) fn prepare_create(
145 &mut self,
146 args: CreateEntityArgs,
147 batch_skeleton_ids: Option<&std::collections::HashSet<EntityId>>,
148 drift_warnings: Vec<WarningHint>,
149 ) -> Result<CreatePrepareOutcome, EngineError> {
150 let resolved = self.resolve_create(args)?;
151 let validated = self.validate_create(resolved, batch_skeleton_ids, drift_warnings)?;
152 self.compose_create(validated)
153 }
154
155 /// Cap on fully-detailed error envelopes in a refused batch's
156 /// report — bounded reporting for very large failing batches.
157 /// Entries beyond the cap still carry `action: "error"`; the
158 /// result's `errors_suppressed` counts them. Never a silent
159 /// truncation.
160 pub const BATCH_ERROR_REPORT_CAP: usize = 50;
161
162 /// CommitContext-bundling wrapper around [`Self::create_entity`].
163 /// Destructures `CommitContext` into `(actor, client, note)`
164 /// and delegates.
165 pub fn create_entity_with_ctx(
166 &mut self,
167 args: CreateEntityArgs,
168 ctx: &CommitContext<'_>,
169 ) -> Result<CreateEntityOutcome, EngineError> {
170 self.create_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
171 }
172}