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