memstead-base 0.26.1

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! `Engine::batch_create`: the same phases as a single create, driven
//! over every entry before anything is written — an identity pass
//! that refuses duplicates against the store and within the batch,
//! skeleton staging so intra-batch references validate as real
//! targets, the per-entry prepare (resolve, validate, compose), then
//! stage everything and commit once per mem. A refused or rehearsed
//! batch rolls the store snapshot back and discards every pending
//! buffer.

use std::collections::HashMap;

use crate::engine_fallback_type;
use crate::entity::EntityId;
use crate::entity::id::validate_and_derive_slug;
use crate::entity::parser::parse_markdown;
use crate::entity::store_builder::push_entities_into_store;
use crate::ops::WarningHint;
use crate::provenance::{Provenance, ProvenanceKind};

use super::super::{batch_empty, batch_receipt, batch_refusal, make_stub};
use super::{
    Actor, ClientId, CreateEntityArgs, CreatePrepareOutcome, Engine, EngineError, PreparedCreate,
};

impl Engine {
    /// Atomic batch create — the create-side sibling of
    /// [`Self::batch_update`], with one upgrade and one addition:
    ///
    /// - **Report-all refusal.** Every failing entry is identified with
    ///   its index and typed `{code, message, details}` envelope (the
    ///   family's upgraded contract) — bounded at
    ///   [`Self::BATCH_ERROR_REPORT_CAP`] detailed envelopes, with
    ///   `errors_suppressed` counting the rest. A refused batch writes
    ///   NOTHING: no entity, no edge, no head movement.
    /// - **Intra-batch references resolve as REAL targets.** Every
    ///   entity in the batch is staged (a skeleton store entry carrying
    ///   its declared type) before per-entry validation runs, so an
    ///   edge to a sibling created in the same batch gets full
    ///   target-type shape validation, no transient stub, and no stub
    ///   warning — the batch validates as one graph state, cycles
    ///   included where the schema permits them. Duplicates within the
    ///   batch are refused in the identity pass.
    ///
    /// One workspace load (the caller's), one commit per touched mem
    /// (subject `memstead: batch-create (N entities)`), per-entry
    /// provenance notes exactly like `batch_update`.
    ///
    /// **Rehearsal** (`dry_run: true`): the FULL validation pass runs —
    /// identity, skeleton staging (so intra-batch references resolve as
    /// real targets, cycles included), per-entry prepare, report-all
    /// refusals — then the batch stops before any write. A legal batch
    /// returns the would-be receipt (`applied: true`, per-entry
    /// `"created"` with the prospective ids) with the marker form's
    /// empty `write_id`; an illegal one returns the same refusal a
    /// real call would. Nothing is written, committed, or stubbed.
    pub fn batch_create(
        &mut self,
        creates: Vec<(CreateEntityArgs, Option<String>)>,
        actor: Actor,
        client: Option<&ClientId>,
        dry_run: bool,
    ) -> Result<crate::ops::BatchResult, EngineError> {
        use std::collections::HashSet;

        if creates.is_empty() {
            return Ok(batch_empty());
        }

        // Reload every touched mem once, up front.
        let mut touched_mems: Vec<String> = creates.iter().map(|(a, _)| a.mem.clone()).collect();
        touched_mems.sort();
        touched_mems.dedup();
        // What the roster reconcile and the reloads report (a mem
        // attached since, a sibling's commit, a commit this load
        // completed) rides the receipt like on a single verb.
        let (_write_lock, drift_warnings) = {
            let items = &creates;
            // Each item's own mem, and the mems it refers to.
            let mut locked = touched_mems.clone();
            for (a, _) in items {
                locked.extend(crate::engine::write_lock::referred_mems(
                    &a.mem,
                    a.relations.iter().map(|r| &r.target),
                    a.sections
                        .values()
                        .map(String::as_str)
                        .chain(a.relations.iter().filter_map(|r| r.description.as_deref())),
                ));
            }
            self.lock_for_verb(!dry_run, &locked, &touched_mems, |engine| {
                items.iter().any(|(a, _)| {
                    engine.write_needs_full_load(
                        &a.mem,
                        a.relations
                            .iter()
                            .map(|r| crate::engine::mutation::EdgeWrite {
                                rel_type: &r.rel_type,
                                target_mem: r.target.mem(),
                                remove: false,
                            }),
                        a.sections.values().map(String::as_str),
                    )
                })
            })?
        };
        // Same acyclic-guard rule as the single-item path: declared
        // relations on an ACYCLIC rel-type (or one in an
        // `acyclic_sets` set) walk the whole subgraph, so the walk
        // must see every mem — deferred ones included (see the
        // batch_relate comment). Declared signals on any involved
        // schema need the full load too (see the single-item path).
        if creates.iter().any(|(a, _)| {
            self.write_needs_full_load(
                &a.mem,
                a.relations
                    .iter()
                    .map(|r| crate::engine::mutation::EdgeWrite {
                        rel_type: &r.rel_type,
                        target_mem: r.target.mem(),
                        remove: false,
                    }),
                a.sections.values().map(String::as_str),
            )
        }) {
            self.ensure_mems_loaded(None);
        }

        let store_snapshot = self.store.clone();

        // --- Identity pass: derive every entry's id, refusing
        // duplicates against the pre-batch store AND within the batch.
        // Collect EVERY failure (report-all), never just the first.
        struct IdentityRow {
            id: Option<EntityId>,
            error: Option<EngineError>,
        }
        let mut rows: Vec<IdentityRow> = Vec::with_capacity(creates.len());
        // id → title of the batch entry that claimed it, so a
        // within-batch duplicate can name the occupying title.
        let mut batch_ids: HashMap<EntityId, String> = HashMap::new();
        for (args, _) in &creates {
            let identity = (|| -> Result<EntityId, EngineError> {
                let title = args.title.trim();
                // Divergence warnings ride the per-entry prepare pass
                // below, which re-derives; this pass only needs the id.
                let slug = validate_and_derive_slug(title)?.slug;
                let id = EntityId::new(&args.mem, &slug);
                crate::entity::id::enforce_id_length(id.as_ref())?;
                if let Some(existing) = self.store.get(&id)
                    && !existing.stub
                {
                    return Err(EngineError::AlreadyExists {
                        id: id.to_string(),
                        existing_title: existing.title.clone(),
                        existing_is_stub: false,
                    });
                }
                if let Some(prior_title) = batch_ids.get(&id) {
                    // Duplicate WITHIN the batch — same typed code as
                    // the store collision; the index in the report
                    // localises it.
                    return Err(EngineError::AlreadyExists {
                        id: id.to_string(),
                        existing_title: prior_title.clone(),
                        existing_is_stub: false,
                    });
                }
                Ok(id)
            })();
            match identity {
                Ok(id) => {
                    batch_ids.insert(id.clone(), args.title.trim().to_string());
                    rows.push(IdentityRow {
                        id: Some(id),
                        error: None,
                    });
                }
                Err(e) => rows.push(IdentityRow {
                    id: None,
                    error: Some(e),
                }),
            }
        }

        // --- Skeleton staging: make every batch id a REAL, typed store
        // entry so sibling references validate against present targets.
        // A pre-existing stub at a batch id is replaced (its incoming
        // edges survive the upsert — the same adoption the single-item
        // create performs).
        for ((args, _), row) in creates.iter().zip(rows.iter()) {
            if let Some(id) = &row.id {
                let mut skeleton = make_stub(id, crate::entity::StubKind::ForwardReference);
                skeleton.stub = false;
                skeleton.stub_kind = None;
                skeleton.entity_type = args.entity_type.clone();
                skeleton.title = args.title.trim().to_string();
                self.store.upsert(id.clone(), skeleton);
            }
        }

        // --- Full prepare pass, report-all. Skeletons make intra-batch
        // targets real; each entry's own skeleton is exempted from the
        // duplicate check via `batch_skeleton_ids`.
        let mut prepared: Vec<PreparedCreate> = Vec::new();
        let mut notes: Vec<Option<String>> = Vec::new();
        let mut errors: Vec<(usize, EngineError)> = Vec::new();
        let mut ids_in_order: Vec<EntityId> = Vec::new();
        let skeleton_ids: HashSet<EntityId> = batch_ids.keys().cloned().collect();
        for (i, ((args, note), row)) in creates.into_iter().zip(rows).enumerate() {
            let fallback_id = row
                .id
                .clone()
                .unwrap_or_else(|| EntityId::new(&args.mem, "invalid-entry"));
            ids_in_order.push(fallback_id);
            if let Some(e) = row.error {
                errors.push((i, e));
                continue;
            }
            // Rehearsal is batch-level (the `dry_run` parameter) —
            // per-entry dry-run stays forced off so the prepare pass
            // below never short-circuits into a per-entry preview.
            let mut args = args;
            args.dry_run = false;
            match self.prepare_create(args, Some(&skeleton_ids), Vec::new()) {
                Ok(CreatePrepareOutcome::Prepared(p)) => {
                    // Stage this item's declared edges onto its skeleton
                    // so later items validate against the batch's own
                    // graph state — an intra-batch cycle on an acyclic
                    // rel-type refuses exactly like a stored one
                    // (`validate_edge_acyclicity` walks the store). The
                    // snapshot rollback discards these on refusal; the
                    // apply pass replaces them with the parsed truth.
                    for r in &p.relations_declared {
                        self.store.add_edge(
                            p.id.clone(),
                            crate::store::Edge {
                                rel_type: r.rel_type.clone(),
                                target: r.target.clone(),
                                source: crate::store::EdgeSource::Explicit,
                            },
                        );
                    }
                    ids_in_order[i] = p.id.clone();
                    prepared.push(p);
                    notes.push(note);
                }
                Ok(CreatePrepareOutcome::Done(_)) => unreachable!("dry_run forced off"),
                Err(e) => errors.push((i, e)),
            }
        }

        // The checks form over the store as the whole batch leaves it: a
        // new criterion created beside the plan it closes counts, as it
        // does when the two creates run one after the other.
        if errors.is_empty() {
            let mut post = store_snapshot.clone();
            let mut writes = Vec::new();
            for p in &prepared {
                match crate::entity::parser::parse_markdown(
                    &p.markdown,
                    &p.file_path,
                    p.type_def.as_ref(),
                    &p.mem,
                ) {
                    Ok(parsed) => {
                        post.upsert(parsed.entity.id.clone(), parsed.entity.clone());
                        writes.push((parsed.entity, p.type_def.clone()));
                    }
                    Err(e) => {
                        self.store = store_snapshot;
                        self.discard_all_pending();
                        return Err(EngineError::ParseAfterWrite(e.to_string()));
                    }
                }
            }
            for (entity, blocked) in self.checks_form_after(&post, &store_snapshot, &writes) {
                let i = ids_in_order
                    .iter()
                    .position(|id| *id == entity.id)
                    .unwrap_or(0);
                errors.push((
                    i,
                    EngineError::ConstraintUnsatisfied {
                        entity_type: entity.entity_type.clone(),
                        entity_id: entity.id.to_string(),
                        violations: blocked,
                    },
                ));
            }
        }

        if !errors.is_empty() {
            // Refuse the whole batch; nothing was committed and the
            // store snapshot rolls back the skeletons.
            self.store = store_snapshot;
            self.discard_all_pending();
            return Ok(batch_refusal(ids_in_order, errors));
        }

        // Rehearsal: every entry validated against the batch's own
        // graph state (skeletons made intra-batch targets real) and
        // nothing failed — stop before any write. Roll back the
        // skeleton staging and return the would-be receipt with the
        // marker form's empty `write_id`.
        if dry_run {
            self.store = store_snapshot;
            self.discard_all_pending();
            return Ok(batch_receipt(
                created_actions(prepared),
                Vec::new(),
                Vec::new(),
                String::new(),
            ));
        }

        // --- Stage every write + anchors, then commit once per mem.
        for p in &prepared {
            if let Err(e) = self.stage_prepared_create(p) {
                self.store = store_snapshot;
                self.discard_all_pending();
                return Err(e);
            }
        }
        let mut distinct_mounts: Vec<usize> = Vec::new();
        for p in &prepared {
            if !distinct_mounts.contains(&p.mount_idx) {
                distinct_mounts.push(p.mount_idx);
            }
        }
        let mut mount_commits: Vec<(usize, String)> = Vec::with_capacity(distinct_mounts.len());
        let mut batch_warnings: Vec<WarningHint> = drift_warnings;
        for &m in &distinct_mounts {
            let entity_ids: Vec<String> = prepared
                .iter()
                .filter(|p| p.mount_idx == m)
                .map(|p| p.id.to_string())
                .collect();
            let count = entity_ids.len();
            let subject = format!("memstead: batch-create ({count} entities)");
            // Per-entry notes ride the ONE batch commit's note record as
            // `<id>: <note>` lines:
            // `append_provenance` below is a documented no-op on the
            // git-branch backend, so without this the notes survived
            // nowhere exactly where most writes happen. A batch with no
            // notes carries no note record at all.
            let note_lines: Vec<String> = prepared
                .iter()
                .zip(notes.iter())
                .filter(|(p, _)| p.mount_idx == m)
                .filter_map(|(p, n)| n.as_ref().map(|n| format!("{}: {n}", p.id)))
                .collect();
            let mut ctx = self.commit_context(
                Some("batch_create"),
                actor,
                client.cloned(),
                if note_lines.is_empty() {
                    None
                } else {
                    Some(note_lines.join("\n"))
                },
            );
            ctx.entity_ids = Some(entity_ids);
            // One provenance record per item, landing with the mem's
            // commit.
            let records: Vec<Provenance> = prepared
                .iter()
                .zip(notes.iter())
                .filter(|(p, _)| p.mount_idx == m)
                .map(|(p, note)| {
                    self.provenance_record(
                        ProvenanceKind::Create,
                        &p.id,
                        actor,
                        client,
                        note.as_deref(),
                    )
                })
                .collect();
            match self.commit_or_complete(m, self.commit_staged(m, &subject, &ctx, &records)) {
                Ok(landed) => {
                    batch_warnings.extend(landed.warnings);
                    mount_commits.push((m, landed.write_id));
                }
                Err(e) => {
                    // Mems already committed in this loop stay
                    // committed, so the view of each is reloaded from
                    // storage after the store rollback.
                    self.store = store_snapshot;
                    self.discard_all_pending();
                    let items: Vec<(usize, EntityId)> = prepared
                        .iter()
                        .map(|p| (p.mount_idx, p.id.clone()))
                        .collect();
                    return Err(self.batch_commit_failed(
                        &distinct_mounts,
                        &items,
                        mount_commits,
                        m,
                        e,
                    ));
                }
            }
        }

        // Store application (parse the generated bytes so the store
        // mirrors disk, replacing the skeletons).
        for (m, write_id) in &mount_commits {
            self.record_self_write(*m, write_id);
            batch_warnings.extend(self.stamp_mutation_versions(*m));
        }
        let committed_mounts: Vec<usize> = mount_commits.iter().map(|(m, _)| *m).collect();
        self.after_commits(
            &committed_mounts,
            "store_update",
            &mut batch_warnings,
            |engine| {
                let fallback = engine_fallback_type();
                for p in &prepared {
                    let parse_result =
                        parse_markdown(&p.markdown, &p.file_path, p.type_def.as_ref(), &p.mem)
                            .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
                    push_entities_into_store(
                        &mut engine.store,
                        vec![parse_result],
                        fallback.as_ref(),
                        None,
                    );
                }
                crate::entity::store_builder::remap_alias_target_edge_sources(
                    &mut engine.store,
                    &engine.schemas,
                );
                // Forward-reference stubs for OUT-OF-BATCH targets only —
                // in-batch targets are real entities now.
                let mut out_of_batch_stubs: Vec<(EntityId, crate::entity::StubKind)> = Vec::new();
                for p in &prepared {
                    for target in &p.relation_targets {
                        if !engine.store.contains(target) {
                            let kind = super::super::deferred_verified_stub_kind(engine, target)?;
                            out_of_batch_stubs.push((target.clone(), kind));
                        }
                    }
                }
                for (target, kind) in out_of_batch_stubs {
                    engine
                        .store
                        .upsert(target.clone(), make_stub(&target, kind));
                }
                Ok(())
            },
        );
        self.invalidate_communities();
        self.invalidate_search_indexes();

        let write_id = mount_commits
            .last()
            .map(|(_, s)| s.clone())
            .unwrap_or_default();
        Ok(batch_receipt(
            created_actions(prepared),
            batch_warnings,
            Vec::new(),
            write_id,
        ))
    }
}

/// The create verb's one action word: every prepared item was `created`.
fn created_actions(prepared: Vec<PreparedCreate>) -> Vec<(EntityId, String)> {
    prepared
        .into_iter()
        .map(|p| (p.id, "created".to_string()))
        .collect()
}