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