Skip to main content

memstead_base/engine/mutation/
retype.rs

1//! `Engine::retype_entity` — change an entity's type in place.
2//!
3//! The identity triple (`mem` / `id` / `type`) is reserved on `update`
4//! by decision: `type` set refuses `READ_ONLY_FIELD`. A type change is
5//! its own verb because it is its own validation regime — the existing
6//! sections and metadata have to satisfy the TARGET type, and every edge
7//! touching the entity, incoming and outgoing, same-mem and cross-mem,
8//! has to fit the target type's relationship pins — and its own
9//! provenance kind. The id, the file path, and every incoming edge stay:
10//! nothing is deleted and re-created, so history and provenance survive.
11//!
12//! Report-all refusal: every unknown section, missing required section,
13//! unknown or invalid metadata value, unsatisfied block-tier constraint,
14//! and shape-violating edge is collected and returned in ONE envelope
15//! (`RetypeRefused`), with the target's declared sections, its catch-all,
16//! and a proposed `section_map` in the recovery payload, so a second
17//! attempt can be the right one. Nothing is written before the set is
18//! empty.
19//!
20//! The edge re-check on both directions is mandatory, not thoroughness:
21//! the loader drops a shape-invalid edge at the next boot with only a
22//! `PARSED_RELATION_INVALID` warning, so a retype that skipped it would
23//! amputate the graph on restart. Referrers that live in a lazy (deferred,
24//! unloaded) mem are not in the store; they are probed through storage —
25//! the same backend the relate path probes deferred targets through — and
26//! when a deferred mem cannot be enumerated the retype refuses naming it,
27//! never proceeding on the assumption that its edges are fine.
28
29use std::collections::BTreeMap;
30use std::path::Path;
31
32use indexmap::IndexMap;
33
34use crate::engine_fallback_type;
35use crate::entity::EntityId;
36use crate::entity::parser::parse_markdown;
37use crate::entity::store_builder::push_entities_into_store;
38use crate::ops::WarningHint;
39use crate::provenance::{Provenance, ProvenanceKind};
40use crate::runtime_validator::{
41    CatchAllContext, CrossMemRelCheck, READ_ONLY_METADATA_KEYS, ValidationError,
42    missing_required_fields, missing_required_sections, parse_metadata_value,
43    validate_cross_mem_edge, validate_rel_shape, validate_section_content, validate_section_keys,
44};
45use crate::vcs::{Actor, ClientId};
46use crate::workspace::MountCapability;
47
48use super::super::{Engine, EngineError, RetypeEntityArgs, RetypeEntityOutcome};
49use super::unknown_type_error;
50use crate::engine::outcomes::{RetypeEdge, RetypeEdgeDirection, RetypeProblem};
51
52impl Engine {
53    /// Change `args.id`'s type to `args.target_type` in place. See the
54    /// module docs for the contract; the outcome names the old and new
55    /// type, the renamed sections, the edges re-checked, and states that
56    /// check records and derivation baselines on the entity are stale
57    /// (its content hash moved).
58    pub fn retype_entity(
59        &mut self,
60        args: RetypeEntityArgs,
61        actor: Actor,
62        client: Option<&ClientId>,
63        note: Option<&str>,
64    ) -> Result<RetypeEntityOutcome, EngineError> {
65        // A short id resolves (or refuses) before anything reads its mem.
66        let mut args = args;
67        let (resolved, short_hint) = self.resolve_entity_id(&args.id)?;
68        args.id = resolved;
69        let id = &args.id;
70        let mem = id.mem().to_string();
71
72        let mount_idx = self
73            .mounts
74            .iter()
75            .position(|m| m.mount.mem == mem)
76            .ok_or_else(|| self.unknown_mem_error(&mem))?;
77        if self.mounts[mount_idx].mount.capability != MountCapability::Write {
78            return Err(EngineError::ReadOnlyMount(mem));
79        }
80
81        // Reload-before-operation, so the CAS compare and the edge walk
82        // run against current truth.
83        let mut drift_warnings: Vec<WarningHint> = short_hint.into_iter().collect();
84        drift_warnings.extend(self.reload_if_stale(Some(&mem)));
85
86        let entity = self
87            .store
88            .get(id)
89            .ok_or_else(|| EngineError::NotFound { id: id.to_string() })?
90            .clone();
91        if entity.stub {
92            return Err(EngineError::StubNotUpdatable { id: id.to_string() });
93        }
94        if !args.dry_run
95            && let Some(expected) = args.expected_hash.as_deref()
96            && entity.content_hash != expected
97        {
98            return Err(EngineError::HashMismatch {
99                id: id.to_string(),
100                current: entity.content_hash.clone(),
101                is_stub: false,
102            });
103        }
104
105        let schema = self
106            .schemas
107            .get(&mem)
108            .expect("schema present for every registered mount")
109            .clone();
110        let target_def = schema
111            .get_type(&args.target_type)
112            .ok_or_else(|| unknown_type_error(&schema, &args.target_type))?;
113        if entity.entity_type == args.target_type {
114            return Err(EngineError::RetypeNoOp {
115                id: id.to_string(),
116                entity_type: entity.entity_type.clone(),
117            });
118        }
119
120        let mut problems: Vec<RetypeProblem> = Vec::new();
121        let mut warnings: Vec<WarningHint> = Vec::new();
122
123        // ----- Sections: apply the map, then validate against the target -----
124        let mut next = entity.clone();
125        next.entity_type = args.target_type.clone();
126        let mut sections_renamed: Vec<(String, String)> = Vec::new();
127        {
128            let mut mapped: IndexMap<String, String> = IndexMap::new();
129            let mut taken: BTreeMap<String, String> = BTreeMap::new(); // new key -> old key
130            for (key, body) in &entity.sections {
131                let new_key = args
132                    .section_map
133                    .get(key.as_str())
134                    .cloned()
135                    .unwrap_or_else(|| key.clone());
136                if let Some(prev) = taken.get(&new_key) {
137                    problems.push(RetypeProblem::SectionMapCollision {
138                        from: key.clone(),
139                        to: new_key.clone(),
140                        also_from: prev.clone(),
141                    });
142                    continue;
143                }
144                taken.insert(new_key.clone(), key.clone());
145                if new_key != *key {
146                    sections_renamed.push((key.clone(), new_key.clone()));
147                }
148                mapped.insert(new_key, body.clone());
149            }
150            for from in args.section_map.keys() {
151                if !entity.sections.contains_key(from.as_str()) {
152                    problems.push(RetypeProblem::SectionMapSourceMissing {
153                        key: from.clone(),
154                        present: entity.sections.keys().cloned().collect(),
155                    });
156                }
157            }
158            next.sections = mapped;
159        }
160        // Every mapped key against the target's declared sections — one
161        // problem per unknown key (the validator refuses on the first, so
162        // it is asked one key at a time).
163        for key in next.sections.keys() {
164            if let Err(ValidationError::UnknownSection {
165                key,
166                declared,
167                suggestion,
168                ..
169            }) = validate_section_keys(std::iter::once(key.as_str()), target_def.as_ref())
170            {
171                problems.push(RetypeProblem::UnknownSection {
172                    key,
173                    declared,
174                    suggestion,
175                });
176            }
177        }
178        // Body content under the target's catch-all posture.
179        {
180            let declared_headings: Vec<&str> = target_def
181                .sections
182                .iter()
183                .map(|s| s.heading.as_str())
184                .collect();
185            let catch_all = target_def.catch_all_section().map(|s| CatchAllContext {
186                key: s.key.as_str(),
187                entity_type: target_def.name.as_str(),
188                declared_headings: &declared_headings,
189            });
190            if let Err(e) = validate_section_content(
191                next.sections.iter().map(|(k, v)| (k.as_str(), v.as_str())),
192                catch_all,
193            ) {
194                problems.push(RetypeProblem::Validation {
195                    code: e.code(),
196                    message: e.to_string(),
197                    details: e.details(),
198                });
199            }
200        }
201        for missing in missing_required_sections(target_def.as_ref(), &next.sections) {
202            problems.push(RetypeProblem::MissingRequiredSection {
203                key: missing.key,
204                heading: missing.heading,
205                write_rules: missing.write_rules,
206            });
207        }
208
209        // ----- Metadata: every carried value must parse for the target -----
210        {
211            let mut parsed: IndexMap<String, crate::entity::MetadataValue> = IndexMap::new();
212            let mut supplied: IndexMap<String, String> = IndexMap::new();
213            for (key, value) in &entity.metadata {
214                if args.drop_metadata.iter().any(|k| k == key) {
215                    continue;
216                }
217                if READ_ONLY_METADATA_KEYS.contains(&key.as_str()) {
218                    // The identity triple is engine-authoritative: carried
219                    // as is, with `type` set to the target — the one field
220                    // this verb exists to move.
221                    let carried = if key == "type" {
222                        crate::entity::MetadataValue::String(args.target_type.clone())
223                    } else {
224                        value.clone()
225                    };
226                    parsed.insert(key.clone(), carried);
227                    continue;
228                }
229                let raw = value.to_frontmatter_string();
230                match parse_metadata_value(key, &raw, target_def.as_ref()) {
231                    Ok(v) => {
232                        parsed.insert(key.clone(), v);
233                        supplied.insert(key.clone(), raw);
234                    }
235                    Err(e) => {
236                        // A field the target does not declare has one honest
237                        // exit: the caller drops it by name.
238                        let message = if e.code() == "UNKNOWN_METADATA_FIELD" {
239                            format!("{e}; drop it explicitly with drop_metadata [{key}]")
240                        } else {
241                            e.to_string()
242                        };
243                        problems.push(RetypeProblem::Validation {
244                            code: e.code(),
245                            message,
246                            details: e.details(),
247                        })
248                    }
249                }
250            }
251            // The target's defaults fill fields the entity never carried,
252            // the way create seeds them.
253            for field in &target_def.metadata_fields {
254                if parsed.contains_key(field.key.as_str()) || supplied.contains_key(&field.key) {
255                    continue;
256                }
257                if let Some(default) = &field.default_value
258                    && let Ok(v) = parse_metadata_value(&field.key, default, target_def.as_ref())
259                {
260                    parsed.insert(field.key.clone(), v);
261                    supplied.insert(field.key.clone(), default.clone());
262                }
263            }
264            for missing in missing_required_fields(target_def.as_ref(), &supplied) {
265                problems.push(RetypeProblem::MissingRequiredField {
266                    key: missing.key,
267                    description: missing.description,
268                    enum_values: missing.enum_values,
269                });
270            }
271            next.metadata = parsed;
272        }
273
274        // ----- Edges: both directions, same-mem and cross-mem -----
275        let mut edges_rechecked = 0usize;
276        // Outgoing: this entity is the source; its type changes.
277        for rel in &next.relationships {
278            edges_rechecked += 1;
279            let target_type = self
280                .store
281                .get(&rel.target)
282                .filter(|e| !e.stub)
283                .map(|e| e.entity_type.clone());
284            let target_mem = rel.target.mem();
285            let violation = self.edge_shape_violation(
286                &schema,
287                &mem,
288                target_mem,
289                &rel.rel_type,
290                &args.target_type,
291                target_type.as_deref(),
292            );
293            if let Some(e) = violation {
294                problems.push(RetypeProblem::EdgeShape(RetypeEdge {
295                    direction: RetypeEdgeDirection::Outgoing,
296                    from: id.to_string(),
297                    to: rel.target.to_string(),
298                    rel_type: rel.rel_type.clone(),
299                    cross_mem: target_mem != mem,
300                    detail: e.details(),
301                }));
302            }
303        }
304        // Incoming, loaded referrers: this entity is the target.
305        let incoming: Vec<(EntityId, String)> = self
306            .store
307            .incoming(id)
308            .iter()
309            .map(|e| (e.from.clone(), e.rel_type.clone()))
310            .collect();
311        for (from, rel_type) in incoming {
312            let Some(referrer) = self.store.get(&from) else {
313                continue;
314            };
315            edges_rechecked += 1;
316            let from_mem = from.mem().to_string();
317            let referrer_type = referrer.entity_type.clone();
318            // The edge's source schema is the referrer's; the target is this
319            // mem. Same-schema cross-mem edges take the shared schema's pins
320            // exactly as relate and the loader do.
321            let violation = match self.schemas.get(&from_mem).cloned() {
322                Some(referrer_schema) => self.edge_shape_violation(
323                    &referrer_schema,
324                    &from_mem,
325                    &mem,
326                    &rel_type,
327                    &referrer_type,
328                    Some(&args.target_type),
329                ),
330                None => None,
331            };
332            if let Some(e) = violation {
333                problems.push(RetypeProblem::EdgeShape(RetypeEdge {
334                    direction: RetypeEdgeDirection::Incoming,
335                    from: from.to_string(),
336                    to: id.to_string(),
337                    rel_type,
338                    cross_mem: from_mem != mem,
339                    detail: e.details(),
340                }));
341            }
342        }
343        // Incoming, deferred referrers: a lazy mem's entities are not in
344        // the store. Enumerate its storage and check every relation that
345        // names this entity. A mem that cannot be enumerated refuses.
346        edges_rechecked += self.recheck_deferred_referrers(id, &args.target_type, &mut problems)?;
347
348        // ----- Block-tier constraints of the target type -----
349        let unsatisfied =
350            crate::ops::health::unsatisfied_required_outgoing(&next, target_def.as_ref());
351        if !unsatisfied.is_empty() {
352            let blocked: Vec<_> = unsatisfied
353                .iter()
354                .filter(|b| b.severity == memstead_schema::ConstraintSeverity::Block)
355                .cloned()
356                .collect();
357            if !blocked.is_empty() {
358                problems.push(RetypeProblem::RequiredOutgoingUnsatisfied(blocked));
359            }
360            warnings.push(WarningHint::MissingRequiredOutgoing {
361                entity_type: args.target_type.clone(),
362                entity_id: id.clone(),
363                missing: unsatisfied,
364            });
365        }
366        {
367            let check_provider = self.check_standing_provider();
368            let violated = crate::ops::health::unsatisfied_constraints(
369                &self.store,
370                &next,
371                target_def.as_ref(),
372                Some(id),
373                Some(&check_provider),
374            );
375            if !violated.is_empty() {
376                let blocked: Vec<_> = violated
377                    .iter()
378                    .filter(|v| v.severity() == memstead_schema::ConstraintSeverity::Block)
379                    .cloned()
380                    .collect();
381                if !blocked.is_empty() {
382                    problems.push(RetypeProblem::ConstraintUnsatisfied(blocked));
383                }
384                warnings.push(WarningHint::ConstraintUnsatisfied {
385                    entity_type: args.target_type.clone(),
386                    entity_id: id.clone(),
387                    violations: violated,
388                });
389            }
390        }
391
392        if !problems.is_empty() {
393            let mut declared: Vec<String> =
394                target_def.sections.iter().map(|s| s.key.clone()).collect();
395            declared.sort();
396            let catch_all = target_def.catch_all_section().map(|s| s.key.clone());
397            // A proposed map: every entity section the target does not
398            // declare, pointed at the closest declared key or the catch-all.
399            let mut proposed: BTreeMap<String, String> = BTreeMap::new();
400            for key in entity.sections.keys() {
401                if key == "relationships" || target_def.section(key).is_some() {
402                    continue;
403                }
404                if let Some(to) = target_def
405                    .suggest_section(key)
406                    .or_else(|| catch_all.clone())
407                {
408                    proposed.insert(key.clone(), to);
409                }
410            }
411            return Err(EngineError::RetypeRefused {
412                id: id.to_string(),
413                from_type: entity.entity_type.clone(),
414                to_type: args.target_type.clone(),
415                problems,
416                target_sections: declared,
417                target_catch_all: catch_all,
418                proposed_section_map: proposed,
419            });
420        }
421
422        // ----- Render, and either preview or write -----
423        let today = self.now_iso();
424        super::auto_stamp_timestamps(&mut next, target_def.as_ref(), &today);
425        let markdown = super::render_for_write(&next, target_def.as_ref())?;
426        let staleness_note = |from: &str, to: &str| {
427            format!(
428                "check records and derivation baselines on {id} are stale: its content hash \
429                 moved from {from} to {to} with the type change; re-check and re-baseline \
430                 deliberately"
431            )
432        };
433        if args.dry_run {
434            let parsed = parse_markdown(&markdown, &entity.file_path, target_def.as_ref(), &mem)
435                .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
436            let prospective = parsed.entity.content_hash.clone();
437            return Ok(RetypeEntityOutcome {
438                id: id.clone(),
439                file_path: entity.file_path.clone(),
440                old_type: entity.entity_type.clone(),
441                new_type: args.target_type.clone(),
442                content_hash: entity.content_hash.clone(),
443                prospective_hash: Some(prospective.clone()),
444                write_id: String::new(),
445                sections_renamed,
446                edges_rechecked,
447                checks_stale: true,
448                staleness_note: staleness_note(&entity.content_hash, &prospective),
449                warnings,
450            });
451        }
452
453        let backend = self.mounts[mount_idx].backend.as_ref();
454        backend.write_entity(Path::new(&entity.file_path), markdown.as_bytes())?;
455        // An adopted body's origin marks follow a re-keyed section in the
456        // same commit. A `section_map` moves content to another key without
457        // changing it, and a mark's hash covers its key, so an unfollowed
458        // mark would stop matching and serve a contributor's untouched
459        // sentences as the workspace's own prose.
460        super::stage_proposal_marks_retype(backend, id, &args.section_map, &next.sections)?;
461        // `memstead: <verb> <id>` — the subject grammar the history reader
462        // attributes touches by; the type change rides the outcome and the
463        // provenance verb, not the subject.
464        let commit_subject = format!("memstead: retype {id}");
465        let ctx = self.commit_context(
466            Some("retype_entity"),
467            actor,
468            client.cloned(),
469            note.map(String::from),
470        );
471        let write_id = backend.commit(&commit_subject, &ctx)?;
472        backend.append_provenance(
473            &Provenance::new(
474                std::time::SystemTime::now(),
475                ProvenanceKind::Retype,
476                Some(id.to_string()),
477                actor,
478                client.cloned(),
479                note.map(String::from),
480            )
481            .with_role(self.current_role)
482            .with_identity(self.current_identity.clone()),
483        )?;
484        self.record_self_write(mount_idx, &write_id);
485        let stamp_warnings = self.stamp_mutation_versions(mount_idx);
486
487        let parse_result = parse_markdown(&markdown, &entity.file_path, target_def.as_ref(), &mem)
488            .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
489        let content_hash = parse_result.entity.content_hash.clone();
490        let fallback = engine_fallback_type();
491        push_entities_into_store(&mut self.store, vec![parse_result], fallback.as_ref(), None);
492        crate::entity::store_builder::remap_alias_target_edge_sources(
493            &mut self.store,
494            &self.schemas,
495        );
496        self.invalidate_communities();
497        self.maintain_search_indexes(std::slice::from_ref(id));
498
499        let mut outcome_warnings = Vec::new();
500        outcome_warnings.append(&mut drift_warnings);
501        outcome_warnings.extend(stamp_warnings);
502        outcome_warnings.extend(warnings);
503        if let Some(w) = self.note_missing_warning("retype_entity", note) {
504            outcome_warnings.push(w);
505        }
506
507        Ok(RetypeEntityOutcome {
508            id: id.clone(),
509            file_path: entity.file_path.clone(),
510            old_type: entity.entity_type.clone(),
511            new_type: args.target_type.clone(),
512            staleness_note: staleness_note(&entity.content_hash, &content_hash),
513            content_hash,
514            prospective_hash: None,
515            write_id,
516            sections_renamed,
517            edges_rechecked,
518            checks_stale: true,
519            warnings: outcome_warnings,
520        })
521    }
522
523    /// The shape violation, if any, of one edge `from_type --rel_type-->
524    /// to_type` whose source entity lives in `source_mem` (schema
525    /// `source_schema`) and whose target lives in `target_mem` — the rule
526    /// relate applies at write time and the loader at boot, so the three
527    /// can never disagree: a same-mem edge, and a cross-mem edge between
528    /// mems pinning the SAME schema, is judged by that schema's own
529    /// relationship pins; a cross-mem edge between different schemas is
530    /// judged by the source schema's `cross_mem_relationships` entry for
531    /// the target schema. An edge whose entry is not declared at all is
532    /// not a shape violation (it already exists; the loader drops it on
533    /// its own grounds), and a target mem whose schema cannot be resolved
534    /// falls back to the intra-mem rule, as relate does.
535    fn edge_shape_violation(
536        &self,
537        source_schema: &memstead_schema::Schema,
538        source_mem: &str,
539        target_mem: &str,
540        rel_type: &str,
541        from_type: &str,
542        to_type: Option<&str>,
543    ) -> Option<ValidationError> {
544        let target_ref: Option<memstead_schema::SchemaRef> = if source_mem == target_mem {
545            None
546        } else {
547            super::target_schema_ref_for_routing(self, target_mem)
548        };
549        let cross_mem_different = match (&target_ref, source_schema.id()) {
550            (Some(target), (src_name, _)) => target.name != src_name,
551            (None, _) => false,
552        };
553        if cross_mem_different {
554            let target_ref = target_ref.expect("Some when cross_mem_different");
555            match validate_cross_mem_edge(rel_type, from_type, to_type, source_schema, &target_ref)
556            {
557                CrossMemRelCheck::Ok | CrossMemRelCheck::EdgeNotDeclared => None,
558                CrossMemRelCheck::Invalid(e) => Some(e),
559            }
560        } else {
561            validate_rel_shape(rel_type, from_type, to_type, source_schema).err()
562        }
563    }
564
565    /// Re-check the edges that reach `id` from mems whose content is not
566    /// in the store — deferred (lazy, unloaded) mounts. Their entities
567    /// are enumerated and read through the mount's own backend, the same
568    /// storage the relate path probes deferred targets through; every
569    /// relation naming `id` is shape-checked against the target type.
570    /// Returns the number of edges examined; a mem whose storage cannot
571    /// be enumerated refuses typed rather than being assumed fine.
572    fn recheck_deferred_referrers(
573        &self,
574        id: &EntityId,
575        target_type: &str,
576        problems: &mut Vec<RetypeProblem>,
577    ) -> Result<usize, EngineError> {
578        let mut examined = 0usize;
579        let id_str = id.to_string();
580        let fallback = engine_fallback_type();
581        for mounted in self.mounts.iter().filter(|m| m.deferred) {
582            let referrer_mem = mounted.mount.mem.clone();
583            let paths = mounted.backend.list_entities().map_err(|e| {
584                EngineError::RetypeReferrerUnprobeable {
585                    id: id_str.clone(),
586                    mem: referrer_mem.clone(),
587                    reason: e.to_string(),
588                }
589            })?;
590            let referrer_schema = self.schemas.get(&referrer_mem);
591            for path in paths {
592                let rel_path = path.to_string_lossy().into_owned();
593                let Some(bytes) =
594                    mounted
595                        .backend
596                        .read_entity(Path::new(&rel_path))
597                        .map_err(|e| EngineError::RetypeReferrerUnprobeable {
598                            id: id_str.clone(),
599                            mem: referrer_mem.clone(),
600                            reason: format!("{rel_path}: {e}"),
601                        })?
602                else {
603                    continue;
604                };
605                let text = String::from_utf8_lossy(&bytes);
606                // Cheap gate before parsing: a relation row names the
607                // entity as `mem--slug` or `mem:slug`; both carry the slug.
608                if !text.contains(id.name()) {
609                    continue;
610                }
611                // Parse under the referrer's own type when its schema is
612                // known, the fallback type otherwise: relationships are
613                // parsed identically either way.
614                let declared_type = crate::entity::parser::peek_type_from_frontmatter(&text);
615                let type_def = referrer_schema
616                    .and_then(|s| declared_type.as_deref().and_then(|t| s.get_type(t)))
617                    .unwrap_or_else(|| fallback.clone());
618                let Ok(parsed) = parse_markdown(&text, &rel_path, type_def.as_ref(), &referrer_mem)
619                else {
620                    continue;
621                };
622                for rel in &parsed.entity.relationships {
623                    if rel.target != *id {
624                        continue;
625                    }
626                    examined += 1;
627                    let violation = match referrer_schema {
628                        Some(referrer_schema) => self.edge_shape_violation(
629                            referrer_schema,
630                            &referrer_mem,
631                            id.mem(),
632                            &rel.rel_type,
633                            &parsed.entity.entity_type,
634                            Some(target_type),
635                        ),
636                        None => None,
637                    };
638                    if let Some(e) = violation {
639                        problems.push(RetypeProblem::EdgeShape(RetypeEdge {
640                            direction: RetypeEdgeDirection::Incoming,
641                            from: parsed.entity.id.to_string(),
642                            to: id_str.clone(),
643                            rel_type: rel.rel_type.clone(),
644                            cross_mem: true,
645                            detail: e.details(),
646                        }));
647                    }
648                }
649            }
650        }
651        Ok(examined)
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use std::collections::BTreeMap;
658    use std::path::Path;
659
660    use indexmap::IndexMap;
661    use memstead_schema::SchemaRef;
662    use memstead_schema::workspace_config::CrossLinkValue;
663    use tempfile::TempDir;
664
665    use crate::backend::MemBackend;
666    use crate::engine::outcomes::{RetypeEdgeDirection, RetypeProblem};
667    use crate::engine::test_helpers::*;
668    use crate::engine::{
669        CreateEntityArgs, Engine, EngineError, RelateEntityArgs, RetypeEntityArgs,
670    };
671    use crate::ops::WarningHint;
672    use crate::storage::FilesystemBackend;
673    use crate::workspace::{
674        Mount, MountCapability, MountLifecycle, MountStorage, WorkspaceSettings,
675    };
676
677    const MAIN_MANIFEST: &str = r#"name: rt
678version: 0.1.0
679description: retype fixture
680when_to_use: tests
681types:
682  - claim
683  - finding
684relationships:
685  mode: strict
686  definitions:
687    - name: SUPPORTS
688      description: pinned both ends to claim
689      default_weight: 1.0
690      source_types: [claim]
691      target_types: [claim]
692    - name: CITES
693      description: unpinned
694      default_weight: 1.0
695    - name: _default
696      description: fallback
697      default_weight: 1.0
698community:
699  resolution: 1.0
700  seed: 42
701"#;
702
703    const PEER_MANIFEST: &str = r#"name: rt-peer
704version: 0.1.0
705description: peer fixture
706when_to_use: tests
707types:
708  - remark
709relationships:
710  mode: strict
711  definitions:
712    - name: _default
713      description: fallback
714      default_weight: 1.0
715cross_mem_relationships:
716  - to_schema: rt
717    definitions:
718      - name: COMMENTS_ON
719        description: pinned to claim on the target side
720        default_weight: 1.0
721        source_types: [remark]
722        target_types: [claim]
723community:
724  resolution: 1.0
725  seed: 42
726"#;
727
728    fn type_yaml(name: &str, main_section: &str, main_heading: &str) -> String {
729        format!(
730            r#"name: {name}
731description: t
732when_to_use: Here
733sections:
734  - key: {main_section}
735    heading: {main_heading}
736    required: true
737    search_weight: 10.0
738    write_rules: []
739  - key: notes
740    heading: Notes
741    required: false
742    search_weight: 1.0
743    catch_all: true
744    write_rules: []
745metadata_fields: []
746title_weight: 100.0
747text_fields:
748  - {main_section}
749hierarchy_relationship: _default
750no_self_loop_relationships: []
751updatable_fields:
752  - title
753  - {main_section}
754  - notes
755health_required_fields:
756  - {main_section}
757staleness_threshold_days: 90
758write_rules: []
759"#
760        )
761    }
762
763    fn write_schema(root: &Path, name: &str, manifest: &str, types: &[(&str, String)]) {
764        let dir = root.join(name);
765        std::fs::create_dir_all(dir.join("types")).unwrap();
766        std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
767        for (t, body) in types {
768            std::fs::write(dir.join("types").join(format!("{t}.yaml")), body).unwrap();
769        }
770    }
771
772    fn mount(
773        mem: &str,
774        path: std::path::PathBuf,
775        pin: SchemaRef,
776        lifecycle: MountLifecycle,
777    ) -> Mount {
778        Mount {
779            mem: mem.to_string(),
780            schema: Some(pin),
781            storage: MountStorage::Folder { path },
782            capability: MountCapability::Write,
783            lifecycle,
784            cross_linkable: true,
785            migration_target: None,
786        }
787    }
788
789    struct Fixture {
790        _tmp: TempDir,
791        schemas_dir: std::path::PathBuf,
792        main_dir: std::path::PathBuf,
793        peer_dir: std::path::PathBuf,
794    }
795
796    fn fixture() -> Fixture {
797        let tmp = TempDir::new().unwrap();
798        let schemas_dir = tmp.path().join("schemas");
799        std::fs::create_dir_all(&schemas_dir).unwrap();
800        write_schema(
801            &schemas_dir,
802            "rt",
803            MAIN_MANIFEST,
804            &[
805                ("claim", type_yaml("claim", "statement", "Statement")),
806                ("finding", type_yaml("finding", "conclusion", "Conclusion")),
807            ],
808        );
809        write_schema(
810            &schemas_dir,
811            "rt-peer",
812            PEER_MANIFEST,
813            &[("remark", type_yaml("remark", "body", "Body"))],
814        );
815        let main_dir = tmp.path().join("mem-main");
816        let peer_dir = tmp.path().join("mem-peer");
817        std::fs::create_dir_all(&main_dir).unwrap();
818        std::fs::create_dir_all(&peer_dir).unwrap();
819        Fixture {
820            _tmp: tmp,
821            schemas_dir,
822            main_dir,
823            peer_dir,
824        }
825    }
826
827    fn boot(f: &Fixture, peer_lifecycle: MountLifecycle) -> Engine {
828        let main_pin = SchemaRef::new("rt", semver::Version::new(0, 1, 0));
829        let peer_pin = SchemaRef::new("rt-peer", semver::Version::new(0, 1, 0));
830        let mut engine = Engine::from_mounts_with_schemas_dir(
831            vec![
832                (
833                    mount("main", f.main_dir.clone(), main_pin, MountLifecycle::Eager),
834                    Box::new(FilesystemBackend::new(f.main_dir.clone())) as Box<dyn MemBackend>,
835                ),
836                (
837                    mount("peer", f.peer_dir.clone(), peer_pin, peer_lifecycle),
838                    Box::new(FilesystemBackend::new(f.peer_dir.clone())) as Box<dyn MemBackend>,
839                ),
840            ],
841            Some(&f.schemas_dir),
842        )
843        .expect("engine boots");
844        let mut settings = WorkspaceSettings::default();
845        let mut links: BTreeMap<String, CrossLinkValue> = BTreeMap::new();
846        links.insert("peer".to_string(), CrossLinkValue::Wildcard);
847        settings.cross_mem_links = links;
848        engine.set_settings(settings);
849        engine
850    }
851
852    fn create(
853        engine: &mut Engine,
854        mem: &str,
855        title: &str,
856        ty: &str,
857        section: &str,
858    ) -> crate::EntityId {
859        let (actor, client) = cli_actor();
860        engine
861            .create_entity(
862                CreateEntityArgs {
863                    anchors: Vec::new(),
864                    mem: mem.to_string(),
865                    title: title.to_string(),
866                    entity_type: ty.to_string(),
867                    sections: IndexMap::from_iter([
868                        (section.to_string(), format!("{title} says so.")),
869                        ("notes".to_string(), "Some notes.".to_string()),
870                    ]),
871                    metadata: IndexMap::new(),
872                    relations: Vec::new(),
873                    dry_run: false,
874                },
875                actor,
876                Some(&client),
877                None,
878            )
879            .expect("creates")
880            .id
881    }
882
883    fn relate(engine: &mut Engine, from: &crate::EntityId, rel: &str, to: &crate::EntityId) {
884        let (actor, client) = cli_actor();
885        engine
886            .relate_entity(
887                RelateEntityArgs {
888                    source: from.clone(),
889                    expected_hash: None,
890                    rel_type: rel.to_string(),
891                    target: to.clone(),
892                    remove: false,
893                    description: None,
894                    dry_run: false,
895                },
896                actor,
897                Some(&client),
898                None,
899            )
900            .expect("relates");
901    }
902
903    fn retype(
904        engine: &mut Engine,
905        id: &crate::EntityId,
906        target: &str,
907        map: &[(&str, &str)],
908    ) -> Result<crate::engine::RetypeEntityOutcome, EngineError> {
909        let (actor, client) = cli_actor();
910        let hash = engine.get_entity(id).unwrap().content_hash.clone();
911        engine.retype_entity(
912            RetypeEntityArgs {
913                id: id.clone(),
914                expected_hash: Some(hash),
915                target_type: target.to_string(),
916                section_map: map
917                    .iter()
918                    .map(|(a, b)| (a.to_string(), b.to_string()))
919                    .collect(),
920                drop_metadata: Vec::new(),
921                dry_run: false,
922            },
923            actor,
924            Some(&client),
925            Some("test retype"),
926        )
927    }
928
929    fn file_bytes(f: &Fixture, id: &crate::EntityId) -> Vec<u8> {
930        std::fs::read(f.main_dir.join(format!("{}.md", id.name()))).unwrap()
931    }
932
933    /// AC1: the type changes in place with the mapped section; id, path and
934    /// incoming edges stay; the response says checks are stale; a fresh
935    /// boot loads the result with no shape drops and the same edge count.
936    #[test]
937    fn retype_keeps_identity_and_edges_and_states_staleness() {
938        let f = fixture();
939        let mut engine = boot(&f, MountLifecycle::Eager);
940        let a = create(&mut engine, "main", "Claim A", "claim", "statement");
941        let b = create(&mut engine, "main", "Claim B", "claim", "statement");
942        // Unpinned incoming edge onto B, and an unpinned outgoing one.
943        relate(&mut engine, &a, "CITES", &b);
944        relate(&mut engine, &b, "CITES", &a);
945        let edges_before = engine.store().incoming(&b).len() + engine.store().outgoing(&b).len();
946        let hash_before = engine.get_entity(&b).unwrap().content_hash.clone();
947
948        let out = retype(&mut engine, &b, "finding", &[("statement", "conclusion")])
949            .expect("retype succeeds");
950        assert_eq!(out.id, b);
951        assert_eq!(out.file_path, "claim-b.md");
952        assert_eq!(
953            (out.old_type.as_str(), out.new_type.as_str()),
954            ("claim", "finding")
955        );
956        assert_eq!(
957            out.sections_renamed,
958            vec![("statement".to_string(), "conclusion".to_string())]
959        );
960        assert_eq!(out.edges_rechecked, 2);
961        assert!(out.checks_stale);
962        assert!(
963            out.staleness_note
964                .contains("check records and derivation baselines")
965        );
966        assert!(out.staleness_note.contains(&hash_before));
967        assert!(!out.write_id.is_empty());
968
969        let e = engine.get_entity(&b).unwrap();
970        assert_eq!(
971            e.entity_type,
972            "finding",
973            "store entity after retype: {e:?}\nfile: {}",
974            String::from_utf8(file_bytes(&f, &b)).unwrap()
975        );
976        assert_eq!(e.file_path, "claim-b.md");
977        assert_eq!(
978            e.sections.get("conclusion").map(String::as_str),
979            Some("Claim B says so.")
980        );
981        assert!(!e.sections.contains_key("statement"));
982        assert_ne!(e.content_hash, hash_before);
983        assert_eq!(engine.store().incoming(&b).len(), 1, "incoming edge stays");
984        assert_eq!(engine.store().incoming(&b)[0].from, a);
985        let text = String::from_utf8(file_bytes(&f, &b)).unwrap();
986        assert!(text.contains("type: finding"), "{text}");
987        assert!(text.contains("## Conclusion"), "{text}");
988
989        // Restart: nothing dropped, edge count unchanged.
990        let fresh = boot(&f, MountLifecycle::Eager);
991        let dropped = fresh
992            .load_warnings()
993            .iter()
994            .any(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }));
995        assert!(!dropped, "{:?}", fresh.load_warnings());
996        assert_eq!(
997            fresh.store().incoming(&b).len() + fresh.store().outgoing(&b).len(),
998            edges_before
999        );
1000        assert_eq!(
1001            fresh.get_entity(&b).unwrap().entity_type,
1002            "finding",
1003            "warnings: {:?}\nfile: {}",
1004            fresh.load_warnings(),
1005            String::from_utf8(file_bytes(&f, &b)).unwrap()
1006        );
1007    }
1008
1009    /// AC1 refusal complement: a map naming a key the target does not
1010    /// declare refuses UNKNOWN_SECTION with the target's declared sections
1011    /// and a proposed map, and the file is byte-identical afterwards.
1012    #[test]
1013    fn unknown_section_refuses_with_declared_sections_and_touches_nothing() {
1014        let f = fixture();
1015        let mut engine = boot(&f, MountLifecycle::Eager);
1016        let b = create(&mut engine, "main", "Claim B", "claim", "statement");
1017        let before = file_bytes(&f, &b);
1018        let err = retype(&mut engine, &b, "finding", &[("statement", "bogus")]).unwrap_err();
1019        assert_eq!(err.code(), "UNKNOWN_SECTION");
1020        let d = err.details();
1021        assert_eq!(
1022            d["target_sections"],
1023            serde_json::json!(["conclusion", "notes"])
1024        );
1025        assert_eq!(d["target_catch_all"], "notes");
1026        assert_eq!(d["proposed_section_map"]["statement"], "notes", "{d}");
1027        // Report-all: the unknown key AND the required section it leaves
1028        // empty arrive together; the envelope code is the map defect.
1029        let codes: Vec<&str> = d["problems"]
1030            .as_array()
1031            .unwrap()
1032            .iter()
1033            .map(|p| p["code"].as_str().unwrap())
1034            .collect();
1035        assert_eq!(codes, vec!["UNKNOWN_SECTION", "MISSING_REQUIRED_SECTION"]);
1036        assert_eq!(d["problems"][0]["key"], "bogus");
1037        assert_eq!(
1038            file_bytes(&f, &b),
1039            before,
1040            "refusal leaves the file untouched"
1041        );
1042        assert_eq!(engine.get_entity(&b).unwrap().entity_type, "claim");
1043
1044        // No map at all: the undeclared `statement` refuses the same way,
1045        // and the required `conclusion` is reported in the same envelope.
1046        let err = retype(&mut engine, &b, "finding", &[]).unwrap_err();
1047        assert_eq!(
1048            err.code(),
1049            "UNKNOWN_SECTION",
1050            "a section-map defect dominates the envelope code"
1051        );
1052        let codes: Vec<String> = err.details()["problems"]
1053            .as_array()
1054            .unwrap()
1055            .iter()
1056            .map(|p| p["code"].as_str().unwrap().to_string())
1057            .collect();
1058        assert_eq!(codes, vec!["UNKNOWN_SECTION", "MISSING_REQUIRED_SECTION"]);
1059        assert_eq!(file_bytes(&f, &b), before);
1060        assert!(matches!(
1061            retype(&mut engine, &b, "claim", &[]).unwrap_err(),
1062            EngineError::RetypeNoOp { .. }
1063        ));
1064    }
1065
1066    /// AC2: an incoming edge whose rel-type pins its target to the current
1067    /// type refuses; so does an outgoing one and a cross-mem one; two
1068    /// violations at once arrive in one envelope; every refusal leaves the
1069    /// file byte-identical.
1070    #[test]
1071    fn edge_shapes_are_rechecked_in_both_directions_and_across_mems() {
1072        let f = fixture();
1073        let mut engine = boot(&f, MountLifecycle::Eager);
1074        let a = create(&mut engine, "main", "Claim A", "claim", "statement");
1075        let b = create(&mut engine, "main", "Claim B", "claim", "statement");
1076        relate(&mut engine, &a, "SUPPORTS", &b); // pinned: target must stay claim
1077        let before_b = file_bytes(&f, &b);
1078
1079        // Incoming.
1080        let err = retype(&mut engine, &b, "finding", &[("statement", "conclusion")]).unwrap_err();
1081        assert_eq!(err.code(), "INVALID_REL_SHAPE", "{err}");
1082        let EngineError::RetypeRefused { problems, .. } = &err else {
1083            panic!("{err:?}")
1084        };
1085        assert_eq!(problems.len(), 1);
1086        let RetypeProblem::EdgeShape(edge) = &problems[0] else {
1087            panic!("{problems:?}")
1088        };
1089        assert_eq!(edge.direction, RetypeEdgeDirection::Incoming);
1090        assert_eq!(
1091            (edge.from.as_str(), edge.rel_type.as_str()),
1092            (a.as_ref(), "SUPPORTS")
1093        );
1094        assert!(!edge.cross_mem);
1095        assert_eq!(file_bytes(&f, &b), before_b);
1096
1097        // Outgoing.
1098        let before_a = file_bytes(&f, &a);
1099        let err = retype(&mut engine, &a, "finding", &[("statement", "conclusion")]).unwrap_err();
1100        assert_eq!(err.code(), "INVALID_REL_SHAPE");
1101        let EngineError::RetypeRefused { problems, .. } = &err else {
1102            panic!("{err:?}")
1103        };
1104        let RetypeProblem::EdgeShape(edge) = &problems[0] else {
1105            panic!("{problems:?}")
1106        };
1107        assert_eq!(edge.direction, RetypeEdgeDirection::Outgoing);
1108        assert_eq!(edge.to, b.to_string());
1109        assert_eq!(file_bytes(&f, &a), before_a);
1110
1111        // Report-all: B also supports A now — retyping B violates an
1112        // incoming AND an outgoing pin, both in one envelope.
1113        relate(&mut engine, &b, "SUPPORTS", &a);
1114        let before_b = file_bytes(&f, &b);
1115        let err = retype(&mut engine, &b, "finding", &[("statement", "conclusion")]).unwrap_err();
1116        assert_eq!(err.code(), "INVALID_REL_SHAPE");
1117        let d = err.details();
1118        let dirs: Vec<String> = d["problems"]
1119            .as_array()
1120            .unwrap()
1121            .iter()
1122            .map(|p| p["direction"].as_str().unwrap().to_string())
1123            .collect();
1124        assert_eq!(dirs, vec!["outgoing", "incoming"]);
1125        assert_eq!(file_bytes(&f, &b), before_b);
1126
1127        // Cross-mem: a remark in the peer mem comments on a claim; the
1128        // cross-mem entry pins the target to claim.
1129        let c = create(&mut engine, "main", "Claim C", "claim", "statement");
1130        let r = create(&mut engine, "peer", "Remark R", "remark", "body");
1131        relate(&mut engine, &r, "COMMENTS_ON", &c);
1132        let before_c = file_bytes(&f, &c);
1133        let err = retype(&mut engine, &c, "finding", &[("statement", "conclusion")]).unwrap_err();
1134        assert_eq!(err.code(), "INVALID_REL_SHAPE", "{err}");
1135        let EngineError::RetypeRefused { problems, .. } = &err else {
1136            panic!("{err:?}")
1137        };
1138        let RetypeProblem::EdgeShape(edge) = &problems[0] else {
1139            panic!("{problems:?}")
1140        };
1141        assert!(edge.cross_mem);
1142        assert_eq!(edge.from, r.to_string());
1143        assert_eq!(file_bytes(&f, &c), before_c);
1144    }
1145
1146    /// Two mems pinning the SAME schema: a cross-mem edge is judged by that
1147    /// schema's own pins, exactly as relate and the loader judge it, so a
1148    /// retype that would strand the referrer's edge refuses — the
1149    /// same-schema case the grader of 2026-09-02 found waved through.
1150    #[test]
1151    fn same_schema_cross_mem_edges_are_rechecked() {
1152        let f = fixture();
1153        let tmp_twin = f._tmp.path().join("mem-twin");
1154        std::fs::create_dir_all(&tmp_twin).unwrap();
1155        let main_pin = SchemaRef::new("rt", semver::Version::new(0, 1, 0));
1156        let mut engine = Engine::from_mounts_with_schemas_dir(
1157            vec![
1158                (
1159                    mount(
1160                        "main",
1161                        f.main_dir.clone(),
1162                        main_pin.clone(),
1163                        MountLifecycle::Eager,
1164                    ),
1165                    Box::new(FilesystemBackend::new(f.main_dir.clone())) as Box<dyn MemBackend>,
1166                ),
1167                (
1168                    mount("twin", tmp_twin.clone(), main_pin, MountLifecycle::Eager),
1169                    Box::new(FilesystemBackend::new(tmp_twin.clone())) as Box<dyn MemBackend>,
1170                ),
1171            ],
1172            Some(&f.schemas_dir),
1173        )
1174        .unwrap();
1175        let mut settings = WorkspaceSettings::default();
1176        let mut links: BTreeMap<String, CrossLinkValue> = BTreeMap::new();
1177        links.insert("twin".to_string(), CrossLinkValue::Wildcard);
1178        links.insert("main".to_string(), CrossLinkValue::Wildcard);
1179        settings.cross_mem_links = links;
1180        engine.set_settings(settings);
1181
1182        let v = create(&mut engine, "main", "Claim V", "claim", "statement");
1183        let w = create(&mut engine, "twin", "Claim W", "claim", "statement");
1184        relate(&mut engine, &w, "SUPPORTS", &v); // pinned target: claim
1185        let before = file_bytes(&f, &v);
1186        let err = retype(&mut engine, &v, "finding", &[("statement", "conclusion")]).unwrap_err();
1187        assert_eq!(err.code(), "INVALID_REL_SHAPE", "{err}");
1188        let EngineError::RetypeRefused { problems, .. } = &err else {
1189            panic!("{err:?}")
1190        };
1191        let RetypeProblem::EdgeShape(edge) = &problems[0] else {
1192            panic!("{problems:?}")
1193        };
1194        assert!(edge.cross_mem);
1195        assert_eq!(edge.from, w.to_string());
1196        assert_eq!(file_bytes(&f, &v), before);
1197
1198        // Outgoing across the twin: W supports V, retyping W refuses too.
1199        let err = retype(&mut engine, &w, "finding", &[("statement", "conclusion")]).unwrap_err();
1200        assert_eq!(err.code(), "INVALID_REL_SHAPE", "{err}");
1201    }
1202
1203    /// The referrer lives in a LAZY mem: its edge is not in the store, so
1204    /// the retype probes the mem's storage and finds it; the same graph
1205    /// with the peer loaded eagerly refuses identically, and the deferred
1206    /// probe counts the edge it examined.
1207    #[test]
1208    fn deferred_referrers_are_probed_through_storage() {
1209        let f = fixture();
1210        {
1211            let mut engine = boot(&f, MountLifecycle::Eager);
1212            let c = create(&mut engine, "main", "Claim C", "claim", "statement");
1213            let r = create(&mut engine, "peer", "Remark R", "remark", "body");
1214            relate(&mut engine, &r, "COMMENTS_ON", &c);
1215        }
1216        let mut lazy = boot(&f, MountLifecycle::Lazy);
1217        let c = crate::EntityId::canonical("main--claim-c");
1218        assert!(
1219            lazy.mem_is_deferred("peer"),
1220            "peer stays unloaded until touched"
1221        );
1222        assert!(
1223            lazy.store().incoming(&c).is_empty(),
1224            "the lazy referrer's edge is not in the store"
1225        );
1226        let err = retype(&mut lazy, &c, "finding", &[("statement", "conclusion")]).unwrap_err();
1227        assert_eq!(err.code(), "INVALID_REL_SHAPE", "{err}");
1228        let EngineError::RetypeRefused { problems, .. } = &err else {
1229            panic!("{err:?}")
1230        };
1231        let RetypeProblem::EdgeShape(edge) = &problems[0] else {
1232            panic!("{problems:?}")
1233        };
1234        assert!(edge.cross_mem);
1235        assert_eq!(edge.from, "peer--remark-r");
1236        assert_eq!(lazy.get_entity(&c).unwrap().entity_type, "claim");
1237
1238        // Without the pinned referrer, a lazily mounted peer does not
1239        // block, and the probe reports the edges it examined (none).
1240        let d = create(&mut lazy, "main", "Claim D", "claim", "statement");
1241        let out = retype(&mut lazy, &d, "finding", &[("statement", "conclusion")]).unwrap();
1242        assert_eq!(out.edges_rechecked, 0);
1243    }
1244
1245    /// Dry run: the same validation, the prospective hash, no write.
1246    #[test]
1247    fn dry_run_validates_and_writes_nothing() {
1248        let f = fixture();
1249        let mut engine = boot(&f, MountLifecycle::Eager);
1250        let b = create(&mut engine, "main", "Claim B", "claim", "statement");
1251        let before = file_bytes(&f, &b);
1252        let (actor, client) = cli_actor();
1253        let out = engine
1254            .retype_entity(
1255                RetypeEntityArgs {
1256                    id: b.clone(),
1257                    expected_hash: None,
1258                    target_type: "finding".to_string(),
1259                    section_map: IndexMap::from_iter([(
1260                        "statement".to_string(),
1261                        "conclusion".to_string(),
1262                    )]),
1263                    drop_metadata: Vec::new(),
1264                    dry_run: true,
1265                },
1266                actor,
1267                Some(&client),
1268                None,
1269            )
1270            .unwrap();
1271        assert!(out.write_id.is_empty());
1272        assert!(out.prospective_hash.is_some());
1273        assert_ne!(
1274            out.prospective_hash.as_deref(),
1275            Some(out.content_hash.as_str())
1276        );
1277        assert_eq!(file_bytes(&f, &b), before);
1278        assert_eq!(engine.get_entity(&b).unwrap().entity_type, "claim");
1279    }
1280}