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