Skip to main content

memstead_base/engine/
error.rs

1//! Engine error envelopes.
2//!
3//! `EngineError` lifts the typed payloads every consumer pattern-matches
4//! on (`BackendError` via `#[from]`, `ValidationError` from the runtime
5//! validator, `SlugError` from the slug helper, `ParseError` from the
6//! markdown parser). `BootError` is the smaller envelope produced by
7//! `Engine::from_workspace_root` and its full counterpart — the failure
8//! modes specific to layout detection, workspace-store load, per-mount
9//! backend instantiation, and engine construction.
10
11use std::fmt;
12use std::path::PathBuf;
13
14use crate::backend::BackendError;
15use crate::entity::EntityId;
16use crate::entity::id::SlugError;
17use crate::entity::parser::ParseError;
18use crate::runtime_validator::{MissingRequiredField, ValidationError};
19
20/// Maximum items rendered inline before truncation kicks in. Picked to
21/// keep the typical fanout (1–25 items) on one terminal line while
22/// still bounding pathological cases (200+ referrers on a hub entity)
23/// to a constant prefix plus a count.
24pub const INLINE_LIST_CAP: usize = 3;
25
26/// One blocked-direction summary entry for
27/// [`EngineError::RenameBlockedByCrossMemPolicy`]. Pairs the
28/// referrer's mem with the renaming entity's mem (the edge's
29/// actual `referrer → renamed` direction post-rewrite) and the count
30/// of distinct referrers in that mem that would emit the blocked
31/// rewrite.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct BlockedReferrer {
34    /// Referrer's mem — `from_mem` in the propagated edge's
35    /// actual direction.
36    pub from_mem: String,
37    /// Renaming entity's mem — `to_mem` in the propagated edge's
38    /// actual direction. Always the same value across every
39    /// `blocked_referrers` entry of a single rename refusal.
40    pub to_mem: String,
41    /// Distinct referrers in `from_mem` that would emit the
42    /// blocked rewrite.
43    pub count: usize,
44}
45
46impl fmt::Display for BlockedReferrer {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(
49            f,
50            "{} → {} ({} referrer{})",
51            self.from_mem,
52            self.to_mem,
53            self.count,
54            if self.count == 1 { "" } else { "s" }
55        )
56    }
57}
58
59fn format_blocked_referrers(items: &[BlockedReferrer]) -> String {
60    format_inline_list_overflow(items, "blocked_referrers")
61}
62
63/// Occupant rendering for [`EngineError::AlreadyExists`]: a real
64/// entity renders its quoted title; a stub renders as "a stub" (with
65/// its title when it has one — a titleless stub must never render as
66/// an empty title).
67fn render_occupant(existing_title: &str, existing_is_stub: bool) -> String {
68    match (existing_is_stub, existing_title.is_empty()) {
69        (true, true) => "a stub".to_string(),
70        (true, false) => format!("a stub titled '{existing_title}'"),
71        (false, _) => format!("'{existing_title}'"),
72    }
73}
74
75/// Render a structured-list payload onto the text-mirror message. The
76/// first [`INLINE_LIST_CAP`] items appear inline, comma-separated; when
77/// the list is longer, the suffix " +N more — see details.<field>"
78/// points the agent at the structured channel's typed list under
79/// `field`. Empty input renders as an empty string. The function is
80/// generic over any [`fmt::Display`] item — wrap structs in a small
81/// `Display` newtype if their default rendering is too verbose for the
82/// text channel.
83pub fn format_inline_list_overflow<T: fmt::Display>(items: &[T], field: &str) -> String {
84    if items.is_empty() {
85        return String::new();
86    }
87    let head: Vec<String> = items
88        .iter()
89        .take(INLINE_LIST_CAP)
90        .map(|i| i.to_string())
91        .collect();
92    let inline = head.join(", ");
93    if items.len() > INLINE_LIST_CAP {
94        let extra = items.len() - INLINE_LIST_CAP;
95        format!("{inline} +{extra} more — see details.{field}")
96    } else {
97        inline
98    }
99}
100
101/// One resolution-source line on [`EngineError::SchemaNotFound`]'s
102/// `details.sources` payload.
103///
104/// The schema registry consults sources in a fixed order — local
105/// storage (the mem's own storage backend), built-in (compiled into
106/// the engine binary), remote (memstead.io, reserved) — and records
107/// what each held for the pinned *name* so an agent or operator can
108/// tell *where* a pin failed: missing from local authoring, absent
109/// from the shipped catalogue, or past the not-yet-wired remote. The
110/// `local_storage`/`builtin` lines report a wrong-version partial
111/// match (right name, wrong version) through `pinned_version_match`.
112#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
113pub struct SchemaSourceDiagnostic {
114    /// Stable source label: `"local_storage"`, `"builtin"`, or
115    /// `"remote"`. Agents may branch on it.
116    pub source: &'static str,
117    /// Versions of the pinned *name* this source held, ascending.
118    /// Empty when the source carried nothing for that name — or was
119    /// not enumerated (today only `remote`, see `status`).
120    pub versions_found: Vec<String>,
121    /// `true` when the pinned exact version is among `versions_found`.
122    /// Always `false` across every source on a genuine not-found (the
123    /// fixed resolution order means a match on any source would have
124    /// resolved); a lone `true` here signals right-name/wrong-version.
125    pub pinned_version_match: bool,
126    /// Non-enumerable status for sources that do not list versions —
127    /// today only `remote`, which reports `"not_configured"`. `None`
128    /// for the enumerable `local_storage`/`builtin` sources.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub status: Option<&'static str>,
131}
132
133impl SchemaSourceDiagnostic {
134    /// Build the fixed-order source diagnostics for a failed pin.
135    ///
136    /// `consulted` is the resolution set the call site actually
137    /// searched: at boot it is the workspace-authored schemas layered
138    /// over the built-ins; at the create/migration sites it is the
139    /// set that path consulted (built-in alone, or workspace + built-in
140    /// for the migration resolver). The `builtin` line is recomputed
141    /// from the static catalogue so it is honest regardless of what the
142    /// caller passed; anything in `consulted` the built-in set does not
143    /// carry is attributed to `local_storage`. `remote` is always the
144    /// reserved `not_configured` slot.
145    pub fn for_failed_pin(
146        name: &str,
147        requested: &semver::Version,
148        consulted: &[std::sync::Arc<memstead_schema::Schema>],
149    ) -> Vec<Self> {
150        use std::collections::BTreeSet;
151        let builtin: BTreeSet<semver::Version> = memstead_schema::builtins::load_builtin_schemas()
152            .map(|set| {
153                set.iter()
154                    .filter(|s| s.manifest.name == name)
155                    .map(|s| s.version.clone())
156                    .collect()
157            })
158            .unwrap_or_default();
159        let local: BTreeSet<semver::Version> = consulted
160            .iter()
161            .filter(|s| s.manifest.name == name)
162            .map(|s| s.version.clone())
163            .filter(|v| !builtin.contains(v))
164            .collect();
165        let to_strings =
166            |set: &BTreeSet<semver::Version>| set.iter().map(|v| v.to_string()).collect::<Vec<_>>();
167        vec![
168            Self {
169                source: "local_storage",
170                pinned_version_match: local.contains(requested),
171                versions_found: to_strings(&local),
172                status: None,
173            },
174            Self {
175                source: "builtin",
176                pinned_version_match: builtin.contains(requested),
177                versions_found: to_strings(&builtin),
178                status: None,
179            },
180            Self {
181                source: "remote",
182                versions_found: Vec::new(),
183                pinned_version_match: false,
184                status: Some("not_configured"),
185            },
186        ]
187    }
188}
189
190/// Errors surfaced by [`Engine`].
191///
192/// `Backend` lifts [`BackendError`] verbatim through a `#[from]`
193/// conversion so the engine layer's error envelope preserves the
194/// backend's typed `Sealed` / `HashMismatch` payloads. The MCP layer
195/// branches on the discriminant when mapping into the typed `code`
196/// field of its error envelope.
197#[derive(Debug, thiserror::Error)]
198pub enum EngineError {
199    /// `Engine::from_mounts` received two mounts naming the same
200    /// mem. Configuration error: the persistence adapter or
201    /// caller produced a malformed mount list.
202    #[error("duplicate mem in mount list: {0}")]
203    DuplicateMem(String),
204    /// No mount in this engine names the requested mem. Surfaced
205    /// before reaching any backend so callers can distinguish
206    /// "wrong mem name" from "backend failure".
207    #[error("unknown mem: {0}")]
208    UnknownMem(String),
209    /// The mem exists in the workspace but failed its mem-level boot
210    /// step and is quarantined — it serves nothing until repaired
211    /// (degrade, never disappear; quarantine is not tolerance).
212    /// `reason_message` is the underlying typed failure verbatim, its
213    /// final clause the repair command; after the repair,
214    /// `memstead_reload` re-attaches the mem without a restart.
215    #[error(
216        "mem '{mem}' is quarantined — it failed to attach at boot and serves nothing until \
217         repaired: [{reason_code}] {reason_message}. After repairing, run memstead_reload \
218         (or `memstead reload`) to bring it back into service."
219    )]
220    MemQuarantined {
221        mem: String,
222        reason_code: String,
223        reason_message: String,
224    },
225    /// Mutation rejected because the mount declares
226    /// [`MountCapability::ReadOnly`]. Surfaced before reaching the
227    /// backend so the typed `Sealed` payload from the archive
228    /// backend never triggers — capability gating runs first.
229    #[error("mem {0} is mounted read-only; mutations rejected")]
230    ReadOnlyMount(String),
231    /// A check could not be persisted — either the engine has no
232    /// workspace root (in-memory engines have no durable check
233    /// store) or the ledger append failed. A check the caller
234    /// believes recorded but was not is worse than a refusal, so
235    /// recording is never best-effort.
236    #[error("check not recorded: {reason}")]
237    CheckNotRecorded { reason: String },
238    /// Entity type is not declared in the pinned schema for this
239    /// mem. Carries the declared types (sorted) and a fuzzy
240    /// suggestion so the agent can recover without re-reading the
241    /// schema. `schema_ref` is the pinned `<name>@<version>`.
242    #[error(
243        "unknown entity type '{name}' in schema '{schema_ref}'. Declared types: [{}]{}",
244        declared.join(", "),
245        suggestion.as_deref().map(|s| format!(". Did you mean '{s}'?")).unwrap_or_default()
246    )]
247    UnknownType {
248        name: String,
249        schema_ref: String,
250        declared: Vec<String>,
251        suggestion: Option<String>,
252    },
253    /// Title slug is empty / invalid.
254    #[error("title is invalid: {0}")]
255    InvalidTitle(#[from] SlugError),
256    /// Create attempted against an id already present in the store.
257    /// Names the occupant's title — distinct titles can derive the
258    /// same slug, so the id alone does not tell the caller which
259    /// entity holds it. `existing_is_stub` marks a stub occupant
260    /// (reachable via rename; the create path adopts stubs instead
261    /// of refusing).
262    #[error(
263        "entity already exists: {id} — occupied by {}",
264        render_occupant(existing_title, *existing_is_stub)
265    )]
266    AlreadyExists {
267        id: String,
268        existing_title: String,
269        existing_is_stub: bool,
270    },
271    /// Write refused: the entity as written would violate a
272    /// block-tier declared constraint of its type (`severity: block`
273    /// in the schema's `constraints`). Warn-tier violations warn
274    /// instead (`WarningHint::ConstraintUnsatisfied`) — same
275    /// evaluation, tier decided by the declaration. `violations`
276    /// restates each violated declaration so the caller can repair
277    /// without re-fetching the schema.
278    #[error(
279        "write refused: {entity_id} ({entity_type}) violates {n} block-tier declared constraint(s) — first: {first}",
280        n = violations.len(),
281        first = violations.first().map(|v| v.describe()).unwrap_or_default(),
282    )]
283    ConstraintUnsatisfied {
284        entity_type: String,
285        entity_id: String,
286        violations: Vec<crate::ops::health::UnsatisfiedConstraint>,
287    },
288    /// Write refused: a section body violates its schema-declared
289    /// markdown format (`content` / `item_pattern` / `table` on the
290    /// section, `format_severity: block`). The code and recovery
291    /// payload come from the violation itself
292    /// (`SECTION_CONTENT_MISMATCH` / `SECTION_ITEM_PATTERN_MISMATCH`
293    /// / `INVALID_TABLE_COLUMNS`, or `SECTION_CONTENT_INVALID` for a
294    /// reserved setext heading); the payload echoes the declared
295    /// `example` where one exists — for an agent, a conforming
296    /// example outperforms any grammar string.
297    #[error("write refused: {entity_id} ({entity_type}) — {}", violation.describe())]
298    SectionFormatRefused {
299        entity_type: String,
300        entity_id: String,
301        violation: crate::section_format::SectionFormatViolation,
302    },
303    /// Write refused: the entity's final edge set leaves a
304    /// block-tier `required_outgoing` block unsatisfied
305    /// (`severity: block` on the block). The default warn tier keeps
306    /// the long-standing warning behavior; this refusal exists only
307    /// where a schema explicitly promoted the block. Shares the
308    /// `MISSING_REQUIRED_OUTGOING` code and `missing` payload shape
309    /// with the warning — one condition, one vocabulary, tier decided
310    /// by the declaration.
311    #[error(
312        "write refused: {entity_id} ({entity_type}) leaves {n} block-tier `required_outgoing` block(s) unsatisfied",
313        n = missing.len(),
314    )]
315    RequiredOutgoingUnsatisfied {
316        entity_type: String,
317        entity_id: String,
318        missing: Vec<crate::ops::MissingRequiredOutgoingBlock>,
319    },
320    /// Mutation rejected because the named entity is not in the
321    /// store. Distinct from `UnknownMem`: the mem exists, the
322    /// entity does not.
323    #[error("entity not found: {id}")]
324    NotFound { id: String },
325    /// Optimistic-locking failure: the caller's `expected_hash` does
326    /// not match the entity's current `content_hash` in the store.
327    /// `current` is the live hash — pass it as `expected_hash` after
328    /// re-reading to retry. `is_stub` is set when the entity is a
329    /// stub (no body, no content_hash); the corrective action is to
330    /// pass `expected_hash: ""` rather than re-read via `memstead_entity`.
331    /// Surfaces on `details.is_stub` so MCP callers branch on the
332    /// structured payload instead of parsing the message text — pre-fix
333    /// the wire emitted `(current: )` with an empty paren that
334    /// misdirected toward hash-recovery for a stub-shaped entity.
335    #[error("{}", _hash_mismatch_msg(id, current, *is_stub))]
336    HashMismatch {
337        id: String,
338        current: String,
339        is_stub: bool,
340    },
341    /// Refusal to delete or rename an entity because other entities
342    /// in **Write-Mems** still reference it. There is no force flag
343    /// or escape hatch — the agent removes the offending references
344    /// (via `memstead_relate --remove` or `memstead_update`) before retrying.
345    /// `referrers` carries the typed referrer info (source id,
346    /// rel-type, source mem) so the response payload describes the
347    /// full surface in one round-trip. ReadOnly-mount referrers are
348    /// excluded from this list — they are handled by the residual-
349    /// stub demotion path on the destructive mutation.
350    #[error(
351        "entity {id} has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
352        n = referrers.len(),
353        inline = format_inline_list_overflow(referrers, "referrers"),
354    )]
355    HasIncomingRefs {
356        id: String,
357        referrers: Vec<ReferrerInfo>,
358    },
359    /// Refusal to delete a mem because entities in other Write-Mems
360    /// still reference entities inside it. Mirrors entity-level
361    /// [`Self::HasIncomingRefs`] at the mem granularity — the
362    /// edge-graph axis (F15 / CLI F8). Revoking a workspace-level grant only closes
363    /// the policy axis; this check closes the actual-edge axis so a
364    /// mem delete that would orphan cross-mem edges refuses with
365    /// the typed envelope listing every offending `(from_id, rel_type,
366    /// source_mem)` triple. No force flag — the operator must
367    /// `memstead_relate --remove` (or `memstead_update` to drop the section)
368    /// on each referrer first, then retry. ReadOnly-mount referrers
369    /// stay out of this list and route through the residual-stub
370    /// demotion path on the destructive mutation, same posture as the
371    /// entity-level variant.
372    #[error(
373        "mem `{mem}` has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
374        n = referrers.len(),
375        inline = format_inline_list_overflow(referrers, "referrers"),
376    )]
377    MemHasIncomingRefs {
378        mem: String,
379        referrers: Vec<ReferrerInfo>,
380    },
381    /// Relate across mems rejected because the workspace's
382    /// `[cross_mem_links]` policy (or the per-create-rule
383    /// `default_cross_links` synthesis) does not permit `from_mem →
384    /// to_mem`. Agents adjust the policy or pick a same-mem
385    /// target. The hint points at the workspace `[cross_mem_links]`
386    /// section.
387    #[error(
388        "cross-mem link from mem `{from_mem}` to mem `{to_mem}` is not allowed by the workspace `[cross_mem_links]` policy"
389    )]
390    CrossMemLinkNotAllowed { from_mem: String, to_mem: String },
391    /// Any add-shaped cross-mem edge write (`memstead_relate`,
392    /// `memstead_create.relations[]`, `memstead_update.declare_relations`,
393    /// or a body wiki-link) to a target whose mem is mounted
394    /// `MountCapability::ReadOnly` and the target is absent. Auto-stub
395    /// is unavailable across the engine/ReadOnly-mem boundary (the
396    /// engine cannot persist a stub in a mem it has no write access
397    /// to), and a read-only mem never gains the entity later — the
398    /// target must already exist before the link is written.
399    #[error(
400        "cross-mem link target {target_id} is absent in read-only mem `{target_mem}` — auto-stub is unavailable across the read-only boundary; the target must exist before linking"
401    )]
402    CrossMemTargetNotFound {
403        target_id: String,
404        target_mem: String,
405    },
406    /// `memstead_relate` across mems pinning schemas with different
407    /// *names* refused because the source schema's
408    /// `cross_mem_relationships:` section declares no entry for the
409    /// target schema's domain. Each source schema must explicitly
410    /// enumerate outbound cross-mem edges per target domain; the
411    /// absence here means the source schema does not speak the target
412    /// domain's vocabulary. Eligibility is name-based — a declaration
413    /// covers every version of the named target schema. The agent's
414    /// recovery is to declare the rel-type in the source schema's
415    /// `cross_mem_relationships:` section under the target's bare
416    /// schema name (`to_schema: <name>`).
417    ///
418    /// Orthogonal to the `cross_mem_links` permission policy:
419    /// vocabulary and permission fire independently. A policy-admissible
420    /// edge that violates vocabulary surfaces here; a vocabulary-admissible
421    /// edge that violates policy surfaces as
422    /// [`Self::CrossMemLinkNotAllowed`].
423    #[error(
424        "cross-mem edge {rel_type} from `{from_id}` (schema {source_schema}) to `{to_id}` (schema {target_schema}) is not declared in {source_schema}'s `cross_mem_relationships:` section"
425    )]
426    CrossMemEdgeNotDeclared {
427        source_schema: String,
428        target_schema: String,
429        rel_type: String,
430        from_id: String,
431        to_id: String,
432    },
433    /// `memstead_update` received repair-shaped input (`relations_unset`)
434    /// for an entity that currently passes the conformance check.
435    /// Repair-powers gate on evidence — a conformance failure on the
436    /// target entity — and a conformant entity has the focused tools
437    /// instead: `memstead_relate(remove)` detaches an edge, the additive
438    /// `memstead_update` params evolve content. The entity is not
439    /// modified.
440    #[error(
441        "repair input refused for {id}: the entity currently passes the conformance check — {recovery}"
442    )]
443    RepairNotNeeded { id: String, recovery: String },
444    /// Rename where the new title would slugify to the existing id.
445    /// Surfaced as a typed no-op so callers don't loop on a degenerate
446    /// retry.
447    #[error(
448        "rename would not change the id of {id} — new title {new_title:?} produces the same slug"
449    )]
450    RenameNoOp { id: String, new_title: String },
451    /// `memstead_update` / `memstead_batch_update` payload parsed cleanly but
452    /// carries no recognised mutation content — every mutation map is
453    /// empty and no relations are declared. Distinct from
454    /// `UPDATE_NOOP` (a warning that fires when mutation content was
455    /// provided but matched the current state): `EMPTY_UPDATE` is
456    /// keyed on "no mutation content provided at all", and refuses
457    /// before any mutation work runs so a misspelled/omitted mutation
458    /// key doesn't silently land as `succeeded: 1, commit_sha: ""`.
459    #[error(
460        "no mutation content for {id} — payload carries an id but every mutation map is empty (recognised keys: sections, append_sections, patch_sections, metadata, metadata_unset, declare_relations, relations_unset)"
461    )]
462    EmptyUpdate { id: String },
463    /// `memstead_rename` cannot proceed because one or more cross-mem
464    /// referrers would emit a propagated rewrite whose direction the
465    /// workspace's `cross_mem_links` policy does not permit. The
466    /// engine refuses the rename up-front (before any write); the
467    /// agent's recovery is either to grant the missing direction in
468    /// `[cross_mem_links]` or to drop the offending edges first.
469    ///
470    /// Each `blocked_referrers` entry names a single blocked direction
471    /// (`from_mem → to_mem`) — the referrer's mem and the
472    /// renaming entity's mem, respectively — together with the
473    /// count of distinct referrers in that mem that would emit the
474    /// blocked rewrite. The direction is the edge's actual direction
475    /// post-rewrite (`referrer → renamed`), which is what the policy
476    /// gates.
477    #[error(
478        "rename blocked: cross-mem rewrite from referrer mem(s) into `{from_mem}` is not permitted by `[cross_mem_links]` — blocked: {} — grant the missing direction or rewrite the blocked referrers manually",
479        format_blocked_referrers(blocked_referrers)
480    )]
481    RenameBlockedByCrossMemPolicy {
482        from_mem: String,
483        blocked_referrers: Vec<BlockedReferrer>,
484    },
485    /// `memstead_create` / `memstead_update` / `memstead_batch_update` refused
486    /// because the post-mutation entity's section bodies contain
487    /// inline wiki-links to targets that have no corresponding
488    /// explicit relation in `entity.relationships`. Strict
489    /// wiki-link / relation invariant: every body wiki-link must
490    /// have a backing relation. The agent's recovery is
491    /// `memstead_relate <this-entity> REFERENCES <target>` (or a more
492    /// specific rel-type) for each missing entry, then re-issue
493    /// the mutation. `missing` enumerates each violation as a
494    /// `(section_key, target_id)` pair so the agent can fix every
495    /// surviving link in one pass. This validator is gated behind
496    /// the workspace's reference-coherence migration completion
497    /// marker; workspaces that haven't been migrated continue
498    /// running the permissive auto-stub regime.
499    #[error(
500        "post-mutation body of {from_id} has {n} wiki-link(s) without a backing relation ({inline}) — declare the relation(s) via memstead_relate first (REFERENCES or a more specific rel-type), then retry",
501        n = missing.len(),
502        inline = format_inline_list_overflow(missing, "missing"),
503    )]
504    WikiLinkWithoutRelation {
505        from_id: String,
506        missing: Vec<MissingWikiLink>,
507    },
508    /// `memstead_relate --remove` refused because the source entity's
509    /// section bodies still contain `[[<target>]]` (or
510    /// `[[<mem>:<target>]]`) wiki-links pointing at the relation's
511    /// target. Removing the explicit relation while body links
512    /// survive would violate the strict wiki-link/relation invariant
513    /// (inline links require a backing relation). The agent's
514    /// recovery is `memstead_update <source-id>` with section content
515    /// that drops the wiki-link tokens, then re-issue `memstead_relate
516    /// --remove`. `body_links` enumerates the surviving section keys
517    /// so the agent can patch them in one pass.
518    #[error(
519        "cannot remove {rel_type} {from_id} → {to_id}: source body still contains wiki-link(s) to the target in section(s) {inline} — drop them via memstead_update before removing the relation",
520        inline = format_inline_list_overflow(body_links, "body_links"),
521    )]
522    RelationHasBodyLinks {
523        from_id: String,
524        to_id: String,
525        rel_type: String,
526        body_links: Vec<String>,
527    },
528    /// A multi-mem `memstead_rename` partially landed: at least one
529    /// mem committed successfully, then a subsequent per-mem
530    /// commit aborted (typically because a sibling writer advanced
531    /// the failed mem's head between the rename's snapshot and the
532    /// commit attempt — the parent-ref pin tripped via
533    /// `BackendError::ParentMismatch`). The committed mems' state
534    /// has already landed and is durable; the failed mem's writes
535    /// did not land. The agent's recovery options: retry the rename
536    /// (reload the workspace first so the engine re-derives the right
537    /// referrer set), or accept the partial state and reconcile
538    /// manually via subsequent mutations.
539    #[error(
540        "rename partial-failure: mem `{failed_mem}` aborted with cause {failure_cause:?} after {committed_mems:?} already committed — reload and retry, or reconcile manually"
541    )]
542    RenamePartialFailure {
543        committed_mems: Vec<String>,
544        failed_mem: String,
545        failure_cause: String,
546    },
547    /// `memstead_relate` source is a stub — stubs have no `entity_type`
548    /// and cannot author edges. The agent must promote the stub to a
549    /// real entity via `memstead_create` (stub adoption preserves any
550    /// incoming references) before relating. Pre-fix surfaced as the
551    /// cryptic `UnknownType { name: "" }`.
552    #[error("source entity {id} is a stub — promote it to a real entity via memstead_create first")]
553    StubCannotRelate { id: String },
554    /// `memstead_update` target is a stub — stubs have no body, no
555    /// metadata, no schema-resolved type to validate against. The
556    /// agent must promote the stub to a real entity via `memstead_create`
557    /// (stub adoption preserves any incoming references) before
558    /// updating. Pre-Item-02 surfaced as the cryptic
559    /// `UnknownType { name: "" }` cascade — identical symptom to the
560    /// one `StubCannotRelate` was added to replace on `memstead_relate`.
561    #[error("entity {id} is a stub — promote it to a real entity via memstead_create first")]
562    StubNotUpdatable { id: String },
563    /// `memstead_rename` target is a stub — stubs do not have a title to
564    /// rename (their title is derived from the id). Same recovery
565    /// path as [`Self::StubNotUpdatable`].
566    #[error(
567        "entity {id} is a stub — promote it to a real entity via memstead_create before renaming"
568    )]
569    StubNotRenamable { id: String },
570    /// An `EntityId` reaching a write path (notably `memstead_relate to=`)
571    /// does not match the wiki-link grammar
572    /// (`^[a-z0-9-]+(/[a-z0-9-]+)*$` for the slug; `^[a-z0-9-]+$` for
573    /// the mem). The gate prevents an auto-stub being created at a
574    /// malformed id — once present, that stub would fail any
575    /// downstream wiki-link parse that referenced it.
576    #[error("entity id '{id}' is malformed: {reason}")]
577    InvalidEntityId { id: String, reason: String },
578    /// A body wiki-link target in a section body failed the strict
579    /// slug-form grammar gate. The invariant is that every wiki-link target reaching
580    /// `entity.relationships` carries a grammar-valid `EntityId` — the
581    /// alias-synthesis pass would otherwise emit a relation pointing
582    /// at a literal id (e.g. `mem--Knowledge Graph`) that no
583    /// downstream wiki-link parse could ever resolve. `raw` is the
584    /// input between brackets (after alias / `.md` strip); `suggested`
585    /// is the `title_to_slug`-derived slug-form the agent lifts
586    /// directly into the retry (omitted when the input has no
587    /// meaningful canonical form — empty, all-punctuation, all-emoji);
588    /// `section` is the section key whose body carried the link;
589    /// `source` is a stable discriminator (`"body_link"`) future-
590    /// proofed against additional ingress surfaces.
591    #[error("body wiki-link target '{raw}' in section '{section}' is not slug-form: {reason}")]
592    InvalidWikiLinkTarget {
593        raw: String,
594        suggested: Option<String>,
595        section: String,
596        link_source: String,
597        reason: String,
598    },
599    /// A body wiki-link's Tier-2 mem prefix `[[mem:slug]]` failed
600    /// the mem-name grammar (`^[a-z0-9-]+(/[a-z0-9-]+)*$`). Distinct
601    /// from `InvalidWikiLinkTarget` because the recovery is different
602    /// — mem names are fixed identifiers in the workspace, not
603    /// free-form text the agent can mechanically slugify; the agent
604    /// correlates the bad prefix against the workspace's known mems
605    /// rather than reaching for `title_to_slug`.
606    #[error(
607        "body wiki-link mem prefix '{raw}' in section '{section}' is not a valid mem name: {reason}"
608    )]
609    InvalidWikiLinkMem {
610        raw: String,
611        section: String,
612        reason: String,
613    },
614    /// `memstead_update` was asked to apply more than one section-
615    /// mutation mode (`sections`, `append_sections`,
616    /// `patch_sections`) to the same key. The request is ambiguous
617    /// and rejected before any disk write. `modes` lists the
618    /// conflicting modes for the key in canonical order.
619    #[error("conflicting section modes for {section}: {modes:?}")]
620    ConflictingSectionModes { section: String, modes: Vec<String> },
621    /// Adding the proposed edge would close a cycle in an
622    /// acyclic-declared subgraph. Carries the existing back-path
623    /// `[from, …, current, target's intermediates, … from]` so MCP
624    /// envelopes ship the cycle's shape without a follow-up
625    /// `memstead_search`. Truncated at
626    /// [`RELATIONSHIP_CYCLE_PATH_CAP`] entries.
627    #[error(
628        "creating edge {rel_type} from '{from}' to '{to}' would close a cycle in the {rel_type} subgraph"
629    )]
630    RelationshipCycle {
631        rel_type: String,
632        from: EntityId,
633        to: EntityId,
634        existing_path: Vec<EntityId>,
635        path_truncated: bool,
636    },
637    /// `memstead_update` received the same metadata key in both `metadata`
638    /// (set) and `metadata_unset` lists. The request is ambiguous and
639    /// rejected before any disk write — the caller picks which map the
640    /// key belongs in. `keys` lists every overlapping key in alphabetical
641    /// order so a single envelope describes the full conflict.
642    #[error("metadata keys appear in both set and unset: {keys:?}")]
643    SetAndUnsetConflict { keys: Vec<String> },
644    /// `metadata_unset` targeted a required field. Carries the
645    /// recovery payload so the agent reads the field's purpose,
646    /// allowed values, and type-level write rules from the envelope
647    /// rather than re-fetching the schema.
648    ///
649    /// Also fires from `memstead_create` when the
650    /// caller did not supply a required metadata field that the
651    /// schema does not auto-fill (`default_value` / `init_timestamp`
652    /// / `auto_timestamp` all absent). Pre-fix the create path
653    /// surfaced this as a `MISSING_REQUIRED_FIELD` warning and let
654    /// the entity land with a placeholder — silently corrupted the
655    /// export-then-install round-trip when the placeholder was
656    /// invalid for the install-time strict validator. The refusal
657    /// fires once per call on the first missing field (declaration
658    /// order); subsequent fields surface on the next attempt.
659    #[error("{}", _required_field_unset_msg(field, entity_type, *on_create))]
660    RequiredFieldUnset {
661        field: String,
662        entity_type: String,
663        /// Schema-supplied description of the field.
664        field_description: Option<String>,
665        /// Allowed enum values when the unset field is enum-typed;
666        /// empty when the field is free-form.
667        enum_values: Vec<String>,
668        /// Type-level `write_rules` for the entity type.
669        type_write_rules: Vec<String>,
670        /// Path discriminator: `true` when the
671        /// create path constructed the variant (caller didn't supply
672        /// the field), `false` when the update path constructed it
673        /// (caller passed `metadata_unset: ["field"]` against a
674        /// required field). The typed code stays `REQUIRED_FIELD_UNSET`
675        /// on both paths; only the rendered prose differs.
676        ///
677        /// Not exposed on the `details` payload — agents already
678        /// branch on the typed code; the new field is for the prose
679        /// dispatch only.
680        on_create: bool,
681        /// Multi-field
682        /// accumulator on the create path. Every required-no-default
683        /// field that was unset, in schema declaration order. Empty
684        /// on the unset path (where the agent targets one field by
685        /// definition and the singular fields above are authoritative);
686        /// always non-empty (and at least a singleton echo of the
687        /// singular fields) on the create path.
688        ///
689        /// Surfaces on `details.missing[]` so an agent fixes every
690        /// missing field in one round-trip. `details.field` and
691        /// `details.missing[0].field` agree on the first-missing
692        /// entry, keeping the back-compat singular-field shape.
693        missing: Vec<MissingRequiredField>,
694    },
695    /// `memstead_create`: one or more required sections for the entity's
696    /// type were absent or whitespace-only in the request. Pre-fix
697    /// the create path surfaced this as `MISSING_REQUIRED_SECTION`
698    /// warnings and wrote the entity with empty placeholders for
699    /// the missing sections; the resulting on-disk state failed the
700    /// install-time strict validator, breaking the export-then-
701    /// install round-trip. The refusal carries every missing section
702    /// (one entry per affected key) plus the type-level `type_guidance`
703    /// map so the agent has a single round-trip recovery via re-call
704    /// with the missing content filled in.
705    ///
706    /// Loader / health / `memstead_update` paths keep their permissive
707    /// posture — a legacy on-disk entity created when this gate was
708    /// a warning continues to load, surface in health, and accept
709    /// partial updates. The refusal is a write-boundary gate, not a
710    /// global invariant.
711    #[error("missing {missing_count} required section(s) for type '{entity_type}'")]
712    MissingRequiredSection {
713        entity_type: String,
714        /// Echoed for diagnostics; equals `sections.len()`.
715        missing_count: usize,
716        /// One entry per missing required section, in schema
717        /// declaration order. Each entry mirrors the shape of the
718        /// pre-fix `WarningHint::MissingRequiredSection` warning so
719        /// agents reading the recovery payload don't branch on
720        /// surface (refusal vs warning).
721        sections: Vec<crate::runtime_validator::MissingRequiredSection>,
722        /// Type-level `write_rules` keyed by `entity_type`. Map shape
723        /// matches the mutation-response top-level `type_guidance`
724        /// the warning-surface ships so a single decoder reads
725        /// guidance from either path.
726        type_guidance: std::collections::BTreeMap<String, Vec<String>>,
727    },
728    /// `patch_sections` targeted a key whose section body is
729    /// absent from the entity (or has never been authored).
730    #[error("patch target section is empty: {section}")]
731    PatchSectionEmpty { section: String },
732    /// `patch_sections` provided an `old` substring that does not
733    /// appear in the section's current body. Carries a truncated
734    /// snapshot of the current content so the caller can surface
735    /// the actual state to the operator.
736    #[error("patch `old` substring not found in {section}")]
737    PatchOldNotFound {
738        section: String,
739        current_content: String,
740        truncated: bool,
741    },
742    /// Schema-strictness rejection from the runtime validator
743    /// (`UNKNOWN_SECTION`, `UNKNOWN_METADATA`, `INVALID_ENUM_VALUE`).
744    #[error("schema validation: {0}")]
745    Validation(#[from] ValidationError),
746    /// Re-parse of the freshly-generated markdown failed. Should
747    /// never happen — the generator's contract is that its output
748    /// round-trips through `parse_markdown`. Surfaces if a future
749    /// generator change breaks that invariant.
750    #[error("parse-after-write failed: {0}")]
751    ParseAfterWrite(String),
752    /// A wrapped parse error for completeness; today only the
753    /// parse-after-write variant above is constructed in the create
754    /// path.
755    #[error("parse error: {0}")]
756    Parse(#[from] ParseError),
757    /// A backend operation failed. Inner error carries the typed
758    /// payload (e.g. `Sealed`, `HashMismatch`, `Io`).
759    #[error(transparent)]
760    Backend(#[from] BackendError),
761    /// A mem's schema pin did not resolve. `sources` carries the
762    /// fixed-order resolution diagnostics (local storage / built-in /
763    /// remote) so the caller can tell *where* the pin failed and spot a
764    /// right-name/wrong-version partial match; it surfaces under
765    /// `details.sources`. Empty `sources` marks an internal lookup miss
766    /// (an already-resolved schema absent from the engine's per-mem
767    /// map), not a genuine source-resolution failure.
768    ///
769    /// The MESSAGE summarises the trail — which sources were searched
770    /// and whether the name was found at other versions — so the
771    /// distinction between a wrong-version pin and a never-installed
772    /// package reaches consumers that never open `details` (a reported
773    /// autonomous loop burned five rounds on the payload-only shape).
774    /// `install_hint` (set by [`EngineError::with_schema_install_probe`]
775    /// where a workspace root is known) names the authoring package
776    /// that exists in the working tree but was never installed, and
777    /// the message then points at `memstead schema install`.
778    #[error("{}", schema_not_found_message(mem, pin, sources, install_hint))]
779    SchemaNotFound {
780        mem: String,
781        pin: String,
782        sources: Vec<SchemaSourceDiagnostic>,
783        /// Path to an authoring package in the working tree whose
784        /// manifest name matches the pin's name while NO source holds
785        /// any version of that name — i.e. the package was authored
786        /// but never installed. `None` when no such package exists,
787        /// when the name is installed at other versions (a version
788        /// mismatch is a different fix), or when no workspace root
789        /// was available to probe.
790        install_hint: Option<String>,
791    },
792    /// A schema package handed to `install_schema` failed validation —
793    /// the loader's semantic checks or the section-heading round-trip
794    /// gate. The engine refuses to seal an invalid schema onto
795    /// `__MEMSTEAD`: install time is the last moment the author can
796    /// act, because a schema already sealed keeps loading even when a
797    /// later rule would refuse it.
798    #[error("schema package '{name}@{version}' failed validation: {message}")]
799    SchemaPackageInvalid {
800        name: String,
801        version: String,
802        message: String,
803    },
804    /// `memstead_schema::builtins::load_builtin_schemas` itself failed.
805    /// Surfaces during `Engine::from_mounts`; should never trip in
806    /// practice (the built-in catalogue is statically embedded), but
807    /// the failure path is preserved so a future on-disk catalogue
808    /// switch lifts cleanly.
809    #[error("built-in schema catalogue failed to load: {0}")]
810    SchemaResolverInit(String),
811    /// Generic mem-level error message — used by accessors that
812    /// surface "mem exists, but the requested resource is not
813    /// available for this backend" (e.g. `gitdir_for` against a
814    /// folder mount, `worktree_for` against a git-branch mount).
815    #[error("mem error: {0}")]
816    Mem(String),
817    /// `register_writable_mem` rejected because `name` is already
818    /// registered (writable OR read-only). `source_origin` is the
819    /// human-readable description of the colliding registration,
820    /// rendered via [`MemOrigin::render_source`] for writable
821    /// entries or a stand-in for read-only ones.
822    #[error("mem name collision: {name} is already registered ({source_origin})")]
823    MemNameCollision { name: String, source_origin: String },
824    /// Lifecycle orchestrator rejected the input. Carries a single
825    /// free-form message — the orchestrator's typed payload (note
826    /// length, malformed path, etc.) is the message text.
827    #[error("invalid input: {0}")]
828    InvalidInput(String),
829    /// `memstead_fetch` / `memstead_pull` / `memstead_push` named a remote that is
830    /// not configured on the workspace's mem-repo. Typed code
831    /// `UNKNOWN_REMOTE`. Recovery: configure the remote via
832    /// `memstead mem-repo remote-add <name> <url>`.
833    #[error("unknown remote: {0}")]
834    UnknownRemote(String),
835    /// `memstead_pull` refused because the local branch has diverged from
836    /// the remote-tracking ref — fast-forward is impossible without
837    /// losing local commits. Recovery: run `memstead branch-reset` to the
838    /// remote-tracking ref (if the local commits are dispensable) or
839    /// run a replay workflow to rewrite them onto the new remote tip.
840    /// Typed code `LOCAL_DIVERGENCE`.
841    #[error(
842        "mem `{mem}`'s local branch has diverged from `{remote_ref}` — pull cannot fast-forward without losing local commits; rebase / replay first or run memstead branch-reset"
843    )]
844    LocalDivergence { mem: String, remote_ref: String },
845    /// `memstead_push` refused because the push would not be a fast-forward
846    /// against the remote and the caller did not pass `force: true`.
847    /// Typed code `NON_FAST_FORWARD`. Recovery: re-fetch + replay, or
848    /// re-issue with `force: true` (warning: rewrites the remote's
849    /// view of the branch — other peers will see the rewrite).
850    #[error(
851        "push to remote `{remote}` for mem `{mem}` is not a fast-forward; rebase / replay locally or pass `force: true` to overwrite the remote"
852    )]
853    NonFastForward { mem: String, remote: String },
854    /// `memstead_push` refused because the local state failed pre-push
855    /// schema validation. The remote was not contacted. Recovery: fix
856    /// the schema violations (use `memstead_health` to find them) and
857    /// retry. Typed code `LOCAL_INVALID_STATE`.
858    #[error(
859        "mem `{mem}` failed pre-push schema validation; remote `{remote}` was not contacted: {detail}"
860    )]
861    LocalInvalidState {
862        mem: String,
863        remote: String,
864        detail: String,
865    },
866    /// `memstead_pull` (or any future merge path that consumes fetched
867    /// commits) refused because the prospective post-merge tree
868    /// contains entities that fail schema validation. The branch
869    /// pointer was not moved. `violations` carries one entry per
870    /// offending entity — typically `(relative_path, parse_error)`
871    /// pairs rendered as strings — so the caller can surface the
872    /// remediation surface without re-walking the tree. Typed code
873    /// `SCHEMA_VIOLATION_IN_FETCH`.
874    #[error(
875        "mem `{mem}` would fail schema validation at `{ref_name}` — {n} violation(s); fix the remote or replay locally first",
876        n = violations.len(),
877    )]
878    SchemaViolationInFetch {
879        mem: String,
880        ref_name: String,
881        violations: Vec<String>,
882    },
883    /// `memstead_branch_reset` refused because at least one commit that
884    /// would be discarded by the reset is already reachable from a
885    /// `refs/remotes/*` ref (the engine's definition of "pushed").
886    /// `pushed_shas` lists the offending commits. The agent's
887    /// recovery is to pick a target SHA that does not strand a pushed
888    /// commit, or to push the pre-reset state under a different
889    /// branch name first. Typed code: `PUSHED_COMMITS_PROTECTED`.
890    #[error(
891        "branch_reset refused: {} pushed commit(s) would be discarded ({}); pick a target that preserves the pushed segment or push the pre-reset state under a different branch first",
892        pushed_shas.len(),
893        pushed_shas.join(", "),
894    )]
895    PushedCommitsProtected {
896        mem: String,
897        target_sha: String,
898        pushed_shas: Vec<String>,
899    },
900    /// `branch_reset` refused because the live branch head no longer
901    /// matches the head the caller observed (`expected_head`) — a
902    /// sibling writer advanced the mem, and resetting now would discard
903    /// that foreign work. Optimistic concurrency for history rewrites;
904    /// the caller re-reads and re-decides. Typed code:
905    /// `BRANCH_RESET_HEAD_MOVED`.
906    #[error(
907        "branch_reset refused: '{mem}' has advanced past the observed head (expected {expected}, live {current}) — the span now contains foreign commits; reload and review the accumulated delta instead"
908    )]
909    BranchResetHeadMoved {
910        mem: String,
911        expected: String,
912        current: String,
913    },
914    /// `memstead_diff` (or any future ref-comparing op) received a ref
915    /// that does not resolve against the workspace's mem-repo.
916    /// Carries the ref string verbatim so the caller can fix the
917    /// input. Typed code `UNKNOWN_REF`.
918    #[error("unknown ref: {0}")]
919    UnknownRef(String),
920    /// `memstead_changes_since` received a `rename_similarity` value
921    /// outside the allowed range. Maps to wire code `INVALID_INPUT`
922    /// with `details.allowed_range: [min, max]` and
923    /// `details.requested`. Promoted from the prior silent-clamp + LIMIT_CLAMPED warning so
924    /// nonsense inputs surface as recoverable refusal rather than
925    /// silent rounding.
926    #[error("rename_similarity {requested} outside allowed range [{allowed_min}, {allowed_max}]")]
927    RenameSimilarityOutOfRange {
928        requested: f32,
929        allowed_min: f32,
930        allowed_max: f32,
931    },
932    /// `memstead_changes_since` / `memstead changes --since` was given a `since`
933    /// commit cursor the mem's git repository can't resolve — a
934    /// malformed prefix or a well-formed-but-absent 40-hex. Surfaces the
935    /// `INVALID_CURSOR` code (the documented contract for this op, which
936    /// the CLI previously leaked as the `MEM_ERROR` catch-all) so a
937    /// sync loop branches cleanly: `INVALID_CURSOR` → re-seed from the
938    /// empty-tree sentinel; `MEM_ERROR` → genuine backend fault.
939    /// `details.since` carries the offending cursor untruncated.
940    #[error(
941        "commit cursor '{since}' is not a known commit in mem '{mem}' — pass a commit_sha from a prior mutation, or the empty-tree sentinel to re-seed"
942    )]
943    InvalidChangesCursor { mem: String, since: String },
944    /// `review_mark_diff` was called on a mem with no review mark set.
945    /// Marklessness is a first-class, known-from-the-roster state — the
946    /// diff surface refuses typed rather than silently equating "no
947    /// mark" with "no changes".
948    #[error(
949        "mem '{mem}' has no review mark — set one first, or read the full history via changes_since"
950    )]
951    ReviewMarkNotSet { mem: String },
952    /// Mem config is missing a required field that the engine
953    /// itself would normally populate (today: `version` at mem
954    /// init). Surfaced on the export path — pre-fix this collapsed
955    /// to `INTERNAL` with a misleading `.memstead/config.json` reference
956    /// that doesn't match the mem-repo backend's blob layout.
957    /// Recovery: run `memstead mem set-version <mem> <version>` to
958    /// populate the field, then retry the export. F1.
959    #[error(
960        "mem `{mem}` config is missing required field(s) {missing_fields:?} — \
961         set via `memstead mem set-version {mem} <version>` (e.g. 0.1.0)"
962    )]
963    MemConfigIncomplete {
964        mem: String,
965        missing_fields: Vec<String>,
966    },
967    /// `memstead_relate` (or a `declare_relations` entry) targeted a
968    /// rel-type whose schema declares `per_edge_description:
969    /// required` without supplying a description. Recovery: re-issue
970    /// the call with `--description "<text>"` describing why this
971    /// particular edge exists (the rel-type's name documents the
972    /// kind of edge; the description documents the instance).
973    #[error(
974        "rel-type `{rel_type}` declares `per_edge_description: required` — \
975         {from_id} → {to_id} needs a description; re-issue with \
976         `--description \"<text>\"`."
977    )]
978    MissingRequiredDescription {
979        rel_type: String,
980        from_id: String,
981        to_id: String,
982    },
983    /// `memstead_relate` (or a `declare_relations` entry) supplied a
984    /// description for a rel-type whose schema declares
985    /// `per_edge_description: forbidden`. Recovery: drop the
986    /// `description` parameter — the rel-type's name describes the
987    /// edge; per-edge text is not permitted on this rel-type.
988    #[error(
989        "rel-type `{rel_type}` declares `per_edge_description: forbidden` — \
990         {from_id} → {to_id} cannot carry a description; drop the \
991         `--description` argument."
992    )]
993    DescriptionNotPermitted {
994        rel_type: String,
995        from_id: String,
996        to_id: String,
997    },
998    /// `memstead_relate` (or a `declare_relations` / `memstead_create`'s
999    /// inline `relations:` entry) targeted a rel-type whose schema
1000    /// declares `manual_authoring: forbidden`. The rel-type is
1001    /// reserved for engine-emitted synthesis (the body-link →
1002    /// relation alias machinery, typically). Recovery: don't author
1003    /// the relation explicitly; instead author a body wiki-link
1004    /// `[[target]]` in the source's section content, which the
1005    /// engine surfaces as the appropriate alias relation
1006    /// automatically.
1007    #[error(
1008        "rel-type `{rel_type}` declares `manual_authoring: forbidden` — \
1009         {from_id} → {to_id} cannot be authored explicitly; this rel-type \
1010         is reserved for engine-emitted synthesis via the body-link → \
1011         relation alias path. {guidance}"
1012    )]
1013    RelationManualAuthoringForbidden {
1014        rel_type: String,
1015        from_id: String,
1016        to_id: String,
1017        guidance: String,
1018    },
1019    /// Full-text search is unavailable in the current engine build —
1020    /// `Engine::search` is callable on every target so JS / FFI
1021    /// consumers don't need to re-shape their call sites, but `wasm32`
1022    /// builds omit the tantivy index entirely (its native-only
1023    /// transitives — `getrandom 0.2` without `js`, `memmap2`, `rayon`,
1024    /// `zstd-sys` — block WASM compilation). Browser consumers route
1025    /// queries to the bridge's `memstead_search` endpoint. The MCP layer
1026    /// maps this to typed code `SEARCH_UNAVAILABLE_IN_WASM`.
1027    #[error(
1028        "full-text search is unavailable in this engine build (wasm32); \
1029         route search queries to the bridge's memstead_search endpoint"
1030    )]
1031    SearchUnavailable,
1032    /// `memstead export --format markdown --mem-name <V>` was called
1033    /// against a mem whose active backend doesn't support markdown
1034    /// regeneration in place (today: every backend other than
1035    /// `folder`). Pre-fix this collapsed to a silent
1036    /// `ExportResult { written: 0, unchanged: 0 }` masquerading as
1037    /// success. Recovery: use `--format mem` to produce a portable
1038    /// `.mem` archive, which every backend supports.
1039    #[error(
1040        "mem `{mem}` is on backend `{active_backend}`; `memstead export --format markdown` \
1041         is supported only on backends [{}] — use `--format mem` to produce a portable \
1042         `.mem` archive instead",
1043        supported_backends.join(", ")
1044    )]
1045    MarkdownExportUnsupportedBackend {
1046        mem: String,
1047        active_backend: String,
1048        supported_backends: Vec<String>,
1049    },
1050    /// A `memstead_create` / `memstead_update` `anchors[]` element was
1051    /// malformed — an unknown provenance class or grain, a missing artifact
1052    /// reference, a content hash on a class without hash semantics, or a
1053    /// grain the resolving medium's namespace cannot express. The whole
1054    /// mutation refuses and the entity is not written; the wrapped
1055    /// [`crate::anchor::AnchorValidationError`] carries the recovery
1056    /// `details` (offending field, bad value, allowed set). Typed code
1057    /// `INVALID_ANCHOR`.
1058    #[error("invalid anchor: {0}")]
1059    InvalidAnchor(#[from] crate::anchor::AnchorValidationError),
1060}
1061
1062/// Typed payload for a single Write-Mem referrer in
1063/// [`EngineError::HasIncomingRefs`]. Captures the (from_id, rel_types,
1064/// mem) triple the surface envelope projects so consumers can reason
1065/// about the offending edges without a follow-up `memstead_entity` call.
1066/// The mem is always a Write-Mem — ReadOnly referrers are
1067/// partitioned out before this struct is constructed and surfaced via
1068/// the residual-stub warning channel instead.
1069///
1070/// Per-source deduplication: when one source entity has multiple
1071/// edges of different rel-types pointing at the deletion target, the
1072/// engine collapses them into a single `ReferrerInfo` whose
1073/// `rel_types` list carries every edge type. A prior shape
1074/// emitted one entry per edge, making a source-with-N-edges look
1075/// like N distinct referrers in the error message and structured
1076/// payload.
1077#[derive(Debug, Clone, serde::Serialize)]
1078pub struct ReferrerInfo {
1079    pub from_id: String,
1080    pub rel_types: Vec<String>,
1081    pub mem: String,
1082}
1083
1084/// Inline rendering on the text mirror. Single rel-type renders as
1085/// just the referring entity id; multiple rel-types append the
1086/// `×N [REL1, REL2]` annotation so the count and the offending
1087/// edge-types stay visible without parsing the structured payload.
1088impl fmt::Display for ReferrerInfo {
1089    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1090        if self.rel_types.len() <= 1 {
1091            f.write_str(&self.from_id)
1092        } else {
1093            write!(
1094                f,
1095                "{} ×{} [{}]",
1096                self.from_id,
1097                self.rel_types.len(),
1098                self.rel_types.join(", ")
1099            )
1100        }
1101    }
1102}
1103
1104/// One body wiki-link that violates the strict wiki-link /
1105/// relation invariant. Surfaces inside
1106/// [`EngineError::WikiLinkWithoutRelation::missing`].
1107#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
1108pub struct MissingWikiLink {
1109    /// Section key of the entity body where the unbacked
1110    /// wiki-link appears.
1111    pub section_key: String,
1112    /// EntityId target of the unbacked wiki-link.
1113    pub target_id: String,
1114}
1115
1116/// Inline rendering pairs the section key with the unbacked target id
1117/// so an agent reading only the text mirror can see both where the link
1118/// lives and what it points at without decoding the structured payload.
1119impl fmt::Display for MissingWikiLink {
1120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1121        write!(f, "{}→{}", self.section_key, self.target_id)
1122    }
1123}
1124
1125impl EngineError {
1126    /// Stable, surface-independent error code token.
1127    ///
1128    /// Each surface (MCP envelope, CLI envelope, UniFFI binding) maps
1129    /// the variant to its wire shape; the code returned here is the
1130    /// canonical name agents key on. Add a new code here when a new
1131    /// variant lands; do not invent ad-hoc strings inside the
1132    /// per-surface mapping.
1133    pub fn code(&self) -> &'static str {
1134        match self {
1135            EngineError::DuplicateMem(_) => "DUPLICATE_MEM",
1136            EngineError::UnknownMem(_) => "UNKNOWN_MEM",
1137            EngineError::MemQuarantined { .. } => "MEM_QUARANTINED",
1138            EngineError::UnknownRef(_) => "UNKNOWN_REF",
1139            EngineError::UnknownRemote(_) => "UNKNOWN_REMOTE",
1140            EngineError::LocalDivergence { .. } => "LOCAL_DIVERGENCE",
1141            EngineError::NonFastForward { .. } => "NON_FAST_FORWARD",
1142            EngineError::LocalInvalidState { .. } => "LOCAL_INVALID_STATE",
1143            EngineError::SchemaViolationInFetch { .. } => "SCHEMA_VIOLATION_IN_FETCH",
1144            EngineError::PushedCommitsProtected { .. } => "PUSHED_COMMITS_PROTECTED",
1145            EngineError::BranchResetHeadMoved { .. } => "BRANCH_RESET_HEAD_MOVED",
1146            EngineError::ReadOnlyMount(_) => "READ_ONLY_MOUNT",
1147            EngineError::CheckNotRecorded { .. } => "CHECK_NOT_RECORDED",
1148            EngineError::UnknownType { .. } => "UNKNOWN_ENTITY_TYPE",
1149            EngineError::InvalidTitle(_) => "INVALID_TITLE",
1150            EngineError::AlreadyExists { .. } => "ENTITY_ALREADY_EXISTS",
1151            EngineError::ConstraintUnsatisfied { .. } => "CONSTRAINT_UNSATISFIED",
1152            EngineError::RequiredOutgoingUnsatisfied { .. } => "MISSING_REQUIRED_OUTGOING",
1153            EngineError::SectionFormatRefused { violation, .. } => violation.code(),
1154            EngineError::NotFound { .. } => "ENTITY_NOT_FOUND",
1155            EngineError::HashMismatch { .. } => "HASH_MISMATCH",
1156            EngineError::HasIncomingRefs { .. } => "HAS_INCOMING_REFS",
1157            EngineError::MemHasIncomingRefs { .. } => "MEM_HAS_INCOMING_REFS",
1158            EngineError::CrossMemLinkNotAllowed { .. } => "CROSS_MEM_LINK_NOT_ALLOWED",
1159            EngineError::CrossMemTargetNotFound { .. } => "CROSS_MEM_TARGET_NOT_FOUND",
1160            EngineError::CrossMemEdgeNotDeclared { .. } => "CROSS_MEM_EDGE_NOT_DECLARED",
1161            EngineError::RepairNotNeeded { .. } => "REPAIR_NOT_NEEDED",
1162            EngineError::RenameNoOp { .. } => "RENAME_NO_OP",
1163            EngineError::EmptyUpdate { .. } => "EMPTY_UPDATE",
1164            EngineError::RenameBlockedByCrossMemPolicy { .. } => {
1165                "RENAME_BLOCKED_BY_CROSS_MEM_POLICY"
1166            }
1167            EngineError::RenamePartialFailure { .. } => "RENAME_PARTIAL_FAILURE",
1168            EngineError::RelationHasBodyLinks { .. } => "RELATION_HAS_BODY_LINKS",
1169            EngineError::WikiLinkWithoutRelation { .. } => "WIKILINK_WITHOUT_RELATION",
1170            EngineError::StubCannotRelate { .. } => "STUB_CANNOT_RELATE",
1171            EngineError::StubNotUpdatable { .. } => "STUB_NOT_UPDATABLE",
1172            EngineError::StubNotRenamable { .. } => "STUB_NOT_RENAMABLE",
1173            EngineError::InvalidEntityId { .. } => "INVALID_ENTITY_ID",
1174            EngineError::InvalidWikiLinkTarget { .. } => "INVALID_WIKI_LINK_TARGET",
1175            EngineError::InvalidWikiLinkMem { .. } => "INVALID_MEM_NAME",
1176            EngineError::ConflictingSectionModes { .. } => "CONFLICTING_SECTION_MODES",
1177            EngineError::RelationshipCycle { .. } => "RELATIONSHIP_CYCLE",
1178            EngineError::SetAndUnsetConflict { .. } => "SET_AND_UNSET_CONFLICT",
1179            EngineError::RequiredFieldUnset { .. } => "REQUIRED_FIELD_UNSET",
1180            EngineError::MissingRequiredSection { .. } => "MISSING_REQUIRED_SECTION",
1181            EngineError::PatchSectionEmpty { .. } => "PATCH_SECTION_EMPTY",
1182            EngineError::PatchOldNotFound { .. } => "PATCH_OLD_NOT_FOUND",
1183            EngineError::Validation(v) => v.code(),
1184            EngineError::ParseAfterWrite(_) => "PARSE_ERROR",
1185            EngineError::Parse(_) => "PARSE_ERROR",
1186            EngineError::Backend(_) => "MEM_ERROR",
1187            EngineError::SchemaNotFound { .. } => "SCHEMA_NOT_FOUND",
1188            EngineError::SchemaPackageInvalid { .. } => "SCHEMA_VALIDATION_FAILED",
1189            EngineError::SchemaResolverInit(_) => "SCHEMA_RESOLVER_INIT_FAILED",
1190            EngineError::Mem(_) => "MEM_ERROR",
1191            EngineError::MemNameCollision { .. } => "MEM_NAME_COLLISION",
1192            EngineError::InvalidInput(_) => "INVALID_INPUT",
1193            EngineError::RenameSimilarityOutOfRange { .. } => "INVALID_INPUT",
1194            EngineError::InvalidChangesCursor { .. } => "INVALID_CURSOR",
1195            EngineError::ReviewMarkNotSet { .. } => "REVIEW_MARK_NOT_SET",
1196            EngineError::MemConfigIncomplete { .. } => "MEM_CONFIG_INCOMPLETE",
1197            EngineError::MissingRequiredDescription { .. } => "MISSING_REQUIRED_DESCRIPTION",
1198            EngineError::DescriptionNotPermitted { .. } => "DESCRIPTION_NOT_PERMITTED",
1199            EngineError::RelationManualAuthoringForbidden { .. } => {
1200                "RELATION_MANUAL_AUTHORING_FORBIDDEN"
1201            }
1202            EngineError::SearchUnavailable => "SEARCH_UNAVAILABLE_IN_WASM",
1203            EngineError::MarkdownExportUnsupportedBackend { .. } => {
1204                "MARKDOWN_EXPORT_UNSUPPORTED_BACKEND"
1205            }
1206            EngineError::InvalidAnchor(_) => crate::anchor::INVALID_ANCHOR_CODE,
1207        }
1208    }
1209
1210    /// Variant-specific recovery payload, rendered as a structured
1211    /// JSON object that surfaces under `error.details` in MCP /
1212    /// CLI envelopes.
1213    ///
1214    /// Pre-fix the
1215    /// batch-update per-item envelope (`batch_error_envelope`)
1216    /// shipped `{}` for every typed code except `Validation`, while
1217    /// the singleton-call surfaces (`CliError::from_engine_op`,
1218    /// `memstead-mcp`'s `engine_err_unified`) populated structured
1219    /// payloads per-variant. Two envelopes, two details paths —
1220    /// agents' "fix from `details`" recovery loop worked
1221    /// differently in batch vs singleton mode. The centralised
1222    /// helper here gives both surfaces one source of truth.
1223    ///
1224    /// Returns an empty object for variants whose recovery payload
1225    /// is the message text alone (no structured fields beyond
1226    /// `code` + `message`).
1227    pub fn details(&self) -> serde_json::Value {
1228        match self {
1229            EngineError::NotFound { id } => serde_json::json!({ "id": id }),
1230            EngineError::AlreadyExists {
1231                id,
1232                existing_title,
1233                existing_is_stub,
1234            } => serde_json::json!({
1235                "id": id,
1236                "existing_title": existing_title,
1237                "existing_is_stub": existing_is_stub,
1238            }),
1239            EngineError::MemQuarantined {
1240                mem,
1241                reason_code,
1242                reason_message,
1243            } => serde_json::json!({
1244                "mem": mem,
1245                "reason_code": reason_code,
1246                "reason_message": reason_message,
1247            }),
1248            EngineError::ConstraintUnsatisfied {
1249                entity_type,
1250                entity_id,
1251                violations,
1252            } => serde_json::json!({
1253                "entity_type": entity_type,
1254                "entity_id": entity_id,
1255                "violations": violations,
1256            }),
1257            EngineError::RequiredOutgoingUnsatisfied {
1258                entity_type,
1259                entity_id,
1260                missing,
1261            } => serde_json::json!({
1262                "entity_type": entity_type,
1263                "entity_id": entity_id,
1264                "missing": missing,
1265            }),
1266            EngineError::SectionFormatRefused {
1267                entity_type,
1268                entity_id,
1269                violation,
1270            } => {
1271                let mut v = serde_json::to_value(violation).unwrap_or_default();
1272                if let Some(obj) = v.as_object_mut() {
1273                    obj.insert("entity_type".into(), serde_json::json!(entity_type));
1274                    obj.insert("entity_id".into(), serde_json::json!(entity_id));
1275                }
1276                v
1277            }
1278            EngineError::RepairNotNeeded { id, recovery } => {
1279                serde_json::json!({ "id": id, "recovery": recovery })
1280            }
1281            // Same shape the full MCP singleton envelope ships for
1282            // UNKNOWN_ENTITY_TYPE — keeps the centralised helper (and
1283            // every consumer: batch envelopes, the integrity linter)
1284            // aligned with the wire payload agents already decode.
1285            EngineError::UnknownType {
1286                name,
1287                schema_ref,
1288                declared,
1289                suggestion,
1290            } => serde_json::json!({
1291                "name": name,
1292                "schema_ref": schema_ref,
1293                "declared": declared,
1294                "suggestion": suggestion,
1295            }),
1296            EngineError::HashMismatch {
1297                id,
1298                current,
1299                is_stub,
1300            } => serde_json::json!({
1301                "id": id,
1302                "current": current,
1303                "is_stub": is_stub,
1304            }),
1305            EngineError::HasIncomingRefs { id, referrers } => {
1306                let referrers_json: Vec<_> = referrers
1307                    .iter()
1308                    .map(|r| {
1309                        serde_json::json!({
1310                            "from_id": r.from_id,
1311                            "rel_types": r.rel_types,
1312                            "mem": r.mem,
1313                        })
1314                    })
1315                    .collect();
1316                serde_json::json!({ "id": id, "referrers": referrers_json })
1317            }
1318            EngineError::MemHasIncomingRefs { mem, referrers } => {
1319                let referrers_json: Vec<_> = referrers
1320                    .iter()
1321                    .map(|r| {
1322                        serde_json::json!({
1323                            "from_id": r.from_id,
1324                            "rel_types": r.rel_types,
1325                            "mem": r.mem,
1326                        })
1327                    })
1328                    .collect();
1329                serde_json::json!({ "mem": mem, "referrers": referrers_json })
1330            }
1331            EngineError::WikiLinkWithoutRelation { from_id, missing } => serde_json::json!({
1332                "from_id": from_id,
1333                "missing": missing,
1334            }),
1335            EngineError::RelationHasBodyLinks {
1336                from_id,
1337                to_id,
1338                rel_type,
1339                body_links,
1340            } => {
1341                serde_json::json!({
1342                    "from_id": from_id,
1343                    "to_id": to_id,
1344                    "rel_type": rel_type,
1345                    "body_links": body_links,
1346                })
1347            }
1348            EngineError::InvalidEntityId { id, reason } => {
1349                serde_json::json!({ "id": id, "reason": reason })
1350            }
1351            EngineError::InvalidWikiLinkTarget {
1352                raw,
1353                suggested,
1354                section,
1355                link_source,
1356                reason,
1357            } => {
1358                // Surface
1359                // the slug-form retry under `proposed_slug`, mirroring the
1360                // title gate's `INVALID_TITLE` recovery key, so an agent
1361                // that wrote `[[Idempotency]]` finds `idempotency` under
1362                // the same field it already knows. `suggested` is the
1363                // general hint and is sometimes a colon-form
1364                // (`mem:slug`) for the ambiguous-grammar case — only
1365                // promote it to `proposed_slug` when it's a bare slug.
1366                let proposed_slug = suggested
1367                    .as_ref()
1368                    .filter(|s| !s.contains(':') && !s.contains("--"));
1369                serde_json::json!({
1370                    "raw": raw,
1371                    "suggested": suggested,
1372                    "proposed_slug": proposed_slug,
1373                    "section": section,
1374                    "source": link_source,
1375                    "reason": reason,
1376                })
1377            }
1378            EngineError::InvalidWikiLinkMem {
1379                raw,
1380                section,
1381                reason,
1382            } => {
1383                serde_json::json!({ "raw": raw, "section": section, "reason": reason })
1384            }
1385            EngineError::ConflictingSectionModes { section, modes } => {
1386                serde_json::json!({ "section": section, "modes": modes })
1387            }
1388            EngineError::SetAndUnsetConflict { keys } => serde_json::json!({ "keys": keys }),
1389            EngineError::RequiredFieldUnset {
1390                field,
1391                entity_type,
1392                field_description,
1393                enum_values,
1394                type_write_rules,
1395                // `on_create` is a prose-dispatch
1396                // discriminator only; agents branch on the typed
1397                // `REQUIRED_FIELD_UNSET` code, not on this field.
1398                on_create: _,
1399                missing,
1400            } => {
1401                // `details.missing[]` carries every required-no-
1402                // default field unset on the create path so an
1403                // agent fixes the whole set in one retry. Each
1404                // entry echoes the type-level `write_rules` for
1405                // self-containment. Empty on the unset path.
1406                let missing_json: Vec<_> = missing
1407                    .iter()
1408                    .map(|m| {
1409                        serde_json::json!({
1410                            "field": m.key,
1411                            "description": m.description,
1412                            "enum_values": m.enum_values,
1413                            "write_rules": type_write_rules,
1414                        })
1415                    })
1416                    .collect();
1417                serde_json::json!({
1418                    "field": field,
1419                    "entity_type": entity_type,
1420                    "field_description": field_description,
1421                    "enum_values": enum_values,
1422                    "type_write_rules": type_write_rules,
1423                    "missing": missing_json,
1424                })
1425            }
1426            EngineError::MissingRequiredSection {
1427                entity_type,
1428                missing_count,
1429                sections,
1430                type_guidance,
1431            } => {
1432                let sections_json: Vec<_> = sections
1433                    .iter()
1434                    .map(|s| {
1435                        serde_json::json!({
1436                            "entity_type": s.entity_type,
1437                            "key": s.key,
1438                            "heading": s.heading,
1439                            "write_rules": s.write_rules,
1440                        })
1441                    })
1442                    .collect();
1443                serde_json::json!({
1444                    "entity_type": entity_type,
1445                    "missing_count": missing_count,
1446                    "sections": sections_json,
1447                    "type_guidance": type_guidance,
1448                })
1449            }
1450            EngineError::PatchSectionEmpty { section } => serde_json::json!({ "section": section }),
1451            EngineError::PatchOldNotFound {
1452                section,
1453                current_content,
1454                truncated,
1455            } => {
1456                serde_json::json!({
1457                    "section": section,
1458                    "current_content": current_content,
1459                    "truncated": truncated,
1460                })
1461            }
1462            EngineError::RelationshipCycle {
1463                rel_type,
1464                from,
1465                to,
1466                existing_path,
1467                path_truncated,
1468            } => {
1469                let path_json: Vec<_> = existing_path.iter().map(|id| id.to_string()).collect();
1470                serde_json::json!({
1471                    "rel_type": rel_type,
1472                    "from": from.to_string(),
1473                    "to": to.to_string(),
1474                    "existing_path": path_json,
1475                    "path_truncated": path_truncated,
1476                })
1477            }
1478            EngineError::CrossMemLinkNotAllowed { from_mem, to_mem } => {
1479                serde_json::json!({ "from_mem": from_mem, "to_mem": to_mem })
1480            }
1481            EngineError::EmptyUpdate { id } => {
1482                serde_json::json!({
1483                    "id": id,
1484                    "recognised_keys": [
1485                        "sections", "append_sections", "patch_sections",
1486                        "metadata", "metadata_unset", "declare_relations", "relations_unset",
1487                    ],
1488                })
1489            }
1490            EngineError::RenameBlockedByCrossMemPolicy {
1491                from_mem,
1492                blocked_referrers,
1493            } => {
1494                let entries: Vec<_> = blocked_referrers
1495                    .iter()
1496                    .map(|r| {
1497                        serde_json::json!({
1498                            "from_mem": r.from_mem,
1499                            "to_mem": r.to_mem,
1500                            "count": r.count,
1501                        })
1502                    })
1503                    .collect();
1504                serde_json::json!({
1505                    "from_mem": from_mem,
1506                    "blocked_referrers": entries,
1507                })
1508            }
1509            EngineError::CrossMemTargetNotFound {
1510                target_id,
1511                target_mem,
1512            } => {
1513                serde_json::json!({ "target_id": target_id, "target_mem": target_mem })
1514            }
1515            EngineError::Validation(v) => v.details(),
1516            EngineError::MissingRequiredDescription {
1517                rel_type,
1518                from_id,
1519                to_id,
1520            } => {
1521                serde_json::json!({
1522                    "rel_type": rel_type,
1523                    "from_id": from_id,
1524                    "to_id": to_id,
1525                })
1526            }
1527            EngineError::DescriptionNotPermitted {
1528                rel_type,
1529                from_id,
1530                to_id,
1531            } => {
1532                serde_json::json!({
1533                    "rel_type": rel_type,
1534                    "from_id": from_id,
1535                    "to_id": to_id,
1536                })
1537            }
1538            EngineError::RelationManualAuthoringForbidden {
1539                rel_type,
1540                from_id,
1541                to_id,
1542                guidance,
1543            } => serde_json::json!({
1544                "rel_type": rel_type,
1545                "from_id": from_id,
1546                "to_id": to_id,
1547                "guidance": guidance,
1548            }),
1549            EngineError::MarkdownExportUnsupportedBackend {
1550                mem,
1551                active_backend,
1552                supported_backends,
1553            } => serde_json::json!({
1554                "mem": mem,
1555                "active_backend": active_backend,
1556                "supported_backends": supported_backends,
1557            }),
1558            EngineError::ReviewMarkNotSet { mem } => serde_json::json!({ "mem": mem }),
1559            EngineError::InvalidChangesCursor { mem, since } => serde_json::json!({
1560                "mem": mem,
1561                "since": since,
1562            }),
1563            EngineError::SchemaNotFound {
1564                mem,
1565                pin,
1566                sources,
1567                install_hint,
1568            } => {
1569                let mut details = serde_json::json!({
1570                    "mem": mem,
1571                    "pin": pin,
1572                    "sources": sources,
1573                });
1574                if let Some(path) = install_hint {
1575                    details["install_hint"] = serde_json::json!({
1576                        "authoring_package": path,
1577                        "command": format!("memstead schema install {path}"),
1578                    });
1579                }
1580                details
1581            }
1582            EngineError::SchemaPackageInvalid {
1583                name,
1584                version,
1585                message,
1586            } => serde_json::json!({
1587                "schema": format!("{name}@{version}"),
1588                "error": message,
1589            }),
1590            EngineError::InvalidAnchor(e) => {
1591                serde_json::Value::Object(e.detail().into_iter().collect::<serde_json::Map<_, _>>())
1592            }
1593            _ => serde_json::Value::Object(serde_json::Map::new()),
1594        }
1595    }
1596
1597    /// Render rich, fully-inlined recovery prose for the agent-visible
1598    /// text channel.
1599    ///
1600    /// Warnings
1601    /// already render their structured payload inline via
1602    /// `WarningHint::Display`; pre-fix errors with rich payloads
1603    /// collapsed to `Display` plus `format_inline_list_overflow`'s
1604    /// "+N more — see details.X" pointer pointing at a structured
1605    /// channel the agent's MCP client doesn't surface to the model.
1606    /// This method gives errors the same prose-rich rendering warnings
1607    /// have, so `result.content[0].text` is self-recoverable.
1608    ///
1609    /// Variants whose `Display` already inlines every recovery field
1610    /// (no truncation, no "see details" pointer) inherit the default
1611    /// trait impl — they just `to_string()`. Override only the
1612    /// variants that need richer rendering than `Display` provides.
1613    ///
1614    /// The structured `details()` channel is unchanged; consumers
1615    /// branching on `code` continue to receive the typed shape. The
1616    /// `Display` impl stays terse for logs, tracing, panic messages,
1617    /// and other non-agent consumers.
1618    pub fn prose_render(&self) -> String {
1619        match self {
1620            // The echoed conforming `example` is the highest-leverage
1621            // part of a format refusal — inline it on the text channel
1622            // too, not only under `details.example`.
1623            EngineError::SectionFormatRefused { violation, .. } => {
1624                let base = self.to_string();
1625                match violation.example() {
1626                    Some(example) => {
1627                        format!("{base}\nA conforming example:\n{}", example.trim_end())
1628                    }
1629                    None => base,
1630                }
1631            }
1632            EngineError::HasIncomingRefs { id, referrers } => {
1633                let inline = render_referrers_inline(referrers);
1634                format!(
1635                    "entity {id} has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
1636                    n = referrers.len(),
1637                )
1638            }
1639            EngineError::MemHasIncomingRefs { mem, referrers } => {
1640                let inline = render_referrers_inline(referrers);
1641                format!(
1642                    "mem `{mem}` has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
1643                    n = referrers.len(),
1644                )
1645            }
1646            EngineError::WikiLinkWithoutRelation { from_id, missing } => {
1647                let inline = missing
1648                    .iter()
1649                    .map(|m| m.to_string())
1650                    .collect::<Vec<_>>()
1651                    .join(", ");
1652                format!(
1653                    "post-mutation body of {from_id} has {n} wiki-link(s) without a backing relation ({inline}) — declare the relation(s) via memstead_relate first (REFERENCES or a more specific rel-type), then retry",
1654                    n = missing.len(),
1655                )
1656            }
1657            EngineError::RelationHasBodyLinks {
1658                from_id,
1659                to_id,
1660                rel_type,
1661                body_links,
1662            } => {
1663                let inline = body_links.join(", ");
1664                format!(
1665                    "cannot remove {rel_type} {from_id} → {to_id}: source body still contains wiki-link(s) to the target in section(s) {inline} — drop them via memstead_update before removing the relation"
1666                )
1667            }
1668            EngineError::RelationshipCycle {
1669                rel_type,
1670                from,
1671                to,
1672                existing_path,
1673                path_truncated,
1674            } => {
1675                let path_inline = if existing_path.is_empty() {
1676                    String::from("(unavailable)")
1677                } else {
1678                    existing_path
1679                        .iter()
1680                        .map(|id| id.to_string())
1681                        .collect::<Vec<_>>()
1682                        .join(" → ")
1683                };
1684                let trunc = if *path_truncated {
1685                    " (path truncated)"
1686                } else {
1687                    ""
1688                };
1689                format!(
1690                    "creating edge {rel_type} from '{from}' to '{to}' would close a cycle in the {rel_type} subgraph — existing path: {path_inline}{trunc}; remove an edge along this path to break the cycle, then retry"
1691                )
1692            }
1693            EngineError::RequiredFieldUnset {
1694                field,
1695                entity_type,
1696                field_description,
1697                enum_values,
1698                type_write_rules,
1699                on_create,
1700                missing,
1701            } => {
1702                let desc_clause = field_description
1703                    .as_deref()
1704                    .map(|d| format!(" Field purpose: {d}."))
1705                    .unwrap_or_default();
1706                let enum_clause = if enum_values.is_empty() {
1707                    String::new()
1708                } else {
1709                    format!(" Allowed values: {}.", enum_values.join(", "))
1710                };
1711                let rules_clause = if type_write_rules.is_empty() {
1712                    String::new()
1713                } else {
1714                    format!(" Type-level write_rules: {}.", type_write_rules.join("; "))
1715                };
1716                // Path-aware wording — create
1717                // path says "not provided"; update path says "cannot
1718                // unset". Display impl shares the same dispatch via
1719                // `_required_field_unset_msg`.
1720                let lead = if *on_create {
1721                    format!(
1722                        "required metadata field '{field}' not provided — type '{entity_type}' declares the field as required and has no default for it"
1723                    )
1724                } else {
1725                    format!("cannot unset required field '{field}' for type '{entity_type}'")
1726                };
1727                // Multi-field accumulator. On the create path,
1728                // append a tail-list naming every other unset
1729                // required field so the agent's one-shot retry
1730                // covers all of them. The unset path's `missing`
1731                // is empty (or singleton), so the clause is empty
1732                // there.
1733                let tail_clause = if missing.len() > 1 {
1734                    let others: Vec<&str> =
1735                        missing.iter().skip(1).map(|m| m.key.as_str()).collect();
1736                    format!(" Also unset (declaration order): {}.", others.join(", "))
1737                } else {
1738                    String::new()
1739                };
1740                format!("{lead}.{desc_clause}{enum_clause}{rules_clause}{tail_clause}")
1741            }
1742            EngineError::MissingRequiredSection {
1743                entity_type,
1744                missing_count,
1745                sections,
1746                type_guidance,
1747            } => {
1748                let mut out = format!(
1749                    "missing {missing_count} required section(s) for type '{entity_type}':"
1750                );
1751                for s in sections {
1752                    let rules = if s.write_rules.is_empty() {
1753                        String::new()
1754                    } else {
1755                        format!(" — write_rules: {}", s.write_rules.join("; "))
1756                    };
1757                    out.push_str(&format!("\n  - '{}' ({}){rules}", s.key, s.heading));
1758                }
1759                if !type_guidance.is_empty() {
1760                    out.push_str("\nType guidance:");
1761                    for (etype, rules) in type_guidance {
1762                        if rules.is_empty() {
1763                            continue;
1764                        }
1765                        out.push_str(&format!("\n  - {etype}: {}", rules.join("; ")));
1766                    }
1767                }
1768                out
1769            }
1770            EngineError::Validation(v) => v.prose_render(),
1771            // Variants whose `Display` already inlines every recovery
1772            // field — title invariants, hash mismatch (already explains
1773            // the stub case), unknown mem / type (already prints
1774            // declared list verbatim), cross-mem gates, stubs,
1775            // patch errors, etc. — fall back to `Display`. Logs and
1776            // tracing consumers see the same string.
1777            _ => self.to_string(),
1778        }
1779    }
1780}
1781
1782/// Inline-render every [`ReferrerInfo`] without the truncation suffix
1783/// `format_inline_list_overflow` applies. Used by
1784/// [`EngineError::prose_render`]'s `HasIncomingRefs` /
1785/// `MemHasIncomingRefs` arms — the agent text channel inlines the
1786/// full list so recovery doesn't depend on the structured channel.
1787fn render_referrers_inline(referrers: &[ReferrerInfo]) -> String {
1788    referrers
1789        .iter()
1790        .map(|r| r.to_string())
1791        .collect::<Vec<_>>()
1792        .join(", ")
1793}
1794
1795/// Format the `RequiredFieldUnset` message. The same typed code
1796/// fires from two semantically-distinct call sites:
1797///
1798/// * The create path constructs the variant when the caller didn't
1799///   supply a required metadata field. The pre-fix message ("cannot
1800///   unset required field …") was misleading because the field was
1801///   never set in the first place — `on_create: true` flips the
1802///   wording to "required metadata field … not provided".
1803/// * The update path constructs the variant when the caller passed
1804///   `metadata_unset: ["field"]` against a required field. The
1805///   pre-fix wording is correct for this path — `on_create: false`
1806///   keeps it.
1807///
1808/// Both paths share recovery (provide the field); the typed code
1809/// stays `REQUIRED_FIELD_UNSET` for code-key branching consumers.
1810fn _required_field_unset_msg(field: &str, entity_type: &str, on_create: bool) -> String {
1811    if on_create {
1812        format!(
1813            "required metadata field '{field}' not provided — type '{entity_type}' declares the field as required and has no default for it"
1814        )
1815    } else {
1816        format!("cannot unset required field '{field}' for type '{entity_type}'")
1817    }
1818}
1819
1820/// Format the `HashMismatch` message. Stub-shaped entities have no
1821/// `content_hash` to compare against; rendering the empty `current:`
1822/// paren the way pre-fix code did misdirects an agent toward
1823/// hash-recovery via `memstead_entity` (which returns the same empty
1824/// hash). Surface the actual corrective action — pass
1825/// `expected_hash: ""` — instead.
1826/// Render the `SCHEMA_NOT_FOUND` message with its source-trail
1827/// summary. The trail says exactly which sources were searched and
1828/// what each held — never more (a source absent from `sources` is not
1829/// claimed searched). A right-name/wrong-version failure and a
1830/// never-installed failure are distinguishable from this sentence
1831/// alone; the structured `details.sources` stays the richer channel.
1832/// Empty `sources` (internal lookup miss) keeps the bare legacy
1833/// sentence — there was no source search to summarise.
1834fn schema_not_found_message(
1835    mem: &str,
1836    pin: &str,
1837    sources: &[SchemaSourceDiagnostic],
1838    install_hint: &Option<String>,
1839) -> String {
1840    let mut msg = format!("mem {mem}: schema pin {pin:?} did not resolve in any schema source");
1841    if sources.is_empty() {
1842        return msg;
1843    }
1844    let name = pin.split('@').next().unwrap_or(pin);
1845    let trail: Vec<String> = sources
1846        .iter()
1847        .map(|s| {
1848            if let Some(status) = s.status {
1849                format!("{} ({status})", s.source)
1850            } else if s.versions_found.is_empty() {
1851                format!("{} (nothing for {name:?})", s.source)
1852            } else {
1853                format!("{} (holds {})", s.source, s.versions_found.join(", "))
1854            }
1855        })
1856        .collect();
1857    msg.push_str(&format!(" — searched {}", trail.join(", ")));
1858    if sources.iter().any(|s| !s.versions_found.is_empty()) {
1859        // Right name, wrong version. The honest hint is version
1860        // repair, not silence: the final clause is the concrete repin
1861        // command against the newest version a source actually holds.
1862        let best = sources
1863            .iter()
1864            .flat_map(|s| &s.versions_found)
1865            .filter_map(|v| semver::Version::parse(v).ok())
1866            .max();
1867        msg.push_str(&format!(
1868            "; the name {name:?} exists at the versions listed — the pinned version is wrong, \
1869             or the pinned version was never installed"
1870        ));
1871        if let Some(best) = best {
1872            msg.push_str(&format!(
1873                "; repin to an installed version: run: memstead mem set-schema {mem} {name}@{best}"
1874            ));
1875        }
1876    } else if let Some(path) = install_hint {
1877        msg.push_str(&format!(
1878            "; an authoring package named {name:?} exists at {path:?} but is not installed — \
1879             run: memstead schema install {path}"
1880        ));
1881    } else {
1882        // Name unknown everywhere and no authoring package in sight —
1883        // the repair path is still the install path, stated without a
1884        // concrete package location because none exists to name.
1885        msg.push_str(&format!(
1886            "; no source holds any version of {name:?} — author or obtain the schema package, \
1887             then run: memstead schema install <package-dir>"
1888        ));
1889    }
1890    msg
1891}
1892
1893impl EngineError {
1894    /// Attach the schema-install hint to a `SchemaNotFound` where a
1895    /// workspace root is known: probe the root's immediate
1896    /// subdirectories for an authoring schema package (a directory the
1897    /// schema loader accepts) whose manifest name matches the pin's
1898    /// name, and record its path when NO resolution source holds any
1899    /// version of that name. Any other error variant — and any
1900    /// `SchemaNotFound` where the name IS installed at some version
1901    /// (a version mismatch is a different fix), where `sources` is
1902    /// empty (internal miss, no source search happened), or where no
1903    /// candidate package exists — passes through unchanged. Read-only:
1904    /// the probe never writes, installs, or seals anything.
1905    pub fn with_schema_install_probe(self, workspace_root: Option<&std::path::Path>) -> Self {
1906        let EngineError::SchemaNotFound {
1907            mem,
1908            pin,
1909            sources,
1910            install_hint,
1911        } = self
1912        else {
1913            return self;
1914        };
1915        let hint = if install_hint.is_some() {
1916            install_hint
1917        } else if sources.is_empty() || sources.iter().any(|s| !s.versions_found.is_empty()) {
1918            None
1919        } else {
1920            let name = pin.split('@').next().unwrap_or(&pin).to_string();
1921            workspace_root.and_then(|root| probe_authoring_package(root, &name))
1922        };
1923        EngineError::SchemaNotFound {
1924            mem,
1925            pin,
1926            sources,
1927            install_hint: hint,
1928        }
1929    }
1930}
1931
1932/// Scan `root`'s immediate subdirectories for a loadable schema
1933/// package whose manifest name is `name`. Hidden directories and the
1934/// workspace's own storage (`mem-repo`, `.memstead`) are skipped. The
1935/// full loader runs (error path only, so the cost is acceptable) — a
1936/// directory that merely LOOKS like a package but fails validation
1937/// produces no hint, because `memstead schema install` would refuse it
1938/// anyway.
1939fn probe_authoring_package(root: &std::path::Path, name: &str) -> Option<String> {
1940    let entries = std::fs::read_dir(root).ok()?;
1941    for entry in entries.flatten() {
1942        let path = entry.path();
1943        if !path.is_dir() {
1944            continue;
1945        }
1946        let dir_name = entry.file_name();
1947        let dir_name = dir_name.to_string_lossy();
1948        if dir_name.starts_with('.') || dir_name == "mem-repo" {
1949            continue;
1950        }
1951        if !path.join("schema.yaml").is_file() {
1952            continue;
1953        }
1954        if let Ok(schema) = memstead_schema::load_schema_from_dir(&path) {
1955            let (loaded_name, _) = schema.id();
1956            if loaded_name == name {
1957                return Some(path.display().to_string());
1958            }
1959        }
1960    }
1961    None
1962}
1963
1964fn _hash_mismatch_msg(id: &str, current: &str, is_stub: bool) -> String {
1965    if is_stub {
1966        format!(
1967            "hash mismatch for {id} — entity is a stub (no content_hash); pass expected_hash: \"\" to operate on stubs"
1968        )
1969    } else {
1970        format!("hash mismatch for {id} — entity was modified concurrently (current: {current})")
1971    }
1972}
1973
1974/// Errors surfaced by [`Engine::from_workspace_root`] (lean) and its
1975/// full counterpart (`memstead_git_branch::engine_from_workspace_root`).
1976///
1977/// The boot path layers three error sources: layout detection,
1978/// workspace-store load failures, per-mount backend instantiation
1979/// (folder + archive vs git-branch), and engine construction
1980/// (duplicate-mem checks). `#[from]` lifts the lower-layer types so
1981/// callers branch on a single error envelope.
1982// Variants lift lower-layer error types verbatim via `#[from]`, so the enum is
1983// as wide as its widest member. Boot errors are constructed at most once per
1984// process; boxing to equalise them would buy nothing.
1985#[allow(clippy::large_enum_variant)]
1986#[derive(Debug, thiserror::Error)]
1987pub enum BootError {
1988    /// `detect_layout` returned [`crate::Layout::Empty`] — workspace
1989    /// root has no recognised layout marker. Operator runs
1990    /// `memstead mem-repo init` rather than booting against an empty
1991    /// directory.
1992    #[error("workspace at {0} is not initialised — run `memstead mem-repo init` first")]
1993    NotInitialised(PathBuf),
1994    /// Underlying [`crate::WorkspaceStoreAdapter`] load failed
1995    /// (missing config file, parse error, format-mismatch).
1996    #[error(transparent)]
1997    Store(#[from] crate::workspace_store::StoreError),
1998    /// Per-mount backend instantiation failed. Today: a mount
1999    /// declared `MountStorage::GitBranch` while the lean boot path
2000    /// only knows folder + archive.
2001    #[error(transparent)]
2002    Instantiate(#[from] crate::workspace_store::InstantiateError),
2003    /// Engine construction failed (duplicate mem names, etc.).
2004    #[error(transparent)]
2005    Engine(#[from] EngineError),
2006}
2007
2008impl BootError {
2009    /// Stable, surface-independent error code token (UPPER_SNAKE, per
2010    /// the [`EngineError::code`] convention). Every boot failure class
2011    /// resolves to a typed code — `INTERNAL` is not producible from
2012    /// this seam. The wrapped layers each own their vocabulary:
2013    /// store-load failures delegate to
2014    /// [`crate::workspace_store::StoreError::code`], backend
2015    /// instantiation to
2016    /// [`crate::workspace_store::InstantiateError::code`], engine
2017    /// construction to [`EngineError::code`].
2018    pub fn code(&self) -> &'static str {
2019        match self {
2020            // Same token the CLI's workspace walk uses — "no
2021            // workspace here" is one condition wherever detected.
2022            BootError::NotInitialised(_) => "WORKSPACE_NOT_INITIALISED",
2023            BootError::Store(e) => e.code(),
2024            BootError::Instantiate(e) => e.code(),
2025            BootError::Engine(e) => e.code(),
2026        }
2027    }
2028
2029    /// Structured recovery payload for the boot failure, surfacing
2030    /// under `error.details` on `--json` envelopes. Engine-layer
2031    /// failures reuse [`EngineError::details`] (so e.g. a boot-time
2032    /// `SCHEMA_NOT_FOUND` ships the same `details.sources` trail the
2033    /// per-verb surfaces ship); the other layers name the offending
2034    /// path.
2035    pub fn details(&self) -> serde_json::Value {
2036        use crate::workspace_store::StoreError;
2037        match self {
2038            BootError::NotInitialised(path) => {
2039                serde_json::json!({
2040                    "path": path.display().to_string(),
2041                    "hint": { "recovery_command": "memstead mem-repo init" },
2042                })
2043            }
2044            BootError::Store(e) => match e {
2045                StoreError::NotInitialised { path }
2046                | StoreError::Io { path, .. }
2047                | StoreError::Parse { path, .. }
2048                | StoreError::FormatMismatch { path, .. }
2049                | StoreError::LegacyLayout { path, .. }
2050                | StoreError::UnknownBindingVersion { path, .. } => {
2051                    serde_json::json!({ "path": path.display().to_string() })
2052                }
2053                StoreError::LegacyProjectionStore { path } => serde_json::json!({
2054                    "path": path.display().to_string(),
2055                    "hint": { "recovery_command": "memstead projection migrate" },
2056                }),
2057                StoreError::Other(_) => serde_json::json!({}),
2058            },
2059            BootError::Instantiate(
2060                crate::workspace_store::InstantiateError::GitBranchRequiresMemRepoFeature { mem },
2061            ) => serde_json::json!({ "mem": mem }),
2062            BootError::Engine(e) => e.details(),
2063        }
2064    }
2065
2066    /// The one boot-failure message every surface prints verbatim
2067    /// (CLI stderr / `--json`, MCP boot diagnostics), so the same
2068    /// broken workspace reads identically wherever it refuses. The
2069    /// leaf error's own message carries the repair command (or states
2070    /// plainly that none exists).
2071    pub fn surface_message(&self, workspace_root: &std::path::Path) -> String {
2072        format!("init engine at {}: {self}", workspace_root.display())
2073    }
2074}
2075
2076#[cfg(test)]
2077mod plan05_subsystem_tests {
2078    use super::*;
2079
2080    /// A title-case body wiki-link refusal carries the
2081    /// slug-form retry under `proposed_slug` (mirroring `INVALID_TITLE`),
2082    /// so an agent that wrote `[[Idempotency]]` finds `idempotency` under
2083    /// the key it already knows.
2084    #[test]
2085    fn invalid_wiki_link_details_carry_proposed_slug_for_title_case() {
2086        let err = EngineError::InvalidWikiLinkTarget {
2087            raw: "Idempotency".to_string(),
2088            suggested: Some("idempotency".to_string()),
2089            section: "purpose".to_string(),
2090            link_source: "body_link".to_string(),
2091            reason: "slugs must be lowercase".to_string(),
2092        };
2093        let d = err.details();
2094        assert_eq!(d["proposed_slug"], "idempotency");
2095        assert_eq!(d["suggested"], "idempotency");
2096    }
2097
2098    /// `SCHEMA_NOT_FOUND` carries the fixed-order resolution
2099    /// diagnostics under `details.sources`: a right-name/wrong-version
2100    /// pin shows the built-in's available versions with
2101    /// `pinned_version_match = false`, and `remote` is the reserved
2102    /// `not_configured` slot. This is the agent-visible payload that
2103    /// tells the caller the name resolves but the version does not.
2104    #[test]
2105    fn schema_not_found_details_carry_fixed_order_source_diagnostics() {
2106        let requested: semver::Version = "99.0.0".parse().unwrap();
2107        let sources = SchemaSourceDiagnostic::for_failed_pin("default", &requested, &[]);
2108        let err = EngineError::SchemaNotFound {
2109            mem: "specs".to_string(),
2110            pin: "default@99.0.0".to_string(),
2111            sources,
2112            install_hint: None,
2113        };
2114        assert_eq!(err.code(), "SCHEMA_NOT_FOUND");
2115        let d = err.details();
2116        assert_eq!(d["mem"], "specs");
2117        assert_eq!(d["pin"], "default@99.0.0");
2118        let src = d["sources"].as_array().expect("sources is an array");
2119        let labels: Vec<&str> = src.iter().map(|s| s["source"].as_str().unwrap()).collect();
2120        assert_eq!(labels, ["local_storage", "builtin", "remote"]);
2121        // The `default` builtin exists at 1.0.0 — right name, wrong
2122        // version: builtin enumerates it but the pin does not match.
2123        let builtin = &src[1];
2124        assert!(
2125            builtin["versions_found"]
2126                .as_array()
2127                .unwrap()
2128                .iter()
2129                .any(|v| v == "1.0.0"),
2130            "builtin must enumerate default@1.0.0, got {builtin:?}",
2131        );
2132        assert_eq!(builtin["pinned_version_match"], false);
2133        // No local storage was consulted (empty `consulted` slice).
2134        assert_eq!(src[0]["versions_found"].as_array().unwrap().len(), 0);
2135        // Remote is the reserved, unenumerated slot.
2136        assert_eq!(src[2]["status"], "not_configured");
2137        assert!(
2138            src[2].get("versions_found").is_some(),
2139            "remote still ships an (empty) versions_found list",
2140        );
2141    }
2142
2143    /// The MESSAGE (not just `details`) summarises the source trail,
2144    /// and a right-name/wrong-version failure is distinguishable from
2145    /// a never-installed one without opening `details`. The message
2146    /// names exactly the sources in `sources` — never one that was
2147    /// not searched — and the empty-sources internal miss keeps the
2148    /// bare legacy sentence.
2149    #[test]
2150    fn schema_not_found_message_summarises_trail_and_distinguishes_wrong_version() {
2151        // Wrong version: the builtin catalogue holds `default@1.0.0`,
2152        // the pin asks for 99.0.0.
2153        let requested: semver::Version = "99.0.0".parse().unwrap();
2154        let wrong_version = EngineError::SchemaNotFound {
2155            mem: "specs".to_string(),
2156            pin: "default@99.0.0".to_string(),
2157            sources: SchemaSourceDiagnostic::for_failed_pin("default", &requested, &[]),
2158            install_hint: None,
2159        };
2160        let msg = wrong_version.to_string();
2161        assert!(msg.contains("searched local_storage"), "got: {msg}");
2162        assert!(msg.contains("builtin (holds"), "got: {msg}");
2163        assert!(msg.contains("remote (not_configured)"), "got: {msg}");
2164        assert!(
2165            msg.contains("the pinned version is wrong"),
2166            "wrong-version case must be named in the message: {msg}"
2167        );
2168        assert!(
2169            msg.contains("memstead mem set-schema specs default@1.3.0"),
2170            "wrong-version case ends in the concrete repin command: {msg}"
2171        );
2172
2173        // Never installed: no source holds any version of the name.
2174        let never: semver::Version = "1.0.0".parse().unwrap();
2175        let never_installed = EngineError::SchemaNotFound {
2176            mem: "specs".to_string(),
2177            pin: "no-such-schema@1.0.0".to_string(),
2178            sources: SchemaSourceDiagnostic::for_failed_pin("no-such-schema", &never, &[]),
2179            install_hint: None,
2180        };
2181        let msg2 = never_installed.to_string();
2182        assert!(
2183            msg2.contains("nothing for \"no-such-schema\""),
2184            "never-installed case names the empty sources: {msg2}"
2185        );
2186        assert!(
2187            !msg2.contains("the pinned version is wrong"),
2188            "never-installed must NOT claim a version mismatch: {msg2}"
2189        );
2190        assert!(
2191            msg2.contains("memstead schema install <package-dir>"),
2192            "never-installed (no probe) still names the install path: {msg2}"
2193        );
2194        assert_ne!(msg, msg2, "the two failures are distinguishable");
2195
2196        // Internal lookup miss (empty sources): bare legacy sentence,
2197        // no trail is claimed.
2198        let internal = EngineError::SchemaNotFound {
2199            mem: "specs".to_string(),
2200            pin: "x@1.0.0".to_string(),
2201            sources: Vec::new(),
2202            install_hint: None,
2203        };
2204        assert_eq!(
2205            internal.to_string(),
2206            "mem specs: schema pin \"x@1.0.0\" did not resolve in any schema source",
2207        );
2208    }
2209
2210    /// The install-hint probe attaches the authoring-package pointer
2211    /// exactly when a loadable package with the pin's name sits in the
2212    /// workspace root while NO source holds any version of the name —
2213    /// and stays silent for a version mismatch (installed at another
2214    /// version), for an absent package, and for a non-`SchemaNotFound`
2215    /// error.
2216    #[test]
2217    fn schema_install_probe_hints_only_for_uninstalled_authoring_package() {
2218        // Workspace root carrying the memstead-schema `examples/minimal`
2219        // package (name `recipe`) as an authoring folder.
2220        let tmp = tempfile::TempDir::new().unwrap();
2221        let src_pkg = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2222            .join("../memstead-schema/examples/minimal");
2223        let dst = tmp.path().join("recipe");
2224        std::fs::create_dir_all(dst.join("types")).unwrap();
2225        std::fs::copy(src_pkg.join("schema.yaml"), dst.join("schema.yaml")).unwrap();
2226        for entry in std::fs::read_dir(src_pkg.join("types")).unwrap().flatten() {
2227            std::fs::copy(entry.path(), dst.join("types").join(entry.file_name())).unwrap();
2228        }
2229
2230        let requested: semver::Version = "0.1.0".parse().unwrap();
2231        let not_found = || EngineError::SchemaNotFound {
2232            mem: "specs".to_string(),
2233            pin: "recipe@0.1.0".to_string(),
2234            sources: SchemaSourceDiagnostic::for_failed_pin("recipe", &requested, &[]),
2235            install_hint: None,
2236        };
2237
2238        // Uninstalled + authored → hint attaches, message + details
2239        // point at `memstead schema install`.
2240        let hinted = not_found().with_schema_install_probe(Some(tmp.path()));
2241        let msg = hinted.to_string();
2242        assert!(
2243            msg.contains("memstead schema install"),
2244            "hint must name the install command: {msg}"
2245        );
2246        assert!(msg.contains("recipe"), "hint names the package: {msg}");
2247        let d = hinted.details();
2248        assert!(
2249            d["install_hint"]["command"]
2250                .as_str()
2251                .unwrap()
2252                .starts_with("memstead schema install"),
2253            "details carry the hint: {d}"
2254        );
2255
2256        // No workspace root → no concrete package hint; the message
2257        // falls back to the generic install path.
2258        let no_root = not_found().with_schema_install_probe(None);
2259        let no_root_msg = no_root.to_string();
2260        assert!(
2261            no_root_msg.contains("memstead schema install <package-dir>"),
2262            "generic install path without a probe hit: {no_root_msg}"
2263        );
2264        assert!(
2265            !no_root_msg.contains(&tmp.path().display().to_string()),
2266            "no concrete package path without a probe hit: {no_root_msg}"
2267        );
2268
2269        // No such authoring package → same generic fallback, no
2270        // concrete path.
2271        let other_tmp = tempfile::TempDir::new().unwrap();
2272        let absent = not_found().with_schema_install_probe(Some(other_tmp.path()));
2273        let absent_msg = absent.to_string();
2274        assert!(
2275            absent_msg.contains("memstead schema install <package-dir>"),
2276            "generic install path when no package exists: {absent_msg}"
2277        );
2278        assert!(
2279            !absent_msg.contains(&other_tmp.path().display().to_string()),
2280            "no concrete package path when no package exists: {absent_msg}"
2281        );
2282
2283        // Version mismatch against an installed package (some source
2284        // holds versions of the name) → no hint even though the
2285        // authoring package exists.
2286        let mismatch_req: semver::Version = "99.0.0".parse().unwrap();
2287        let mismatch = EngineError::SchemaNotFound {
2288            mem: "specs".to_string(),
2289            pin: "default@99.0.0".to_string(),
2290            sources: SchemaSourceDiagnostic::for_failed_pin("default", &mismatch_req, &[]),
2291            install_hint: None,
2292        }
2293        .with_schema_install_probe(Some(tmp.path()));
2294        let mismatch_msg = mismatch.to_string();
2295        assert!(
2296            !mismatch_msg.contains("schema install"),
2297            "version mismatch must not hint install: {mismatch_msg}"
2298        );
2299        assert!(
2300            mismatch_msg.contains("memstead mem set-schema specs default@1.3.0"),
2301            "version mismatch hints version repair instead: {mismatch_msg}"
2302        );
2303
2304        // Non-SchemaNotFound errors pass through unchanged.
2305        let other = EngineError::UnknownMem("specs".to_string())
2306            .with_schema_install_probe(Some(tmp.path()));
2307        assert_eq!(other.code(), "UNKNOWN_MEM");
2308    }
2309
2310    /// The ambiguous-grammar case suggests a
2311    /// colon-form (`mem:slug`), which is NOT a bare slug — it must not
2312    /// be promoted to `proposed_slug`.
2313    #[test]
2314    fn invalid_wiki_link_colon_form_suggestion_is_not_a_proposed_slug() {
2315        let err = EngineError::InvalidWikiLinkTarget {
2316            raw: "team/sub--thing".to_string(),
2317            suggested: Some("team/sub:thing".to_string()),
2318            section: "purpose".to_string(),
2319            link_source: "body_link".to_string(),
2320            reason: "ambiguous".to_string(),
2321        };
2322        let d = err.details();
2323        assert!(
2324            d["proposed_slug"].is_null(),
2325            "colon-form must not be a proposed_slug: {d}"
2326        );
2327        assert_eq!(d["suggested"], "team/sub:thing");
2328    }
2329
2330    /// A bad `--since` cursor is the typed `INVALID_CURSOR`
2331    /// code carrying the untruncated SHA in `details.since`.
2332    #[test]
2333    fn invalid_changes_cursor_code_and_details() {
2334        let sha = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
2335        let err = EngineError::InvalidChangesCursor {
2336            mem: "specs".to_string(),
2337            since: sha.to_string(),
2338        };
2339        assert_eq!(err.code(), "INVALID_CURSOR");
2340        let d = err.details();
2341        assert_eq!(d["mem"], "specs");
2342        assert_eq!(
2343            d["since"], sha,
2344            "the offending SHA must ride untruncated in details"
2345        );
2346    }
2347}
2348
2349#[cfg(test)]
2350mod inline_list_tests {
2351    use super::*;
2352
2353    #[test]
2354    fn empty_list_renders_empty_string() {
2355        let items: Vec<String> = Vec::new();
2356        assert_eq!(format_inline_list_overflow(&items, "x"), "");
2357    }
2358
2359    #[test]
2360    fn list_at_cap_renders_all_no_overflow_suffix() {
2361        let items = vec!["a".to_string(), "b".to_string(), "c".to_string()];
2362        assert_eq!(format_inline_list_overflow(&items, "x"), "a, b, c");
2363    }
2364
2365    #[test]
2366    fn list_under_cap_renders_all_no_overflow_suffix() {
2367        let items = vec!["a".to_string(), "b".to_string()];
2368        assert_eq!(format_inline_list_overflow(&items, "x"), "a, b");
2369    }
2370
2371    #[test]
2372    fn list_over_cap_appends_count_and_field_name() {
2373        let items: Vec<String> = (0..23).map(|i| format!("id{i}")).collect();
2374        let rendered = format_inline_list_overflow(&items, "referrers");
2375        assert_eq!(rendered, "id0, id1, id2 +20 more — see details.referrers");
2376    }
2377
2378    #[test]
2379    fn list_six_items_truncates_to_three_plus_three() {
2380        let items: Vec<String> = (0..6).map(|i| format!("t{i}")).collect();
2381        let rendered = format_inline_list_overflow(&items, "missing");
2382        assert_eq!(rendered, "t0, t1, t2 +3 more — see details.missing");
2383    }
2384
2385    #[test]
2386    fn has_incoming_refs_display_inlines_first_three_referrer_ids() {
2387        let referrers: Vec<ReferrerInfo> = (0..23)
2388            .map(|i| ReferrerInfo {
2389                from_id: format!("specs--ref{i}"),
2390                rel_types: vec!["USES".to_string()],
2391                mem: "specs".to_string(),
2392            })
2393            .collect();
2394        let err = EngineError::HasIncomingRefs {
2395            id: "specs--hub".to_string(),
2396            referrers,
2397        };
2398        let s = err.to_string();
2399        // First three ids appear inline; the rest are summarised plus a
2400        // pointer to `details.referrers` on the structured channel.
2401        assert!(
2402            s.contains("specs--ref0, specs--ref1, specs--ref2"),
2403            "got: {s}"
2404        );
2405        assert!(s.contains("+20 more — see details.referrers"), "got: {s}");
2406        // Pre-fix the message only carried the count; check the count
2407        // still appears so callers parsing it for "N references" keep
2408        // working.
2409        assert!(s.contains("23 incoming reference"), "got: {s}");
2410    }
2411
2412    #[test]
2413    fn wiki_link_without_relation_display_lists_all_when_under_cap() {
2414        let missing = vec![
2415            MissingWikiLink {
2416                section_key: "specifies".to_string(),
2417                target_id: "specs--a".to_string(),
2418            },
2419            MissingWikiLink {
2420                section_key: "specifies".to_string(),
2421                target_id: "specs--b".to_string(),
2422            },
2423            MissingWikiLink {
2424                section_key: "rationale".to_string(),
2425                target_id: "specs--c".to_string(),
2426            },
2427        ];
2428        let err = EngineError::WikiLinkWithoutRelation {
2429            from_id: "specs--src".to_string(),
2430            missing,
2431        };
2432        let s = err.to_string();
2433        assert!(s.contains("specifies→specs--a"), "got: {s}");
2434        assert!(s.contains("specifies→specs--b"), "got: {s}");
2435        assert!(s.contains("rationale→specs--c"), "got: {s}");
2436        assert!(!s.contains("more — see details"), "got: {s}");
2437    }
2438
2439    #[test]
2440    fn wiki_link_without_relation_display_truncates_at_cap_with_pointer() {
2441        let missing: Vec<MissingWikiLink> = (0..6)
2442            .map(|i| MissingWikiLink {
2443                section_key: format!("s{i}"),
2444                target_id: format!("specs--t{i}"),
2445            })
2446            .collect();
2447        let err = EngineError::WikiLinkWithoutRelation {
2448            from_id: "specs--src".to_string(),
2449            missing,
2450        };
2451        let s = err.to_string();
2452        assert!(
2453            s.contains("s0→specs--t0, s1→specs--t1, s2→specs--t2"),
2454            "got: {s}"
2455        );
2456        assert!(s.contains("+3 more — see details.missing"), "got: {s}");
2457    }
2458
2459    #[test]
2460    fn relation_has_body_links_display_inlines_section_keys() {
2461        let err = EngineError::RelationHasBodyLinks {
2462            from_id: "specs--src".to_string(),
2463            to_id: "specs--dst".to_string(),
2464            rel_type: "USES".to_string(),
2465            body_links: vec!["specifies".to_string(), "rationale".to_string()],
2466        };
2467        let s = err.to_string();
2468        assert!(s.contains("specifies, rationale"), "got: {s}");
2469        assert!(!s.contains("more — see details"), "got: {s}");
2470    }
2471
2472    // --- prose_render -----------------------------------------------
2473    // The text
2474    // channel inlines full recovery payloads (no `+N more — see
2475    // details.X` pointer). Display stays terse for logs; prose_render
2476    // is the rich method MCP / CLI surfaces call for `content[0].text`.
2477
2478    #[test]
2479    fn prose_render_has_incoming_refs_inlines_every_referrer() {
2480        let referrers = (0..7)
2481            .map(|i| ReferrerInfo {
2482                from_id: format!("specs--r{i}"),
2483                rel_types: vec!["DEPENDS_ON".to_string()],
2484                mem: "specs".to_string(),
2485            })
2486            .collect();
2487        let err = EngineError::HasIncomingRefs {
2488            id: "specs--target".to_string(),
2489            referrers,
2490        };
2491        let prose = err.prose_render();
2492        for i in 0..7 {
2493            assert!(
2494                prose.contains(&format!("specs--r{i}")),
2495                "every referrer must appear inline; missing r{i} in: {prose}"
2496            );
2497        }
2498        assert!(!prose.contains("see details"), "got: {prose}");
2499        // Display stays terse with the overflow suffix.
2500        let display = err.to_string();
2501        assert!(
2502            display.contains("+4 more — see details.referrers"),
2503            "got: {display}"
2504        );
2505    }
2506
2507    #[test]
2508    fn prose_render_required_field_unset_inlines_field_description_and_rules() {
2509        // Update-path semantic: `on_create: false` → "cannot unset".
2510        let err = EngineError::RequiredFieldUnset {
2511            field: "verified_on".to_string(),
2512            entity_type: "requirement".to_string(),
2513            field_description: Some("ISO-8601 date the requirement was last validated".to_string()),
2514            enum_values: vec![],
2515            type_write_rules: vec!["bump verified_on on every status change".to_string()],
2516            on_create: false,
2517            missing: Vec::new(),
2518        };
2519        let prose = err.prose_render();
2520        assert!(
2521            prose.contains("ISO-8601 date"),
2522            "field_description missing: {prose}"
2523        );
2524        assert!(
2525            prose.contains("bump verified_on"),
2526            "type_write_rules missing: {prose}"
2527        );
2528        assert!(!prose.contains("see details"), "got: {prose}");
2529        assert!(
2530            prose.contains("cannot unset"),
2531            "update-path wording must say 'cannot unset': {prose}"
2532        );
2533    }
2534
2535    /// Create
2536    /// path renders "not provided" instead of "cannot unset" — the
2537    /// pre-fix wording was misleading on a path where nothing was
2538    /// ever set in the first place.
2539    #[test]
2540    fn prose_render_required_field_unset_create_path_uses_not_provided_wording() {
2541        let err = EngineError::RequiredFieldUnset {
2542            field: "verified_on".to_string(),
2543            entity_type: "requirement".to_string(),
2544            field_description: Some("ISO-8601 date the requirement was last validated".to_string()),
2545            enum_values: vec![],
2546            type_write_rules: vec![],
2547            on_create: true,
2548            missing: Vec::new(),
2549        };
2550        let prose = err.prose_render();
2551        assert!(
2552            prose.contains("not provided"),
2553            "create-path wording must say 'not provided': {prose}"
2554        );
2555        assert!(
2556            !prose.contains("cannot unset"),
2557            "create-path wording must NOT say 'cannot unset': {prose}"
2558        );
2559        // Same Display dispatch — `to_string()` mirrors `prose_render`'s
2560        // create-path lead.
2561        let display = err.to_string();
2562        assert!(
2563            display.contains("not provided"),
2564            "Display must match: {display}"
2565        );
2566        assert!(
2567            !display.contains("cannot unset"),
2568            "Display must match: {display}"
2569        );
2570    }
2571
2572    /// The
2573    /// create-path multi-field accumulator surfaces every required-
2574    /// no-default field unset in `details.missing[]`. Each entry
2575    /// carries `{field, description, enum_values, write_rules}` so
2576    /// the agent fixes the whole set in one retry. The singular
2577    /// `details.field` echoes `missing[0].field` for back-compat.
2578    #[test]
2579    fn details_required_field_unset_multi_field_envelope_shape() {
2580        use crate::runtime_validator::MissingRequiredField;
2581        let err = EngineError::RequiredFieldUnset {
2582            field: "decided_on".to_string(),
2583            entity_type: "decision".to_string(),
2584            field_description: Some("Date the decision was accepted. ISO YYYY-MM-DD.".to_string()),
2585            enum_values: vec![],
2586            type_write_rules: vec!["status transitions: proposed → accepted".to_string()],
2587            on_create: true,
2588            missing: vec![
2589                MissingRequiredField {
2590                    entity_type: "decision".to_string(),
2591                    key: "decided_on".to_string(),
2592                    description: "Date the decision was accepted. ISO YYYY-MM-DD.".to_string(),
2593                    enum_values: vec![],
2594                },
2595                MissingRequiredField {
2596                    entity_type: "decision".to_string(),
2597                    key: "deciders".to_string(),
2598                    description: "Who made the call. Comma-separated handles.".to_string(),
2599                    enum_values: vec![],
2600                },
2601            ],
2602        };
2603        let details = err.details();
2604        // Back-compat: singular `field` echoes the first-missing entry.
2605        assert_eq!(details["field"].as_str(), Some("decided_on"));
2606        // Multi-field accumulator surfaces every entry in
2607        // declaration order.
2608        let missing = details["missing"].as_array().expect("missing[] array");
2609        assert_eq!(missing.len(), 2);
2610        assert_eq!(missing[0]["field"].as_str(), Some("decided_on"));
2611        assert_eq!(missing[1]["field"].as_str(), Some("deciders"));
2612        // First entry's `field` agrees with the singular shape.
2613        assert_eq!(details["field"], missing[0]["field"]);
2614        // Per-entry `write_rules` echoes the type-level rules for
2615        // self-containment.
2616        assert_eq!(missing[0]["write_rules"], details["type_write_rules"]);
2617        // Prose mentions both field names so the agent reading the
2618        // text channel sees the whole set without crossing into the
2619        // structured channel.
2620        let prose = err.prose_render();
2621        assert!(prose.contains("decided_on"), "got: {prose}");
2622        assert!(prose.contains("deciders"), "got: {prose}");
2623    }
2624
2625    /// The unset path's singular shape is
2626    /// preserved — `missing[]` is empty (the user targeted one field
2627    /// by definition); the singular fields above are authoritative.
2628    /// The typed code stays `REQUIRED_FIELD_UNSET`.
2629    #[test]
2630    fn details_required_field_unset_singular_shape_for_unset_path() {
2631        let err = EngineError::RequiredFieldUnset {
2632            field: "decided_on".to_string(),
2633            entity_type: "decision".to_string(),
2634            field_description: Some("…".to_string()),
2635            enum_values: vec![],
2636            type_write_rules: vec![],
2637            on_create: false,
2638            missing: Vec::new(),
2639        };
2640        let details = err.details();
2641        assert_eq!(details["field"].as_str(), Some("decided_on"));
2642        let missing = details["missing"]
2643            .as_array()
2644            .expect("missing[] array present");
2645        assert!(missing.is_empty(), "unset-path missing[] must be empty");
2646        assert_eq!(err.code(), "REQUIRED_FIELD_UNSET");
2647    }
2648
2649    #[test]
2650    fn prose_render_missing_required_section_enumerates_each_section_with_write_rules() {
2651        use crate::runtime_validator::MissingRequiredSection;
2652        let sections = vec![
2653            MissingRequiredSection {
2654                entity_type: "spec".to_string(),
2655                key: "purpose".to_string(),
2656                heading: "Purpose".to_string(),
2657                write_rules: vec!["one-sentence statement of intent".to_string()],
2658            },
2659            MissingRequiredSection {
2660                entity_type: "spec".to_string(),
2661                key: "scope".to_string(),
2662                heading: "Scope".to_string(),
2663                write_rules: vec!["what is in and out of scope".to_string()],
2664            },
2665        ];
2666        let mut type_guidance: std::collections::BTreeMap<String, Vec<String>> = Default::default();
2667        type_guidance.insert(
2668            "spec".to_string(),
2669            vec!["specs are immutable once stable".to_string()],
2670        );
2671        let err = EngineError::MissingRequiredSection {
2672            entity_type: "spec".to_string(),
2673            missing_count: 2,
2674            sections,
2675            type_guidance,
2676        };
2677        let prose = err.prose_render();
2678        assert!(prose.contains("purpose"), "got: {prose}");
2679        assert!(prose.contains("scope"), "got: {prose}");
2680        assert!(
2681            prose.contains("one-sentence statement of intent"),
2682            "got: {prose}"
2683        );
2684        assert!(
2685            prose.contains("specs are immutable once stable"),
2686            "got: {prose}"
2687        );
2688        assert!(!prose.contains("see details"), "got: {prose}");
2689    }
2690
2691    #[test]
2692    fn prose_render_relationship_cycle_inlines_existing_path() {
2693        use crate::entity::EntityId;
2694        let path = vec![
2695            EntityId::canonical("specs--a"),
2696            EntityId::canonical("specs--b"),
2697            EntityId::canonical("specs--c"),
2698            EntityId::canonical("specs--a"),
2699        ];
2700        let err = EngineError::RelationshipCycle {
2701            rel_type: "PART_OF".to_string(),
2702            from: EntityId::canonical("specs--a"),
2703            to: EntityId::canonical("specs--c"),
2704            existing_path: path,
2705            path_truncated: false,
2706        };
2707        let prose = err.prose_render();
2708        assert!(
2709            prose.contains("specs--a → specs--b → specs--c → specs--a"),
2710            "got: {prose}"
2711        );
2712        assert!(!prose.contains("see details"), "got: {prose}");
2713    }
2714
2715    #[test]
2716    fn prose_render_falls_back_to_display_for_trivial_variants() {
2717        // ReadOnlyMount has no list payload — Display already inlines
2718        // the recovery context.
2719        let err = EngineError::ReadOnlyMount("archive-2024".to_string());
2720        assert_eq!(err.prose_render(), err.to_string());
2721    }
2722
2723    /// A slug collision names the occupying title on both channels —
2724    /// two distinct titles can derive one id, and the id alone does
2725    /// not tell the caller which one is already there.
2726    #[test]
2727    fn already_exists_names_the_occupying_title_on_both_channels() {
2728        let err = EngineError::AlreadyExists {
2729            id: "muehle--bösenberg-grundstücks-gmbh-co-kg".to_string(),
2730            existing_title: "Bösenberg Grundstücks GmbH Co KG".to_string(),
2731            existing_is_stub: false,
2732        };
2733        assert!(
2734            err.to_string()
2735                .contains("occupied by 'Bösenberg Grundstücks GmbH Co KG'"),
2736            "got: {err}"
2737        );
2738        let details = err.details();
2739        assert_eq!(
2740            details["existing_title"],
2741            "Bösenberg Grundstücks GmbH Co KG"
2742        );
2743        assert_eq!(details["existing_is_stub"], false);
2744        assert_eq!(details["id"], "muehle--bösenberg-grundstücks-gmbh-co-kg");
2745    }
2746
2747    /// A stub occupant states it is a stub; a titleless stub must not
2748    /// render as an empty or missing title.
2749    #[test]
2750    fn already_exists_stub_occupant_never_renders_an_empty_title() {
2751        let titled = EngineError::AlreadyExists {
2752            id: "specs--x".to_string(),
2753            existing_title: "X".to_string(),
2754            existing_is_stub: true,
2755        };
2756        assert!(
2757            titled.to_string().contains("a stub titled 'X'"),
2758            "got: {titled}"
2759        );
2760
2761        let untitled = EngineError::AlreadyExists {
2762            id: "specs--x".to_string(),
2763            existing_title: String::new(),
2764            existing_is_stub: true,
2765        };
2766        let msg = untitled.to_string();
2767        assert!(msg.contains("occupied by a stub"), "got: {msg}");
2768        assert!(!msg.contains("''"), "empty title must not render: {msg}");
2769    }
2770}