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