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