memstead-base 0.24.0

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
//! Compose phase of a create: synthesise the entity the generator
//! renders (inline relations, alias-synthesised relations from body
//! wiki-links), enforce the alias-existence invariant, render the
//! markdown, and judge the composed state — auto-stubbed link targets,
//! declared section formats, required outgoing edges, declared
//! constraints. A dry-run completes here; a real write leaves as the
//! staged material the commit phase lands.

use std::collections::HashMap;

use crate::entity::{Entity, EntityId, Relationship, normalise_description};
use crate::ops::WarningHint;

use super::validate::ValidatedCreate;
use super::{CreatePrepareOutcome, Engine, EngineError, PreparedCreate};

impl Engine {
    /// Synthesise, render and judge the composed entity; return the
    /// dry-run outcome or the prepared write.
    pub(super) fn compose_create(
        &self,
        validated: ValidatedCreate,
    ) -> Result<CreatePrepareOutcome, EngineError> {
        let ValidatedCreate {
            args,
            mount_idx,
            type_def,
            id,
            file_path,
            metadata,
            anchors: validated_anchors,
            mut warnings,
            type_guidance,
        } = validated;

        // 7. Synthesise the in-memory entity for the generator. The
        //    `content_hash` and `heading_spans` are derived; left
        //    blank because we re-parse the generated bytes below.
        //    Inline relations land in `relationships` so the
        //    generator emits them and the post-parse re-ingest
        //    rebuilds the edges in the store.
        let relationships: Vec<Relationship> = args
            .relations
            .iter()
            .map(|r| Relationship {
                rel_type: r.rel_type.clone(),
                target: r.target.clone(),
                description: normalise_description(r.description.as_deref()),
            })
            .collect();
        // Pre-compute the `relations_declared` outcome echo. Read
        // `target_was_stubbed` against the pre-mutation store state
        // (the post-parse `push_entities_into_store` step will
        // auto-stub absent targets). Shape matches
        // `memstead_update.relations_declared` so callers see a uniform
        // wire shape across the two tools.
        let relations_declared: Vec<crate::engine::outcomes::RelationDeclared> = args
            .relations
            .iter()
            .map(|r| crate::engine::outcomes::RelationDeclared {
                rel_type: r.rel_type.clone(),
                target: r.target.clone(),
                target_was_stubbed: !self.store.contains(&r.target),
            })
            .collect();
        let mut entity_for_render = Entity {
            id: id.clone(),
            title: args.title.clone(),
            entity_type: args.entity_type.clone(),
            mem: args.mem.clone(),
            file_path: file_path.clone(),
            metadata,
            sections: args.sections,
            relationships,
            content_hash: String::new(),
            stub: false,
            stub_kind: None,
            heading_spans: HashMap::new(),
            raw_section_headings: Vec::new(),
        };
        // Alias-synthesis pass: for schemas declaring
        // `alias_target_rel_type`, append engine-emitted relations of
        // that rel-type for every body wiki-link not already backed.
        // Cross-mem refusal aborts the create — no partial state.
        // Schemas without the pointer fall through unchanged and the
        // validator below catches the missing relations.
        //
        // The returned `Vec<Relationship>` is the per-call set of
        // relations the pass just emitted (in body iteration order).
        // It feeds the `InlineWikiLinkAutoStubbed` emission below —
        // using the post-mutation `entity.relationships` as the source
        // via `parse_markdown` filters out the body-link targets
        // because the parser-side `relationships`-coverage filter has
        // already absorbed them.
        let empty_prev_targets = std::collections::HashSet::new();
        let alias_outcome = super::super::synthesise_alias_relations(
            self,
            &empty_prev_targets,
            &mut entity_for_render,
        )?;
        let synthesised_relations = alias_outcome.emitted;
        if alias_outcome.self_link_ignored {
            warnings.push(WarningHint::SelfLinkIgnored { id: id.clone() });
        }
        let undeclared_targets: std::collections::HashSet<crate::entity::EntityId> = alias_outcome
            .undeclared_dropped
            .iter()
            .map(|d| d.target.clone())
            .collect();
        for dropped in alias_outcome.undeclared_dropped {
            warnings.push(WarningHint::CrossSchemaLinkUndeclared {
                from: id.clone(),
                target: dropped.target,
                source_schema: dropped.source_schema,
                target_schema: dropped.target_schema,
            });
        }

        // Alias-existence invariant: every body wiki-link must be
        // backed by an entry in `entity.relationships` (the auto-managed
        // `## Relationships` section). Runs unconditionally on every
        // Write-Mem create. See [`scan_wikilinks_without_relation`].
        let missing =
            super::super::scan_wikilinks_without_relation(&entity_for_render, &undeclared_targets)?;
        if !missing.is_empty() {
            return Err(EngineError::WikiLinkWithoutRelation {
                from_id: id.to_string(),
                missing: missing
                    .into_iter()
                    .map(|(section_key, target)| crate::engine::MissingWikiLink {
                        section_key,
                        target_id: target.to_string(),
                    })
                    .collect(),
            });
        }

        let markdown = super::super::render_for_write(&entity_for_render, type_def.as_ref())?;

        // 7a. Inline `[[wiki-link]]` patterns in section bodies that
        //     point at non-existent targets get auto-stubbed by the
        //     loader on re-ingest. Surface the would-be stubs as a
        //     warning so prose-induced ghosts are reviewable. Mirrors
        //     `memstead_relate`'s `AUTO_STUB_CREATED` observation
        //     discipline.
        //
        //     The input set is the relations the alias-synthesis pass
        //     emitted on this call — NOT a re-parse of the generated
        //     markdown. `parse_markdown` filters its `inline_links`
        //     against the entity's `relationships` vec (which the
        //     synthesis pass has already appended to), so the
        //     pre-fix path saw `inline_links: []` and never fired
        //     the warning. The synthesised vec is the authoritative
        //     per-call source.
        let auto_stubbed: Vec<EntityId> = synthesised_relations
            .iter()
            .filter_map(|rel| {
                if !self.store.contains(&rel.target) {
                    Some(rel.target.clone())
                } else {
                    None
                }
            })
            .collect();
        if !auto_stubbed.is_empty() {
            warnings.push(WarningHint::InlineWikiLinkAutoStubbed {
                from: id.clone(),
                stubs: auto_stubbed,
            });
        }

        // 7a-bis. Required-outgoing evaluation — the warning the tool
        // descriptions have promised all along. Runs now that every
        // edge this create carries (declared + alias-synthesised) is
        // known, through the same evaluation the health sweep uses
        // (one implementation; the two surfaces cannot disagree). A
        // warning, never a refusal: entities are legitimately built up
        // over several calls.
        // Section-format evaluation (plan 08): each written section
        // body against its declared markdown shape, judged by the
        // real CommonMark reduction. Block-tier refuses with the
        // first violation, pre-commit; warn-tier surfaces via the
        // health sweep, never at write time.
        for def in &type_def.sections {
            if def.format_severity != memstead_schema::ConstraintSeverity::Block {
                continue;
            }
            // Absent-as-empty: the generator renders every declared
            // section heading (empty body when omitted), so the
            // format judges the state that actually lands on disk —
            // an expression that does not admit the empty sequence
            // makes its section effectively required (declare a `?`
            // or `*` form to admit omission). Without this, an
            // omitting create passes while health flags the same
            // on-disk state — write path and health must agree.
            let body = entity_for_render
                .sections
                .get(def.key.as_str())
                .map(String::as_str)
                .unwrap_or("");
            if let Some(first) = crate::section_format::check_section_format(def, body)
                .into_iter()
                .next()
            {
                return Err(EngineError::SectionFormatRefused {
                    entity_type: entity_for_render.entity_type.clone(),
                    entity_id: id.to_string(),
                    violation: first,
                });
            }
        }

        let unsatisfied = crate::ops::health::unsatisfied_required_outgoing(
            &entity_for_render,
            type_def.as_ref(),
        );
        if !unsatisfied.is_empty() {
            // A block declared `severity: block` promotes the warning
            // to a refusal — evaluated here, before any disk or store
            // effect, so a refused create leaves nothing behind.
            let blocked: Vec<_> = unsatisfied
                .iter()
                .filter(|b| b.severity == memstead_schema::ConstraintSeverity::Block)
                .cloned()
                .collect();
            if !blocked.is_empty() {
                return Err(EngineError::RequiredOutgoingUnsatisfied {
                    entity_type: entity_for_render.entity_type.clone(),
                    entity_id: id.to_string(),
                    missing: blocked,
                });
            }
            warnings.push(WarningHint::MissingRequiredOutgoing {
                entity_type: entity_for_render.entity_type.clone(),
                entity_id: id.clone(),
                missing: unsatisfied,
            });
        }

        // Declared-constraints evaluation (`requires_when`, …) — the
        // same single evaluation the health `constraints` include
        // runs. Block-tier violations refuse; warn-tier violations
        // warn and the write proceeds.
        let check_provider = self.check_standing_provider();
        let violated = crate::ops::health::unsatisfied_constraints(
            &self.store,
            &entity_for_render,
            type_def.as_ref(),
            None,
            Some(&check_provider),
        );
        if !violated.is_empty() {
            let blocked: Vec<_> = violated
                .iter()
                .filter(|v| v.severity() == memstead_schema::ConstraintSeverity::Block)
                .cloned()
                .collect();
            if !blocked.is_empty() {
                return Err(EngineError::ConstraintUnsatisfied {
                    entity_type: entity_for_render.entity_type.clone(),
                    entity_id: id.to_string(),
                    violations: blocked,
                });
            }
            warnings.push(WarningHint::ConstraintUnsatisfied {
                entity_type: entity_for_render.entity_type.clone(),
                entity_id: id.clone(),
                violations: violated,
            });
        }

        let prepared = PreparedCreate {
            mount_idx,
            id,
            title: args.title,
            mem: args.mem,
            file_path,
            markdown,
            anchors: validated_anchors,
            warnings,
            type_guidance,
            relations_declared,
            relation_targets: args.relations.iter().map(|r| r.target.clone()).collect(),
            type_def,
        };

        // 7b. Dry-run: compute prospective hash from the in-memory
        //     entity and return without touching disk, store, or
        //     edges. Mirrors full's `CreateArgs.dry_run` semantics —
        //     `content_hash` carries the prospective hash since
        //     there's no current to differentiate from. `write_id`
        //     is empty. Stub creation is also skipped (no
        //     in-memory side effects).
        if args.dry_run {
            // `created_date` from the in-memory entity (the
            // metadata-construction loop already set the
            // init_timestamp default to `today_iso`-equivalent).
            let created_date = entity_for_render
                .metadata
                .get("created_date")
                .map(|v| v.to_frontmatter_string())
                .unwrap_or_default();
            return Ok(CreatePrepareOutcome::Done(
                self.create_dry_run_outcome(prepared, created_date),
            ));
        }

        Ok(CreatePrepareOutcome::Prepared(prepared))
    }
}