Skip to main content

memstead_base/engine/
error.rs

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