Skip to main content

memstead_base/engine/
error.rs

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