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, and the sections whose
784    /// bodies DO contain the substring — the one-call recovery when
785    /// the patch simply targeted the wrong section.
786    #[error("patch `old` substring not found in {section}")]
787    PatchOldNotFound {
788        section: String,
789        current_content: String,
790        truncated: bool,
791        found_in_sections: Vec<String>,
792    },
793    /// `UNTERMINATED_FENCE_IN_STORED_BODY`: the entity on disk already ends a
794    /// section inside an open code fence, and this write does not resolve it
795    /// (consistency-sweep 04/02, criterion 5).
796    ///
797    /// The state is not the caller's doing: the generator closes every fence
798    /// it emits, so it can only arrive by hand-authoring, a folder mem edited
799    /// outside the engine, or sibling-committed branch state. But the closer
800    /// is appended AFTER the already-absorbed bytes, so a write here would
801    /// seal the swallowed sections inside a legitimately closed fence, and no
802    /// later pass can tell them from prose the author meant to fence. The
803    /// freeze is unrecoverable through the engine, which is why this refuses
804    /// rather than warns.
805    ///
806    /// The way out is replace mode on the named section: that value passes
807    /// the `UNTERMINATED_FENCE` guard, so it cannot leave a fence open, and
808    /// the caller can lift the swallowed content back out of it. Its sibling
809    /// [`ValidationError::UnterminatedFence`] refuses the same condition in
810    /// content the caller supplies.
811    #[error(
812        "entity '{id}' section '{section}' ends inside an unterminated `{fence}` code fence, and \
813         this update does not replace it. Writing now would close the fence around content that \
814         belongs to other sections and make the loss permanent. Replace section '{section}' with \
815         a corrected body in the same call."
816    )]
817    UnterminatedFenceInStoredBody {
818        id: String,
819        section: String,
820        fence: String,
821        swallowed: Vec<String>,
822    },
823    /// Schema-strictness rejection from the runtime validator
824    /// (`UNKNOWN_SECTION`, `UNKNOWN_METADATA`, `INVALID_ENUM_VALUE`).
825    #[error("schema validation: {0}")]
826    Validation(#[from] ValidationError),
827    /// Re-parse of the freshly-generated markdown failed. Should
828    /// never happen — the generator's contract is that its output
829    /// round-trips through `parse_markdown`. Surfaces if a future
830    /// generator change breaks that invariant.
831    #[error("parse-after-write failed: {0}")]
832    ParseAfterWrite(String),
833    /// A wrapped parse error for completeness; today only the
834    /// parse-after-write variant above is constructed in the create
835    /// path.
836    #[error("parse error: {0}")]
837    Parse(#[from] ParseError),
838    /// A backend operation failed. Inner error carries the typed
839    /// payload (e.g. `Sealed`, `HashMismatch`, `Io`).
840    #[error(transparent)]
841    Backend(#[from] BackendError),
842    /// A mem's schema pin did not resolve. `sources` carries the
843    /// fixed-order resolution diagnostics (local storage / built-in /
844    /// remote) so the caller can tell *where* the pin failed and spot a
845    /// right-name/wrong-version partial match; it surfaces under
846    /// `details.sources`. Empty `sources` marks an internal lookup miss
847    /// (an already-resolved schema absent from the engine's per-mem
848    /// map), not a genuine source-resolution failure.
849    ///
850    /// The MESSAGE summarises the trail — which sources were searched
851    /// and whether the name was found at other versions — so the
852    /// distinction between a wrong-version pin and a never-installed
853    /// package reaches consumers that never open `details` (a reported
854    /// autonomous loop burned five rounds on the payload-only shape).
855    /// `install_hint` (set by [`EngineError::with_schema_install_probe`]
856    /// where a workspace root is known) names the authoring package
857    /// that exists in the working tree but was never installed, and
858    /// the message then points at `memstead schema install`.
859    #[error("{}", schema_not_found_message(mem, pin, sources, install_hint))]
860    SchemaNotFound {
861        mem: String,
862        pin: String,
863        sources: Vec<SchemaSourceDiagnostic>,
864        /// Path to an authoring package in the working tree whose
865        /// manifest name matches the pin's name while NO source holds
866        /// any version of that name — i.e. the package was authored
867        /// but never installed. `None` when no such package exists,
868        /// when the name is installed at other versions (a version
869        /// mismatch is a different fix), or when no workspace root
870        /// was available to probe.
871        install_hint: Option<String>,
872    },
873    /// A sealed schema package carried inside a mem archive could not
874    /// be loaded — the archive's own `.memstead/schema/` tree is
875    /// broken. Deliberately NOT `SchemaNotFound`: the package is right
876    /// here, so the recovery is never "obtain the schema and install
877    /// it". The message quotes the loader's own diagnosis and the
878    /// refusal leaves nothing mounted and nothing staged; only the
879    /// publisher can fix it.
880    #[error(
881        "mem {mem}: the schema {pin} embedded in the archive could not be loaded: {reason} — \
882         the package is inside the archive, so this is the publisher's to fix; nothing was \
883         staged or mounted"
884    )]
885    EmbeddedSchemaInvalid {
886        mem: String,
887        pin: String,
888        reason: String,
889    },
890    /// A schema package handed to `install_schema` failed validation —
891    /// the loader's semantic checks or the section-heading round-trip
892    /// gate. The engine refuses to seal an invalid schema onto
893    /// `__MEMSTEAD`: install time is the last moment the author can
894    /// act, because a schema already sealed keeps loading even when a
895    /// later rule would refuse it.
896    #[error("schema package '{name}@{version}' failed validation: {message}")]
897    SchemaPackageInvalid {
898        name: String,
899        version: String,
900        message: String,
901    },
902    /// `memstead_schema::builtins::load_builtin_schemas` itself failed.
903    /// Surfaces during `Engine::from_mounts`; should never trip in
904    /// practice (the built-in catalogue is statically embedded), but
905    /// the failure path is preserved so a future on-disk catalogue
906    /// switch lifts cleanly.
907    #[error("built-in schema catalogue failed to load: {0}")]
908    SchemaResolverInit(String),
909    /// Generic mem-level error message — used by accessors that
910    /// surface "mem exists, but the requested resource is not
911    /// available for this backend" (e.g. `gitdir_for` against a
912    /// folder mount, `worktree_for` against a git-branch mount).
913    #[error("mem error: {0}")]
914    Mem(String),
915    /// `register_writable_mem` rejected because `name` is already
916    /// registered (writable OR read-only). `source_origin` is the
917    /// human-readable description of the colliding registration,
918    /// rendered via [`MemOrigin::render_source`] for writable
919    /// entries or a stand-in for read-only ones.
920    #[error("mem name collision: {name} is already registered ({source_origin})")]
921    MemNameCollision { name: String, source_origin: String },
922    /// Lifecycle orchestrator rejected the input. Carries a single
923    /// free-form message — the orchestrator's typed payload (note
924    /// length, malformed path, etc.) is the message text.
925    #[error("invalid input: {0}")]
926    InvalidInput(String),
927    /// Merge-conflict listing/resolution targeted a mem whose backend
928    /// cannot acquire git merge conflicts through supported use — the
929    /// git-branch mem-repo is engine-managed, archives and in-memory
930    /// sketches have no user-git seam at all. Only folder mems live in
931    /// the user's own repository where an ordinary merge can write
932    /// conflict markers into entity files. Typed code
933    /// `CONFLICT_RESOLVE_UNSUPPORTED_BACKEND`.
934    #[error(
935        "mem `{mem}` is not folder-backed — its storage cannot acquire git merge \
936         conflicts through supported use; `conflicts` operations apply to folder mems only"
937    )]
938    MergeConflictUnsupportedBackend { mem: String },
939    /// Conflict resolution targeted an entity whose file carries no git
940    /// merge-conflict markers — nothing to resolve. Distinct from
941    /// `NotFound` so an agent can tell "already clean" from "no such
942    /// entity". Typed code `NOT_CONFLICTED`.
943    #[error(
944        "entity `{id}` is not conflicted — its file carries no git merge-conflict \
945         markers; nothing to resolve"
946    )]
947    NotConflicted { id: String },
948    /// `memstead_fetch` / `memstead_pull` / `memstead_push` named a remote that is
949    /// not configured on the workspace's mem-repo. Typed code
950    /// `UNKNOWN_REMOTE`. Recovery: configure the remote via
951    /// `memstead mem-repo remote-add <name> <url>`.
952    #[error("unknown remote: {0}")]
953    UnknownRemote(String),
954    /// `memstead_pull` refused because the local branch has diverged from
955    /// the remote-tracking ref — fast-forward is impossible without
956    /// losing local commits. Recovery: run `memstead branch-reset` to the
957    /// remote-tracking ref (if the local commits are dispensable) or
958    /// run a replay workflow to rewrite them onto the new remote tip.
959    /// Typed code `LOCAL_DIVERGENCE`.
960    #[error(
961        "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"
962    )]
963    LocalDivergence { mem: String, remote_ref: String },
964    /// `memstead_push` refused because the push would not be a fast-forward
965    /// against the remote and the caller did not pass `force: true`.
966    /// Typed code `NON_FAST_FORWARD`. Recovery: re-fetch + replay, or
967    /// re-issue with `force: true` (warning: rewrites the remote's
968    /// view of the branch — other peers will see the rewrite).
969    #[error(
970        "push to remote `{remote}` for mem `{mem}` is not a fast-forward; rebase / replay locally or pass `force: true` to overwrite the remote"
971    )]
972    NonFastForward { mem: String, remote: String },
973    /// `memstead_push` refused because the local state failed pre-push
974    /// schema validation. The remote was not contacted. Recovery: fix
975    /// the schema violations (use `memstead_health` to find them) and
976    /// retry. Typed code `LOCAL_INVALID_STATE`.
977    #[error(
978        "mem `{mem}` failed pre-push schema validation; remote `{remote}` was not contacted: {detail}"
979    )]
980    LocalInvalidState {
981        mem: String,
982        remote: String,
983        detail: String,
984    },
985    /// `memstead_pull` (or any future merge path that consumes fetched
986    /// commits) refused because the prospective post-merge tree
987    /// contains entities that fail schema validation. The branch
988    /// pointer was not moved. `violations` carries one entry per
989    /// offending entity — typically `(relative_path, parse_error)`
990    /// pairs rendered as strings — so the caller can surface the
991    /// remediation surface without re-walking the tree. Typed code
992    /// `SCHEMA_VIOLATION_IN_FETCH`.
993    #[error(
994        "mem `{mem}` would fail schema validation at `{ref_name}` — {n} violation(s); fix the remote or replay locally first",
995        n = violations.len(),
996    )]
997    SchemaViolationInFetch {
998        mem: String,
999        ref_name: String,
1000        violations: Vec<String>,
1001    },
1002    /// `memstead_branch_reset` refused because at least one commit that
1003    /// would be discarded by the reset is already reachable from a
1004    /// `refs/remotes/*` ref (the engine's definition of "pushed").
1005    /// `pushed_shas` lists the offending commits. The agent's
1006    /// recovery is to pick a target SHA that does not strand a pushed
1007    /// commit, or to push the pre-reset state under a different
1008    /// branch name first. Typed code: `PUSHED_COMMITS_PROTECTED`.
1009    #[error(
1010        "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",
1011        pushed_shas.len(),
1012        pushed_shas.join(", "),
1013    )]
1014    PushedCommitsProtected {
1015        mem: String,
1016        target_sha: String,
1017        pushed_shas: Vec<String>,
1018    },
1019    /// `branch_reset` refused because the live branch head no longer
1020    /// matches the head the caller observed (`expected_head`) — a
1021    /// sibling writer advanced the mem, and resetting now would discard
1022    /// that foreign work. Optimistic concurrency for history rewrites;
1023    /// the caller re-reads and re-decides. Typed code:
1024    /// `BRANCH_RESET_HEAD_MOVED`.
1025    #[error(
1026        "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"
1027    )]
1028    BranchResetHeadMoved {
1029        mem: String,
1030        expected: String,
1031        current: String,
1032    },
1033    /// `memstead_diff` (or any future ref-comparing op) received a ref
1034    /// that does not resolve against the workspace's mem-repo.
1035    /// Carries the ref string verbatim so the caller can fix the
1036    /// input. Typed code `UNKNOWN_REF`.
1037    #[error("unknown ref: {0}")]
1038    UnknownRef(String),
1039    /// `memstead_changes_since` received a `rename_similarity` value
1040    /// outside the allowed range. Maps to wire code `INVALID_INPUT`
1041    /// with `details.allowed_range: [min, max]` and
1042    /// `details.requested`. Promoted from the prior silent-clamp + LIMIT_CLAMPED warning so
1043    /// nonsense inputs surface as recoverable refusal rather than
1044    /// silent rounding.
1045    #[error("rename_similarity {requested} outside allowed range [{allowed_min}, {allowed_max}]")]
1046    RenameSimilarityOutOfRange {
1047        requested: f32,
1048        allowed_min: f32,
1049        allowed_max: f32,
1050    },
1051    /// `memstead_changes_since` / `memstead changes --since` was given a `since`
1052    /// commit cursor the mem's git repository can't resolve — a
1053    /// malformed prefix or a well-formed-but-absent 40-hex. Surfaces the
1054    /// `INVALID_CURSOR` code (the documented contract for this op, which
1055    /// the CLI previously leaked as the `MEM_ERROR` catch-all) so a
1056    /// sync loop branches cleanly: `INVALID_CURSOR` → re-seed from the
1057    /// empty-tree sentinel; `MEM_ERROR` → genuine backend fault.
1058    /// `details.since` carries the offending cursor untruncated.
1059    #[error(
1060        "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"
1061    )]
1062    InvalidChangesCursor { mem: String, since: String },
1063    /// `memstead_changes_since` / `memstead changes --since` on a
1064    /// folder-backed (or in-memory) mem was given a `since` that is not
1065    /// an RFC3339 timestamp. These backends key the change ledger off
1066    /// timestamps and compare lexically, so before this refusal a
1067    /// mutation's `write_id` — fixed-width hex that sorts below every
1068    /// timestamp — silently replayed the whole history. Shares the
1069    /// `INVALID_CURSOR` code with the git-backed variant so a sync
1070    /// loop's branch (`INVALID_CURSOR` → re-seed) is backend-agnostic.
1071    /// `details.since` carries the offending cursor untruncated.
1072    #[error(
1073        "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"
1074    )]
1075    InvalidTimestampCursor { mem: String, since: String },
1076    /// `review_mark_diff` was called on a mem with no review mark set.
1077    /// Marklessness is a first-class, known-from-the-roster state — the
1078    /// diff surface refuses typed rather than silently equating "no
1079    /// mark" with "no changes".
1080    #[error(
1081        "mem '{mem}' has no review mark — set one first, or read the full history via changes_since"
1082    )]
1083    ReviewMarkNotSet { mem: String },
1084    /// Mem config is missing a required field that the engine
1085    /// itself would normally populate (today: `version` at mem
1086    /// init). Surfaced on the export path — pre-fix this collapsed
1087    /// to `INTERNAL` with a misleading `.memstead/config.json` reference
1088    /// that doesn't match the mem-repo backend's blob layout.
1089    /// Recovery: run `memstead mem set-version <mem> <version>` to
1090    /// populate the field, then retry the export. F1.
1091    #[error(
1092        "mem `{mem}` config is missing required field(s) {missing_fields:?} — \
1093         set via `memstead mem set-version {mem} <version>` (e.g. 0.1.0)"
1094    )]
1095    MemConfigIncomplete {
1096        mem: String,
1097        missing_fields: Vec<String>,
1098    },
1099    /// `memstead_relate` (or a `declare_relations` entry) targeted a
1100    /// rel-type whose schema declares `per_edge_description:
1101    /// required` without supplying a description. Recovery: re-issue
1102    /// the call with `--description "<text>"` describing why this
1103    /// particular edge exists (the rel-type's name documents the
1104    /// kind of edge; the description documents the instance).
1105    #[error(
1106        "rel-type `{rel_type}` declares `per_edge_description: required` — \
1107         {from_id} → {to_id} needs a description; re-issue with \
1108         `--description \"<text>\"`."
1109    )]
1110    MissingRequiredDescription {
1111        rel_type: String,
1112        from_id: String,
1113        to_id: String,
1114    },
1115    /// `memstead_relate` (or a `declare_relations` entry) supplied a
1116    /// description for a rel-type whose schema declares
1117    /// `per_edge_description: forbidden`. Recovery: drop the
1118    /// `description` parameter — the rel-type's name describes the
1119    /// edge; per-edge text is not permitted on this rel-type.
1120    #[error(
1121        "rel-type `{rel_type}` declares `per_edge_description: forbidden` — \
1122         {from_id} → {to_id} cannot carry a description; drop the \
1123         `--description` argument."
1124    )]
1125    DescriptionNotPermitted {
1126        rel_type: String,
1127        from_id: String,
1128        to_id: String,
1129    },
1130    /// `memstead_relate` (or a `declare_relations` / `memstead_create`'s
1131    /// inline `relations:` entry) targeted a rel-type whose schema
1132    /// declares `manual_authoring: forbidden`. The rel-type is
1133    /// reserved for engine-emitted synthesis (the body-link →
1134    /// relation alias machinery, typically). Recovery: don't author
1135    /// the relation explicitly; instead author a body wiki-link
1136    /// `[[target]]` in the source's section content, which the
1137    /// engine surfaces as the appropriate alias relation
1138    /// automatically.
1139    #[error(
1140        "rel-type `{rel_type}` declares `manual_authoring: forbidden` — \
1141         {from_id} → {to_id} cannot be authored explicitly; this rel-type \
1142         is reserved for engine-emitted synthesis via the body-link → \
1143         relation alias path. {guidance}"
1144    )]
1145    RelationManualAuthoringForbidden {
1146        rel_type: String,
1147        from_id: String,
1148        to_id: String,
1149        guidance: String,
1150    },
1151    /// Full-text search is unavailable in the current engine build —
1152    /// `Engine::search` is callable on every target so JS / FFI
1153    /// consumers don't need to re-shape their call sites, but `wasm32`
1154    /// builds omit the tantivy index entirely (its native-only
1155    /// transitives — `getrandom 0.2` without `js`, `memmap2`, `rayon`,
1156    /// `zstd-sys` — block WASM compilation). Browser consumers route
1157    /// queries to the bridge's `memstead_search` endpoint. The MCP layer
1158    /// maps this to typed code `SEARCH_UNAVAILABLE_IN_WASM`.
1159    #[error(
1160        "full-text search is unavailable in this engine build (wasm32); \
1161         route search queries to the bridge's memstead_search endpoint"
1162    )]
1163    SearchUnavailable,
1164    /// `memstead export --format markdown --mem-name <V>` was called
1165    /// against a mem whose active backend doesn't support markdown
1166    /// regeneration in place (today: every backend other than
1167    /// `folder`). Pre-fix this collapsed to a silent
1168    /// `ExportResult { written: 0, unchanged: 0 }` masquerading as
1169    /// success. Recovery: use `--format mem` to produce a portable
1170    /// `.mem` archive, which every backend supports.
1171    #[error(
1172        "mem `{mem}` is on backend `{active_backend}`; `memstead export --format markdown` \
1173         is supported only on backends [{}] — use `--format mem` to produce a portable \
1174         `.mem` archive instead",
1175        supported_backends.join(", ")
1176    )]
1177    MarkdownExportUnsupportedBackend {
1178        mem: String,
1179        active_backend: String,
1180        supported_backends: Vec<String>,
1181    },
1182    /// A `memstead_create` / `memstead_update` `anchors[]` element was
1183    /// malformed — an unknown provenance class or grain, a missing artifact
1184    /// reference, a content hash on a class without hash semantics, or a
1185    /// grain the resolving medium's namespace cannot express. The whole
1186    /// mutation refuses and the entity is not written; the wrapped
1187    /// [`crate::anchor::AnchorValidationError`] carries the recovery
1188    /// `details` (offending field, bad value, allowed set). Typed code
1189    /// `INVALID_ANCHOR`.
1190    #[error("invalid anchor: {0}")]
1191    InvalidAnchor(#[from] crate::anchor::AnchorValidationError),
1192}
1193
1194/// Typed payload for a single Write-Mem referrer in
1195/// [`EngineError::HasIncomingRefs`]. Captures the (from_id, rel_types,
1196/// mem) triple the surface envelope projects so consumers can reason
1197/// about the offending edges without a follow-up `memstead_entity` call.
1198/// The mem is always a Write-Mem — ReadOnly referrers are
1199/// partitioned out before this struct is constructed and surfaced via
1200/// the residual-stub warning channel instead.
1201///
1202/// Per-source deduplication: when one source entity has multiple
1203/// edges of different rel-types pointing at the deletion target, the
1204/// engine collapses them into a single `ReferrerInfo` whose
1205/// `rel_types` list carries every edge type. A prior shape
1206/// emitted one entry per edge, making a source-with-N-edges look
1207/// like N distinct referrers in the error message and structured
1208/// payload.
1209#[derive(Debug, Clone, serde::Serialize)]
1210pub struct ReferrerInfo {
1211    pub from_id: String,
1212    pub rel_types: Vec<String>,
1213    pub mem: String,
1214}
1215
1216/// Inline rendering on the text mirror. Single rel-type renders as
1217/// just the referring entity id; multiple rel-types append the
1218/// `×N [REL1, REL2]` annotation so the count and the offending
1219/// edge-types stay visible without parsing the structured payload.
1220impl fmt::Display for ReferrerInfo {
1221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1222        if self.rel_types.len() <= 1 {
1223            f.write_str(&self.from_id)
1224        } else {
1225            write!(
1226                f,
1227                "{} ×{} [{}]",
1228                self.from_id,
1229                self.rel_types.len(),
1230                self.rel_types.join(", ")
1231            )
1232        }
1233    }
1234}
1235
1236/// One body wiki-link that violates the strict wiki-link /
1237/// relation invariant. Surfaces inside
1238/// [`EngineError::WikiLinkWithoutRelation::missing`].
1239#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
1240pub struct MissingWikiLink {
1241    /// Section key of the entity body where the unbacked
1242    /// wiki-link appears.
1243    pub section_key: String,
1244    /// EntityId target of the unbacked wiki-link.
1245    pub target_id: String,
1246}
1247
1248/// Inline rendering pairs the section key with the unbacked target id
1249/// so an agent reading only the text mirror can see both where the link
1250/// lives and what it points at without decoding the structured payload.
1251impl fmt::Display for MissingWikiLink {
1252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1253        write!(f, "{}→{}", self.section_key, self.target_id)
1254    }
1255}
1256
1257impl EngineError {
1258    /// Stable, surface-independent error code token.
1259    ///
1260    /// Each surface (MCP envelope, CLI envelope) maps
1261    /// the variant to its wire shape; the code returned here is the
1262    /// canonical name agents key on. Add a new code here when a new
1263    /// variant lands; do not invent ad-hoc strings inside the
1264    /// per-surface mapping.
1265    pub fn code(&self) -> &'static str {
1266        match self {
1267            EngineError::DuplicateMem(_) => "DUPLICATE_MEM",
1268            EngineError::UnknownMem(_) => "UNKNOWN_MEM",
1269            EngineError::MemQuarantined { .. } => "MEM_QUARANTINED",
1270            EngineError::UnknownRef(_) => "UNKNOWN_REF",
1271            EngineError::UnknownRemote(_) => "UNKNOWN_REMOTE",
1272            EngineError::LocalDivergence { .. } => "LOCAL_DIVERGENCE",
1273            EngineError::NonFastForward { .. } => "NON_FAST_FORWARD",
1274            EngineError::LocalInvalidState { .. } => "LOCAL_INVALID_STATE",
1275            EngineError::SchemaViolationInFetch { .. } => "SCHEMA_VIOLATION_IN_FETCH",
1276            EngineError::PushedCommitsProtected { .. } => "PUSHED_COMMITS_PROTECTED",
1277            EngineError::BranchResetHeadMoved { .. } => "BRANCH_RESET_HEAD_MOVED",
1278            EngineError::ReadOnlyMount(_) => "READ_ONLY_MOUNT",
1279            EngineError::CheckNotRecorded { .. } => "CHECK_NOT_RECORDED",
1280            EngineError::UnknownType { .. } => "UNKNOWN_ENTITY_TYPE",
1281            EngineError::InvalidTitle(_) => "INVALID_TITLE",
1282            EngineError::AlreadyExists { .. } => "ENTITY_ALREADY_EXISTS",
1283            EngineError::ConstraintUnsatisfied { .. } => "CONSTRAINT_UNSATISFIED",
1284            EngineError::RequiredOutgoingUnsatisfied { .. } => "MISSING_REQUIRED_OUTGOING",
1285            EngineError::SectionFormatRefused { violation, .. } => violation.code(),
1286            EngineError::NotFound { .. } => "ENTITY_NOT_FOUND",
1287            EngineError::HashMismatch { .. } => "HASH_MISMATCH",
1288            EngineError::HasIncomingRefs { .. } => "HAS_INCOMING_REFS",
1289            EngineError::MemHasIncomingRefs { .. } => "MEM_HAS_INCOMING_REFS",
1290            EngineError::CrossMemLinkNotAllowed { .. } => "CROSS_MEM_LINK_NOT_ALLOWED",
1291            EngineError::CrossMemTargetNotFound { .. } => "CROSS_MEM_TARGET_NOT_FOUND",
1292            EngineError::CrossMemEdgeNotDeclared { .. } => "CROSS_MEM_EDGE_NOT_DECLARED",
1293            EngineError::RepairNotNeeded { .. } => "REPAIR_NOT_NEEDED",
1294            EngineError::RenameNoOp { .. } => "RENAME_NO_OP",
1295            EngineError::EmptyUpdate { .. } => "EMPTY_UPDATE",
1296            EngineError::RenameBlockedByCrossMemPolicy { .. } => {
1297                "RENAME_BLOCKED_BY_CROSS_MEM_POLICY"
1298            }
1299            EngineError::RenamePartialFailure { .. } => "RENAME_PARTIAL_FAILURE",
1300            EngineError::RelationHasBodyLinks { .. } => "RELATION_HAS_BODY_LINKS",
1301            EngineError::WikiLinkWithoutRelation { .. } => "WIKILINK_WITHOUT_RELATION",
1302            EngineError::StubCannotRelate { .. } => "STUB_CANNOT_RELATE",
1303            EngineError::StubNotUpdatable { .. } => "STUB_NOT_UPDATABLE",
1304            EngineError::StubNotRenamable { .. } => "STUB_NOT_RENAMABLE",
1305            EngineError::InvalidEntityId { .. } => "INVALID_ENTITY_ID",
1306            EngineError::InvalidWikiLinkTarget { .. } => "INVALID_WIKI_LINK_TARGET",
1307            EngineError::InvalidWikiLinkMem { .. } => "INVALID_MEM_NAME",
1308            EngineError::ConflictingSectionModes { .. } => "CONFLICTING_SECTION_MODES",
1309            EngineError::RelationshipCycle { .. } => "RELATIONSHIP_CYCLE",
1310            EngineError::SetAndUnsetConflict { .. } => "SET_AND_UNSET_CONFLICT",
1311            EngineError::RequiredFieldUnset { .. } => "REQUIRED_FIELD_UNSET",
1312            EngineError::MissingRequiredSection { .. } => "MISSING_REQUIRED_SECTION",
1313            EngineError::PatchSectionEmpty { .. } => "PATCH_SECTION_EMPTY",
1314            EngineError::PatchOldNotFound { .. } => "PATCH_OLD_NOT_FOUND",
1315            EngineError::UnterminatedFenceInStoredBody { .. } => {
1316                "UNTERMINATED_FENCE_IN_STORED_BODY"
1317            }
1318            EngineError::Validation(v) => v.code(),
1319            EngineError::ParseAfterWrite(_) => "PARSE_ERROR",
1320            EngineError::Parse(_) => "PARSE_ERROR",
1321            EngineError::Backend(_) => "MEM_ERROR",
1322            EngineError::SchemaNotFound { .. } => "SCHEMA_NOT_FOUND",
1323            EngineError::EmbeddedSchemaInvalid { .. } => "EMBEDDED_SCHEMA_INVALID",
1324            EngineError::SchemaPackageInvalid { .. } => "SCHEMA_VALIDATION_FAILED",
1325            EngineError::SchemaResolverInit(_) => "SCHEMA_RESOLVER_INIT_FAILED",
1326            EngineError::Mem(_) => "MEM_ERROR",
1327            EngineError::MemNameCollision { .. } => "MEM_NAME_COLLISION",
1328            EngineError::InvalidInput(_) => "INVALID_INPUT",
1329            EngineError::MergeConflictUnsupportedBackend { .. } => {
1330                "CONFLICT_RESOLVE_UNSUPPORTED_BACKEND"
1331            }
1332            EngineError::NotConflicted { .. } => "NOT_CONFLICTED",
1333            EngineError::RenameSimilarityOutOfRange { .. } => "INVALID_INPUT",
1334            EngineError::InvalidChangesCursor { .. } => "INVALID_CURSOR",
1335            EngineError::InvalidTimestampCursor { .. } => "INVALID_CURSOR",
1336            EngineError::ReviewMarkNotSet { .. } => "REVIEW_MARK_NOT_SET",
1337            EngineError::MemConfigIncomplete { .. } => "MEM_CONFIG_INCOMPLETE",
1338            EngineError::MissingRequiredDescription { .. } => "MISSING_REQUIRED_DESCRIPTION",
1339            EngineError::DescriptionNotPermitted { .. } => "DESCRIPTION_NOT_PERMITTED",
1340            EngineError::RelationManualAuthoringForbidden { .. } => {
1341                "RELATION_MANUAL_AUTHORING_FORBIDDEN"
1342            }
1343            EngineError::SearchUnavailable => "SEARCH_UNAVAILABLE_IN_WASM",
1344            EngineError::MarkdownExportUnsupportedBackend { .. } => {
1345                "MARKDOWN_EXPORT_UNSUPPORTED_BACKEND"
1346            }
1347            EngineError::InvalidAnchor(_) => crate::anchor::INVALID_ANCHOR_CODE,
1348        }
1349    }
1350
1351    /// Variant-specific recovery payload, rendered as a structured
1352    /// JSON object that surfaces under `error.details` in MCP /
1353    /// CLI envelopes.
1354    ///
1355    /// Pre-fix the
1356    /// batch-update per-item envelope (`batch_error_envelope`)
1357    /// shipped `{}` for every typed code except `Validation`, while
1358    /// the singleton-call surfaces (`CliError::from_engine_op`,
1359    /// `memstead-mcp`'s `engine_err_unified`) populated structured
1360    /// payloads per-variant. Two envelopes, two details paths —
1361    /// agents' "fix from `details`" recovery loop worked
1362    /// differently in batch vs singleton mode. The centralised
1363    /// helper here gives both surfaces one source of truth.
1364    ///
1365    /// Returns an empty object for variants whose recovery payload
1366    /// is the message text alone (no structured fields beyond
1367    /// `code` + `message`).
1368    pub fn details(&self) -> serde_json::Value {
1369        match self {
1370            EngineError::NotFound { id } => serde_json::json!({ "id": id }),
1371            EngineError::AlreadyExists {
1372                id,
1373                existing_title,
1374                existing_is_stub,
1375            } => serde_json::json!({
1376                "id": id,
1377                "existing_title": existing_title,
1378                "existing_is_stub": existing_is_stub,
1379            }),
1380            EngineError::MemQuarantined {
1381                mem,
1382                reason_code,
1383                reason_message,
1384            } => serde_json::json!({
1385                "mem": mem,
1386                "reason_code": reason_code,
1387                "reason_message": reason_message,
1388            }),
1389            EngineError::ConstraintUnsatisfied {
1390                entity_type,
1391                entity_id,
1392                violations,
1393            } => serde_json::json!({
1394                "entity_type": entity_type,
1395                "entity_id": entity_id,
1396                "violations": violations,
1397            }),
1398            EngineError::RequiredOutgoingUnsatisfied {
1399                entity_type,
1400                entity_id,
1401                missing,
1402            } => serde_json::json!({
1403                "entity_type": entity_type,
1404                "entity_id": entity_id,
1405                "missing": missing,
1406            }),
1407            EngineError::SectionFormatRefused {
1408                entity_type,
1409                entity_id,
1410                violation,
1411            } => {
1412                let mut v = serde_json::to_value(violation).unwrap_or_default();
1413                if let Some(obj) = v.as_object_mut() {
1414                    obj.insert("entity_type".into(), serde_json::json!(entity_type));
1415                    obj.insert("entity_id".into(), serde_json::json!(entity_id));
1416                }
1417                v
1418            }
1419            EngineError::RepairNotNeeded { id, recovery } => {
1420                serde_json::json!({ "id": id, "recovery": recovery })
1421            }
1422            // Same shape the full MCP singleton envelope ships for
1423            // UNKNOWN_ENTITY_TYPE — keeps the centralised helper (and
1424            // every consumer: batch envelopes, the integrity linter)
1425            // aligned with the wire payload agents already decode.
1426            EngineError::UnknownType {
1427                name,
1428                schema_ref,
1429                declared,
1430                suggestion,
1431            } => serde_json::json!({
1432                "name": name,
1433                "schema_ref": schema_ref,
1434                "declared": declared,
1435                "suggestion": suggestion,
1436            }),
1437            EngineError::HashMismatch {
1438                id,
1439                current,
1440                is_stub,
1441            } => serde_json::json!({
1442                "id": id,
1443                "current": current,
1444                "is_stub": is_stub,
1445            }),
1446            EngineError::HasIncomingRefs { id, referrers } => {
1447                let referrers_json: Vec<_> = referrers
1448                    .iter()
1449                    .map(|r| {
1450                        serde_json::json!({
1451                            "from_id": r.from_id,
1452                            "rel_types": r.rel_types,
1453                            "mem": r.mem,
1454                        })
1455                    })
1456                    .collect();
1457                serde_json::json!({ "id": id, "referrers": referrers_json })
1458            }
1459            EngineError::MemHasIncomingRefs { mem, referrers } => {
1460                let referrers_json: Vec<_> = referrers
1461                    .iter()
1462                    .map(|r| {
1463                        serde_json::json!({
1464                            "from_id": r.from_id,
1465                            "rel_types": r.rel_types,
1466                            "mem": r.mem,
1467                        })
1468                    })
1469                    .collect();
1470                serde_json::json!({ "mem": mem, "referrers": referrers_json })
1471            }
1472            EngineError::WikiLinkWithoutRelation { from_id, missing } => serde_json::json!({
1473                "from_id": from_id,
1474                "missing": missing,
1475            }),
1476            EngineError::RelationHasBodyLinks {
1477                from_id,
1478                to_id,
1479                rel_type,
1480                body_links,
1481            } => {
1482                serde_json::json!({
1483                    "from_id": from_id,
1484                    "to_id": to_id,
1485                    "rel_type": rel_type,
1486                    "body_links": body_links,
1487                })
1488            }
1489            EngineError::InvalidEntityId { id, reason } => {
1490                serde_json::json!({ "id": id, "reason": reason })
1491            }
1492            EngineError::InvalidWikiLinkTarget {
1493                raw,
1494                suggested,
1495                section,
1496                link_source,
1497                reason,
1498            } => {
1499                // Surface
1500                // the slug-form retry under `proposed_slug`, mirroring the
1501                // title gate's `INVALID_TITLE` recovery key, so an agent
1502                // that wrote `[[Idempotency]]` finds `idempotency` under
1503                // the same field it already knows. `suggested` is the
1504                // general hint and is sometimes a colon-form
1505                // (`mem:slug`) for the ambiguous-grammar case — only
1506                // promote it to `proposed_slug` when it's a bare slug.
1507                let proposed_slug = suggested
1508                    .as_ref()
1509                    .filter(|s| !s.contains(':') && !s.contains("--"));
1510                serde_json::json!({
1511                    "raw": raw,
1512                    "suggested": suggested,
1513                    "proposed_slug": proposed_slug,
1514                    "section": section,
1515                    "source": link_source,
1516                    "reason": reason,
1517                })
1518            }
1519            EngineError::InvalidWikiLinkMem {
1520                raw,
1521                section,
1522                reason,
1523            } => {
1524                serde_json::json!({ "raw": raw, "section": section, "reason": reason })
1525            }
1526            EngineError::ConflictingSectionModes { section, modes } => {
1527                serde_json::json!({ "section": section, "modes": modes })
1528            }
1529            EngineError::SetAndUnsetConflict { keys } => serde_json::json!({ "keys": keys }),
1530            EngineError::RequiredFieldUnset {
1531                field,
1532                entity_type,
1533                field_description,
1534                enum_values,
1535                type_write_rules,
1536                // `on_create` is a prose-dispatch
1537                // discriminator only; agents branch on the typed
1538                // `REQUIRED_FIELD_UNSET` code, not on this field.
1539                on_create: _,
1540                missing,
1541            } => {
1542                // `details.missing[]` carries every required-no-
1543                // default field unset on the create path so an
1544                // agent fixes the whole set in one retry. Each
1545                // entry echoes the type-level `write_rules` for
1546                // self-containment. Empty on the unset path.
1547                let missing_json: Vec<_> = missing
1548                    .iter()
1549                    .map(|m| {
1550                        serde_json::json!({
1551                            "field": m.key,
1552                            "description": m.description,
1553                            "enum_values": m.enum_values,
1554                            "write_rules": type_write_rules,
1555                        })
1556                    })
1557                    .collect();
1558                serde_json::json!({
1559                    "field": field,
1560                    "entity_type": entity_type,
1561                    "field_description": field_description,
1562                    "enum_values": enum_values,
1563                    "type_write_rules": type_write_rules,
1564                    "missing": missing_json,
1565                })
1566            }
1567            EngineError::MissingRequiredSection {
1568                entity_type,
1569                missing_count,
1570                sections,
1571                type_guidance,
1572                pre_announced_missing_fields,
1573            } => {
1574                let sections_json: Vec<_> = sections
1575                    .iter()
1576                    .map(|s| {
1577                        serde_json::json!({
1578                            "entity_type": s.entity_type,
1579                            "key": s.key,
1580                            "heading": s.heading,
1581                            "write_rules": s.write_rules,
1582                        })
1583                    })
1584                    .collect();
1585                let mut details = serde_json::json!({
1586                    "entity_type": entity_type,
1587                    "missing_count": missing_count,
1588                    "sections": sections_json,
1589                    "type_guidance": type_guidance,
1590                });
1591                // Cross-gate pre-announcement rides additionally and
1592                // only when non-empty: the established payload above
1593                // keeps its exact shape, and a single-gate refusal
1594                // stays byte-identical to the pre-announcement-free
1595                // form. Element shape mirrors `REQUIRED_FIELD_UNSET`'s
1596                // `details.missing[]` so one decoder reads both.
1597                if !pre_announced_missing_fields.is_empty() {
1598                    let type_rules = type_guidance.get(entity_type).cloned().unwrap_or_default();
1599                    let missing_json: Vec<_> = pre_announced_missing_fields
1600                        .iter()
1601                        .map(|m| {
1602                            serde_json::json!({
1603                                "field": m.key,
1604                                "description": m.description,
1605                                "enum_values": m.enum_values,
1606                                "write_rules": type_rules,
1607                            })
1608                        })
1609                        .collect();
1610                    details["pre_announced"] = serde_json::json!({
1611                        "required_field_unset": { "missing": missing_json }
1612                    });
1613                }
1614                details
1615            }
1616            EngineError::PatchSectionEmpty { section } => serde_json::json!({ "section": section }),
1617            EngineError::PatchOldNotFound {
1618                section,
1619                current_content,
1620                truncated,
1621                found_in_sections,
1622            } => {
1623                serde_json::json!({
1624                    "section": section,
1625                    "current_content": current_content,
1626                    "truncated": truncated,
1627                    "found_in_sections": found_in_sections,
1628                })
1629            }
1630            EngineError::RelationshipCycle {
1631                rel_type,
1632                from,
1633                to,
1634                existing_path,
1635                path_truncated,
1636                acyclic_set,
1637                existing_path_rel_types,
1638            } => {
1639                let path_json: Vec<_> = existing_path.iter().map(|id| id.to_string()).collect();
1640                let mut d = serde_json::json!({
1641                    "rel_type": rel_type,
1642                    "from": from.to_string(),
1643                    "to": to.to_string(),
1644                    "existing_path": path_json,
1645                    "path_truncated": path_truncated,
1646                });
1647                // Additive: only set refusals carry the set echo and
1648                // the per-hop rel-types; single-rel-type refusals stay
1649                // byte-identical.
1650                if let Some(set) = acyclic_set {
1651                    d["acyclic_set"] = serde_json::json!(set);
1652                }
1653                if let Some(rels) = existing_path_rel_types {
1654                    d["existing_path_rel_types"] = serde_json::json!(rels);
1655                }
1656                d
1657            }
1658            EngineError::CrossMemLinkNotAllowed { from_mem, to_mem } => {
1659                serde_json::json!({ "from_mem": from_mem, "to_mem": to_mem })
1660            }
1661            EngineError::EmptyUpdate { id } => {
1662                serde_json::json!({
1663                    "id": id,
1664                    "recognised_keys": RECOGNISED_MUTATION_KEYS,
1665                })
1666            }
1667            EngineError::RenameBlockedByCrossMemPolicy {
1668                from_mem,
1669                blocked_referrers,
1670            } => {
1671                let entries: Vec<_> = blocked_referrers
1672                    .iter()
1673                    .map(|r| {
1674                        serde_json::json!({
1675                            "from_mem": r.from_mem,
1676                            "to_mem": r.to_mem,
1677                            "count": r.count,
1678                        })
1679                    })
1680                    .collect();
1681                serde_json::json!({
1682                    "from_mem": from_mem,
1683                    "blocked_referrers": entries,
1684                })
1685            }
1686            EngineError::CrossMemTargetNotFound {
1687                target_id,
1688                target_mem,
1689            } => {
1690                serde_json::json!({ "target_id": target_id, "target_mem": target_mem })
1691            }
1692            EngineError::UnterminatedFenceInStoredBody {
1693                id,
1694                section,
1695                fence,
1696                swallowed,
1697            } => serde_json::json!({
1698                "id": id,
1699                "section": section,
1700                "fence": fence,
1701                "swallowed_sections": swallowed,
1702                "expected": format!(
1703                    "supply `sections` with a corrected body for '{section}': lift the swallowed \
1704                     content back into its own sections and close the fence"
1705                ),
1706            }),
1707            EngineError::Validation(v) => v.details(),
1708            EngineError::MissingRequiredDescription {
1709                rel_type,
1710                from_id,
1711                to_id,
1712            } => {
1713                serde_json::json!({
1714                    "rel_type": rel_type,
1715                    "from_id": from_id,
1716                    "to_id": to_id,
1717                })
1718            }
1719            EngineError::DescriptionNotPermitted {
1720                rel_type,
1721                from_id,
1722                to_id,
1723            } => {
1724                serde_json::json!({
1725                    "rel_type": rel_type,
1726                    "from_id": from_id,
1727                    "to_id": to_id,
1728                })
1729            }
1730            EngineError::RelationManualAuthoringForbidden {
1731                rel_type,
1732                from_id,
1733                to_id,
1734                guidance,
1735            } => serde_json::json!({
1736                "rel_type": rel_type,
1737                "from_id": from_id,
1738                "to_id": to_id,
1739                "guidance": guidance,
1740            }),
1741            EngineError::MarkdownExportUnsupportedBackend {
1742                mem,
1743                active_backend,
1744                supported_backends,
1745            } => serde_json::json!({
1746                "mem": mem,
1747                "active_backend": active_backend,
1748                "supported_backends": supported_backends,
1749            }),
1750            EngineError::ReviewMarkNotSet { mem } => serde_json::json!({ "mem": mem }),
1751            EngineError::InvalidChangesCursor { mem, since } => serde_json::json!({
1752                "mem": mem,
1753                "since": since,
1754            }),
1755            EngineError::SchemaNotFound {
1756                mem,
1757                pin,
1758                sources,
1759                install_hint,
1760            } => {
1761                let mut details = serde_json::json!({
1762                    "mem": mem,
1763                    "pin": pin,
1764                    "sources": sources,
1765                });
1766                if let Some(path) = install_hint {
1767                    details["install_hint"] = serde_json::json!({
1768                        "authoring_package": path,
1769                        "command": format!("memstead schema install {path}"),
1770                    });
1771                }
1772                details
1773            }
1774            EngineError::SchemaPackageInvalid {
1775                name,
1776                version,
1777                message,
1778            } => serde_json::json!({
1779                "schema": format!("{name}@{version}"),
1780                "error": message,
1781            }),
1782            EngineError::InvalidAnchor(e) => {
1783                serde_json::Value::Object(e.detail().into_iter().collect::<serde_json::Map<_, _>>())
1784            }
1785            _ => serde_json::Value::Object(serde_json::Map::new()),
1786        }
1787    }
1788
1789    /// Render rich, fully-inlined recovery prose for the agent-visible
1790    /// text channel.
1791    ///
1792    /// Warnings
1793    /// already render their structured payload inline via
1794    /// `WarningHint::Display`; pre-fix errors with rich payloads
1795    /// collapsed to `Display` plus `format_inline_list_overflow`'s
1796    /// "+N more — see details.X" pointer pointing at a structured
1797    /// channel the agent's MCP client doesn't surface to the model.
1798    /// This method gives errors the same prose-rich rendering warnings
1799    /// have, so `result.content[0].text` is self-recoverable.
1800    ///
1801    /// Variants whose `Display` already inlines every recovery field
1802    /// (no truncation, no "see details" pointer) inherit the default
1803    /// trait impl — they just `to_string()`. Override only the
1804    /// variants that need richer rendering than `Display` provides.
1805    ///
1806    /// The structured `details()` channel is unchanged; consumers
1807    /// branching on `code` continue to receive the typed shape. The
1808    /// `Display` impl stays terse for logs, tracing, panic messages,
1809    /// and other non-agent consumers.
1810    pub fn prose_render(&self) -> String {
1811        match self {
1812            // The echoed conforming `example` is the highest-leverage
1813            // part of a format refusal — inline it on the text channel
1814            // too, not only under `details.example`.
1815            EngineError::SectionFormatRefused { violation, .. } => {
1816                let base = self.to_string();
1817                match violation.example() {
1818                    Some(example) => {
1819                        format!("{base}\nA conforming example:\n{}", example.trim_end())
1820                    }
1821                    None => base,
1822                }
1823            }
1824            EngineError::HasIncomingRefs { id, referrers } => {
1825                let inline = render_referrers_inline(referrers);
1826                format!(
1827                    "entity {id} has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
1828                    n = referrers.len(),
1829                )
1830            }
1831            EngineError::MemHasIncomingRefs { mem, referrers } => {
1832                let inline = render_referrers_inline(referrers);
1833                format!(
1834                    "mem `{mem}` has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
1835                    n = referrers.len(),
1836                )
1837            }
1838            EngineError::WikiLinkWithoutRelation { from_id, missing } => {
1839                let inline = missing
1840                    .iter()
1841                    .map(|m| m.to_string())
1842                    .collect::<Vec<_>>()
1843                    .join(", ");
1844                format!(
1845                    "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",
1846                    n = missing.len(),
1847                )
1848            }
1849            EngineError::RelationHasBodyLinks {
1850                from_id,
1851                to_id,
1852                rel_type,
1853                body_links,
1854            } => {
1855                let inline = body_links.join(", ");
1856                format!(
1857                    "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"
1858                )
1859            }
1860            EngineError::RelationshipCycle {
1861                rel_type,
1862                from,
1863                to,
1864                existing_path,
1865                path_truncated,
1866                acyclic_set,
1867                ..
1868            } => {
1869                let path_inline = if existing_path.is_empty() {
1870                    String::from("(unavailable)")
1871                } else {
1872                    existing_path
1873                        .iter()
1874                        .map(|id| id.to_string())
1875                        .collect::<Vec<_>>()
1876                        .join(" → ")
1877                };
1878                let trunc = if *path_truncated {
1879                    " (path truncated)"
1880                } else {
1881                    ""
1882                };
1883                let subgraph = match acyclic_set {
1884                    Some(set) => format!("[{}] acyclicity-set", set.join(", ")),
1885                    None => rel_type.to_string(),
1886                };
1887                format!(
1888                    "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"
1889                )
1890            }
1891            EngineError::RequiredFieldUnset {
1892                field,
1893                entity_type,
1894                field_description,
1895                enum_values,
1896                type_write_rules,
1897                on_create,
1898                missing,
1899            } => {
1900                let desc_clause = field_description
1901                    .as_deref()
1902                    .map(|d| format!(" Field purpose: {d}."))
1903                    .unwrap_or_default();
1904                let enum_clause = if enum_values.is_empty() {
1905                    String::new()
1906                } else {
1907                    format!(" Allowed values: {}.", enum_values.join(", "))
1908                };
1909                let rules_clause = if type_write_rules.is_empty() {
1910                    String::new()
1911                } else {
1912                    format!(" Type-level write_rules: {}.", type_write_rules.join("; "))
1913                };
1914                // Path-aware wording — create
1915                // path says "not provided"; update path says "cannot
1916                // unset". Display impl shares the same dispatch via
1917                // `_required_field_unset_msg`.
1918                let lead = if *on_create {
1919                    format!(
1920                        "required metadata field '{field}' not provided — type '{entity_type}' declares the field as required and has no default for it"
1921                    )
1922                } else {
1923                    format!("cannot unset required field '{field}' for type '{entity_type}'")
1924                };
1925                // Multi-field accumulator. On the create path,
1926                // append a tail-list naming every other unset
1927                // required field so the agent's one-shot retry
1928                // covers all of them. The unset path's `missing`
1929                // is empty (or singleton), so the clause is empty
1930                // there.
1931                let tail_clause = if missing.len() > 1 {
1932                    let others: Vec<&str> =
1933                        missing.iter().skip(1).map(|m| m.key.as_str()).collect();
1934                    format!(" Also unset (declaration order): {}.", others.join(", "))
1935                } else {
1936                    String::new()
1937                };
1938                format!("{lead}.{desc_clause}{enum_clause}{rules_clause}{tail_clause}")
1939            }
1940            EngineError::MissingRequiredSection {
1941                entity_type,
1942                missing_count,
1943                sections,
1944                type_guidance,
1945                pre_announced_missing_fields,
1946            } => {
1947                let mut out = format!(
1948                    "missing {missing_count} required section(s) for type '{entity_type}':"
1949                );
1950                for s in sections {
1951                    let rules = if s.write_rules.is_empty() {
1952                        String::new()
1953                    } else {
1954                        format!(" — write_rules: {}", s.write_rules.join("; "))
1955                    };
1956                    out.push_str(&format!("\n  - '{}' ({}){rules}", s.key, s.heading));
1957                }
1958                if !type_guidance.is_empty() {
1959                    out.push_str("\nType guidance:");
1960                    for (etype, rules) in type_guidance {
1961                        if rules.is_empty() {
1962                            continue;
1963                        }
1964                        out.push_str(&format!("\n  - {etype}: {}", rules.join("; ")));
1965                    }
1966                }
1967                // Cross-gate pre-announcement on the text channel so a
1968                // consumer reading only prose still fixes both gates in
1969                // one retry.
1970                if !pre_announced_missing_fields.is_empty() {
1971                    out.push_str(
1972                        "\nPre-announced — the metadata gate will also require (supply in the same retry):",
1973                    );
1974                    for m in pre_announced_missing_fields {
1975                        let enums = if m.enum_values.is_empty() {
1976                            String::new()
1977                        } else {
1978                            format!(" (one of: {})", m.enum_values.join(", "))
1979                        };
1980                        out.push_str(&format!("\n  - '{}'{enums} — {}", m.key, m.description));
1981                    }
1982                }
1983                out
1984            }
1985            EngineError::UnterminatedFenceInStoredBody {
1986                id,
1987                section,
1988                fence,
1989                swallowed,
1990            } => {
1991                let buried = if swallowed.is_empty() {
1992                    "No declared section follows it in the file yet".to_string()
1993                } else {
1994                    format!("Buried right now: {}", swallowed.join(", "))
1995                };
1996                format!(
1997                    "entity '{id}' section '{section}' ends inside an unterminated `{fence}` code \
1998                     fence. In CommonMark an open fence runs to end of text, so the sections \
1999                     after it were absorbed into this body on the last read and are reported as \
2000                     empty. {buried}. Writing now appends the closing fence AFTER those bytes, \
2001                     sealing them inside a legitimately fenced block where nothing can tell them \
2002                     from prose the author meant to fence. Replace section '{section}' with a \
2003                     corrected body in this same call: lift the swallowed content back into its \
2004                     own sections and close the fence."
2005                )
2006            }
2007            EngineError::Validation(v) => v.prose_render(),
2008            // Variants whose `Display` already inlines every recovery
2009            // field — title invariants, hash mismatch (already explains
2010            // the stub case), unknown mem / type (already prints
2011            // declared list verbatim), cross-mem gates, stubs,
2012            // patch errors, etc. — fall back to `Display`. Logs and
2013            // tracing consumers see the same string.
2014            _ => self.to_string(),
2015        }
2016    }
2017}
2018
2019/// Inline-render every [`ReferrerInfo`] without the truncation suffix
2020/// `format_inline_list_overflow` applies. Used by
2021/// [`EngineError::prose_render`]'s `HasIncomingRefs` /
2022/// `MemHasIncomingRefs` arms — the agent text channel inlines the
2023/// full list so recovery doesn't depend on the structured channel.
2024fn render_referrers_inline(referrers: &[ReferrerInfo]) -> String {
2025    referrers
2026        .iter()
2027        .map(|r| r.to_string())
2028        .collect::<Vec<_>>()
2029        .join(", ")
2030}
2031
2032/// Format the `RequiredFieldUnset` message. The same typed code
2033/// fires from two semantically-distinct call sites:
2034///
2035/// * The create path constructs the variant when the caller didn't
2036///   supply a required metadata field. The pre-fix message ("cannot
2037///   unset required field …") was misleading because the field was
2038///   never set in the first place — `on_create: true` flips the
2039///   wording to "required metadata field … not provided".
2040/// * The update path constructs the variant when the caller passed
2041///   `metadata_unset: ["field"]` against a required field. The
2042///   pre-fix wording is correct for this path — `on_create: false`
2043///   keeps it.
2044///
2045/// Both paths share recovery (provide the field); the typed code
2046/// stays `REQUIRED_FIELD_UNSET` for code-key branching consumers.
2047fn _relationship_cycle_msg(
2048    rel_type: &str,
2049    from: &EntityId,
2050    to: &EntityId,
2051    acyclic_set: Option<&[String]>,
2052) -> String {
2053    match acyclic_set {
2054        Some(set) => format!(
2055            "creating edge {rel_type} from '{from}' to '{to}' would close a cycle in the [{}] acyclicity-set subgraph",
2056            set.join(", ")
2057        ),
2058        None => format!(
2059            "creating edge {rel_type} from '{from}' to '{to}' would close a cycle in the {rel_type} subgraph"
2060        ),
2061    }
2062}
2063
2064fn _required_field_unset_msg(field: &str, entity_type: &str, on_create: bool) -> String {
2065    if on_create {
2066        format!(
2067            "required metadata field '{field}' not provided — type '{entity_type}' declares the field as required and has no default for it"
2068        )
2069    } else {
2070        format!("cannot unset required field '{field}' for type '{entity_type}'")
2071    }
2072}
2073
2074/// Format the `HashMismatch` message. Stub-shaped entities have no
2075/// `content_hash` to compare against; rendering the empty `current:`
2076/// paren the way pre-fix code did misdirects an agent toward
2077/// hash-recovery via `memstead_entity` (which returns the same empty
2078/// hash). Surface the actual corrective action — pass
2079/// `expected_hash: ""` — instead.
2080/// Render the `SCHEMA_NOT_FOUND` message with its source-trail
2081/// summary. The trail says exactly which sources were searched and
2082/// what each held — never more (a source absent from `sources` is not
2083/// claimed searched). A right-name/wrong-version failure and a
2084/// never-installed failure are distinguishable from this sentence
2085/// alone; the structured `details.sources` stays the richer channel.
2086/// Empty `sources` (internal lookup miss) keeps the bare legacy
2087/// sentence — there was no source search to summarise.
2088fn schema_not_found_message(
2089    mem: &str,
2090    pin: &str,
2091    sources: &[SchemaSourceDiagnostic],
2092    install_hint: &Option<String>,
2093) -> String {
2094    let mut msg = format!("mem {mem}: schema pin {pin:?} did not resolve in any schema source");
2095    if sources.is_empty() {
2096        return msg;
2097    }
2098    let name = pin.split('@').next().unwrap_or(pin);
2099    let trail: Vec<String> = sources
2100        .iter()
2101        .map(|s| {
2102            if let Some(status) = s.status {
2103                format!("{} ({status})", s.source)
2104            } else if s.versions_found.is_empty() {
2105                format!("{} (nothing for {name:?})", s.source)
2106            } else {
2107                format!("{} (holds {})", s.source, s.versions_found.join(", "))
2108            }
2109        })
2110        .collect();
2111    msg.push_str(&format!(" — searched {}", trail.join(", ")));
2112    if sources.iter().any(|s| !s.versions_found.is_empty()) {
2113        // Right name, wrong version. The honest hint is version
2114        // repair, not silence: the final clause is the concrete repin
2115        // command against the newest version a source actually holds.
2116        let best = sources
2117            .iter()
2118            .flat_map(|s| &s.versions_found)
2119            .filter_map(|v| semver::Version::parse(v).ok())
2120            .max();
2121        msg.push_str(&format!(
2122            "; the name {name:?} exists at the versions listed — the pinned version is wrong, \
2123             or the pinned version was never installed"
2124        ));
2125        if let Some(best) = best {
2126            msg.push_str(&format!(
2127                "; repin to an installed version: run: memstead mem set-schema {mem} {name}@{best}"
2128            ));
2129        }
2130    } else if let Some(path) = install_hint {
2131        msg.push_str(&format!(
2132            "; an authoring package named {name:?} exists at {path:?} but is not installed — \
2133             run: memstead schema install {path}"
2134        ));
2135    } else {
2136        // Name unknown everywhere and no authoring package in sight —
2137        // the repair path is still the install path, stated without a
2138        // concrete package location because none exists to name.
2139        msg.push_str(&format!(
2140            "; no source holds any version of {name:?} — author or obtain the schema package, \
2141             then run: memstead schema install <package-dir>"
2142        ));
2143    }
2144    msg
2145}
2146
2147impl EngineError {
2148    /// Attach the schema-install hint to a `SchemaNotFound` where a
2149    /// workspace root is known: probe the root's immediate
2150    /// subdirectories for an authoring schema package (a directory the
2151    /// schema loader accepts) whose manifest name matches the pin's
2152    /// name, and record its path when NO resolution source holds any
2153    /// version of that name. Any other error variant — and any
2154    /// `SchemaNotFound` where the name IS installed at some version
2155    /// (a version mismatch is a different fix), where `sources` is
2156    /// empty (internal miss, no source search happened), or where no
2157    /// candidate package exists — passes through unchanged. Read-only:
2158    /// the probe never writes, installs, or seals anything.
2159    pub fn with_schema_install_probe(self, workspace_root: Option<&std::path::Path>) -> Self {
2160        let EngineError::SchemaNotFound {
2161            mem,
2162            pin,
2163            sources,
2164            install_hint,
2165        } = self
2166        else {
2167            return self;
2168        };
2169        let hint = if install_hint.is_some() {
2170            install_hint
2171        } else if sources.is_empty() || sources.iter().any(|s| !s.versions_found.is_empty()) {
2172            None
2173        } else {
2174            let name = pin.split('@').next().unwrap_or(&pin).to_string();
2175            workspace_root.and_then(|root| probe_authoring_package(root, &name))
2176        };
2177        EngineError::SchemaNotFound {
2178            mem,
2179            pin,
2180            sources,
2181            install_hint: hint,
2182        }
2183    }
2184}
2185
2186/// Scan `root`'s immediate subdirectories for a loadable schema
2187/// package whose manifest name is `name`. Hidden directories and the
2188/// workspace's own storage (`mem-repo`, `.memstead`) are skipped. The
2189/// full loader runs (error path only, so the cost is acceptable) — a
2190/// directory that merely LOOKS like a package but fails validation
2191/// produces no hint, because `memstead schema install` would refuse it
2192/// anyway.
2193fn probe_authoring_package(root: &std::path::Path, name: &str) -> Option<String> {
2194    let entries = std::fs::read_dir(root).ok()?;
2195    for entry in entries.flatten() {
2196        let path = entry.path();
2197        if !path.is_dir() {
2198            continue;
2199        }
2200        let dir_name = entry.file_name();
2201        let dir_name = dir_name.to_string_lossy();
2202        if dir_name.starts_with('.') || dir_name == "mem-repo" {
2203            continue;
2204        }
2205        if !path.join("schema.yaml").is_file() {
2206            continue;
2207        }
2208        if let Ok(schema) = memstead_schema::load_schema_from_dir(&path) {
2209            let (loaded_name, _) = schema.id();
2210            if loaded_name == name {
2211                return Some(path.display().to_string());
2212            }
2213        }
2214    }
2215    None
2216}
2217
2218fn _hash_mismatch_msg(id: &str, current: &str, is_stub: bool) -> String {
2219    if is_stub {
2220        format!(
2221            "hash mismatch for {id} — entity is a stub (no content_hash); pass expected_hash: \"\" to operate on stubs"
2222        )
2223    } else {
2224        format!("hash mismatch for {id} — entity was modified concurrently (current: {current})")
2225    }
2226}
2227
2228/// Errors surfaced by [`Engine::from_workspace_root`] (lean) and its
2229/// full counterpart (`memstead_git_branch::engine_from_workspace_root`).
2230///
2231/// The boot path layers three error sources: layout detection,
2232/// workspace-store load failures, per-mount backend instantiation
2233/// (folder + archive vs git-branch), and engine construction
2234/// (duplicate-mem checks). `#[from]` lifts the lower-layer types so
2235/// callers branch on a single error envelope.
2236// Variants lift lower-layer error types verbatim via `#[from]`, so the enum is
2237// as wide as its widest member. Boot errors are constructed at most once per
2238// process; boxing to equalise them would buy nothing.
2239#[allow(clippy::large_enum_variant)]
2240#[derive(Debug, thiserror::Error)]
2241pub enum BootError {
2242    /// `detect_layout` returned [`crate::Layout::Empty`] — workspace
2243    /// root has no recognised layout marker. Operator runs
2244    /// `memstead mem-repo init` rather than booting against an empty
2245    /// directory.
2246    #[error("workspace at {0} is not initialised — run `memstead mem-repo init` first")]
2247    NotInitialised(PathBuf),
2248    /// Underlying [`crate::WorkspaceStoreAdapter`] load failed
2249    /// (missing config file, parse error, format-mismatch).
2250    #[error(transparent)]
2251    Store(#[from] crate::workspace_store::StoreError),
2252    /// Per-mount backend instantiation failed. Today: a mount
2253    /// declared `MountStorage::GitBranch` while the lean boot path
2254    /// only knows folder + archive.
2255    #[error(transparent)]
2256    Instantiate(#[from] crate::workspace_store::InstantiateError),
2257    /// Engine construction failed (duplicate mem names, etc.).
2258    #[error(transparent)]
2259    Engine(#[from] EngineError),
2260}
2261
2262impl BootError {
2263    /// Stable, surface-independent error code token (UPPER_SNAKE, per
2264    /// the [`EngineError::code`] convention). Every boot failure class
2265    /// resolves to a typed code — `INTERNAL` is not producible from
2266    /// this seam. The wrapped layers each own their vocabulary:
2267    /// store-load failures delegate to
2268    /// [`crate::workspace_store::StoreError::code`], backend
2269    /// instantiation to
2270    /// [`crate::workspace_store::InstantiateError::code`], engine
2271    /// construction to [`EngineError::code`].
2272    pub fn code(&self) -> &'static str {
2273        match self {
2274            // Same token the CLI's workspace walk uses — "no
2275            // workspace here" is one condition wherever detected.
2276            BootError::NotInitialised(_) => "WORKSPACE_NOT_INITIALISED",
2277            BootError::Store(e) => e.code(),
2278            BootError::Instantiate(e) => e.code(),
2279            BootError::Engine(e) => e.code(),
2280        }
2281    }
2282
2283    /// Structured recovery payload for the boot failure, surfacing
2284    /// under `error.details` on `--json` envelopes. Engine-layer
2285    /// failures reuse [`EngineError::details`] (so e.g. a boot-time
2286    /// `SCHEMA_NOT_FOUND` ships the same `details.sources` trail the
2287    /// per-verb surfaces ship); the other layers name the offending
2288    /// path.
2289    pub fn details(&self) -> serde_json::Value {
2290        use crate::workspace_store::StoreError;
2291        match self {
2292            BootError::NotInitialised(path) => {
2293                serde_json::json!({
2294                    "path": path.display().to_string(),
2295                    "hint": { "recovery_command": "memstead mem-repo init" },
2296                })
2297            }
2298            BootError::Store(e) => match e {
2299                StoreError::NotInitialised { path }
2300                | StoreError::Io { path, .. }
2301                | StoreError::Parse { path, .. }
2302                | StoreError::FormatMismatch { path, .. }
2303                | StoreError::LegacyLayout { path, .. }
2304                | StoreError::UnknownBindingVersion { path, .. } => {
2305                    serde_json::json!({ "path": path.display().to_string() })
2306                }
2307                StoreError::LegacyProjectionStore { path } => serde_json::json!({
2308                    "path": path.display().to_string(),
2309                    "hint": { "recovery_command": "memstead projection migrate" },
2310                }),
2311                StoreError::Other(_) => serde_json::json!({}),
2312            },
2313            BootError::Instantiate(
2314                crate::workspace_store::InstantiateError::GitBranchRequiresMemRepoFeature { mem },
2315            ) => serde_json::json!({ "mem": mem }),
2316            BootError::Engine(e) => e.details(),
2317        }
2318    }
2319
2320    /// The one boot-failure message every surface prints verbatim
2321    /// (CLI stderr / `--json`, MCP boot diagnostics), so the same
2322    /// broken workspace reads identically wherever it refuses. The
2323    /// leaf error's own message carries the repair command (or states
2324    /// plainly that none exists).
2325    pub fn surface_message(&self, workspace_root: &std::path::Path) -> String {
2326        format!("init engine at {}: {self}", workspace_root.display())
2327    }
2328}
2329
2330#[cfg(test)]
2331mod plan05_subsystem_tests {
2332    use super::*;
2333
2334    /// A title-case body wiki-link refusal carries the
2335    /// slug-form retry under `proposed_slug` (mirroring `INVALID_TITLE`),
2336    /// so an agent that wrote `[[Idempotency]]` finds `idempotency` under
2337    /// the key it already knows.
2338    #[test]
2339    fn invalid_wiki_link_details_carry_proposed_slug_for_title_case() {
2340        let err = EngineError::InvalidWikiLinkTarget {
2341            raw: "Idempotency".to_string(),
2342            suggested: Some("idempotency".to_string()),
2343            section: "purpose".to_string(),
2344            link_source: "body_link".to_string(),
2345            reason: "slugs must be lowercase".to_string(),
2346        };
2347        let d = err.details();
2348        assert_eq!(d["proposed_slug"], "idempotency");
2349        assert_eq!(d["suggested"], "idempotency");
2350    }
2351
2352    /// `SCHEMA_NOT_FOUND` carries the fixed-order resolution
2353    /// diagnostics under `details.sources`: a right-name/wrong-version
2354    /// pin shows the built-in's available versions with
2355    /// `pinned_version_match = false`, and `remote` is the reserved
2356    /// `not_configured` slot. This is the agent-visible payload that
2357    /// tells the caller the name resolves but the version does not.
2358    #[test]
2359    fn schema_not_found_details_carry_fixed_order_source_diagnostics() {
2360        let requested: semver::Version = "99.0.0".parse().unwrap();
2361        let sources = SchemaSourceDiagnostic::for_failed_pin("default", &requested, &[]);
2362        let err = EngineError::SchemaNotFound {
2363            mem: "specs".to_string(),
2364            pin: "default@99.0.0".to_string(),
2365            sources,
2366            install_hint: None,
2367        };
2368        assert_eq!(err.code(), "SCHEMA_NOT_FOUND");
2369        let d = err.details();
2370        assert_eq!(d["mem"], "specs");
2371        assert_eq!(d["pin"], "default@99.0.0");
2372        let src = d["sources"].as_array().expect("sources is an array");
2373        let labels: Vec<&str> = src.iter().map(|s| s["source"].as_str().unwrap()).collect();
2374        assert_eq!(labels, ["local_storage", "builtin", "remote"]);
2375        // The `default` builtin exists at 1.0.0 — right name, wrong
2376        // version: builtin enumerates it but the pin does not match.
2377        let builtin = &src[1];
2378        assert!(
2379            builtin["versions_found"]
2380                .as_array()
2381                .unwrap()
2382                .iter()
2383                .any(|v| v == "1.0.0"),
2384            "builtin must enumerate default@1.0.0, got {builtin:?}",
2385        );
2386        assert_eq!(builtin["pinned_version_match"], false);
2387        // No local storage was consulted (empty `consulted` slice).
2388        assert_eq!(src[0]["versions_found"].as_array().unwrap().len(), 0);
2389        // Remote is the reserved, unenumerated slot.
2390        assert_eq!(src[2]["status"], "not_configured");
2391        assert!(
2392            src[2].get("versions_found").is_some(),
2393            "remote still ships an (empty) versions_found list",
2394        );
2395    }
2396
2397    /// The MESSAGE (not just `details`) summarises the source trail,
2398    /// and a right-name/wrong-version failure is distinguishable from
2399    /// a never-installed one without opening `details`. The message
2400    /// names exactly the sources in `sources` — never one that was
2401    /// not searched — and the empty-sources internal miss keeps the
2402    /// bare legacy sentence.
2403    #[test]
2404    fn schema_not_found_message_summarises_trail_and_distinguishes_wrong_version() {
2405        // Wrong version: the builtin catalogue holds `default@1.0.0`,
2406        // the pin asks for 99.0.0.
2407        let requested: semver::Version = "99.0.0".parse().unwrap();
2408        let wrong_version = EngineError::SchemaNotFound {
2409            mem: "specs".to_string(),
2410            pin: "default@99.0.0".to_string(),
2411            sources: SchemaSourceDiagnostic::for_failed_pin("default", &requested, &[]),
2412            install_hint: None,
2413        };
2414        let msg = wrong_version.to_string();
2415        assert!(msg.contains("searched local_storage"), "got: {msg}");
2416        assert!(msg.contains("builtin (holds"), "got: {msg}");
2417        assert!(msg.contains("remote (not_configured)"), "got: {msg}");
2418        assert!(
2419            msg.contains("the pinned version is wrong"),
2420            "wrong-version case must be named in the message: {msg}"
2421        );
2422        assert!(
2423            msg.contains("memstead mem set-schema specs default@1.3.0"),
2424            "wrong-version case ends in the concrete repin command: {msg}"
2425        );
2426
2427        // Never installed: no source holds any version of the name.
2428        let never: semver::Version = "1.0.0".parse().unwrap();
2429        let never_installed = EngineError::SchemaNotFound {
2430            mem: "specs".to_string(),
2431            pin: "no-such-schema@1.0.0".to_string(),
2432            sources: SchemaSourceDiagnostic::for_failed_pin("no-such-schema", &never, &[]),
2433            install_hint: None,
2434        };
2435        let msg2 = never_installed.to_string();
2436        assert!(
2437            msg2.contains("nothing for \"no-such-schema\""),
2438            "never-installed case names the empty sources: {msg2}"
2439        );
2440        assert!(
2441            !msg2.contains("the pinned version is wrong"),
2442            "never-installed must NOT claim a version mismatch: {msg2}"
2443        );
2444        assert!(
2445            msg2.contains("memstead schema install <package-dir>"),
2446            "never-installed (no probe) still names the install path: {msg2}"
2447        );
2448        assert_ne!(msg, msg2, "the two failures are distinguishable");
2449
2450        // Internal lookup miss (empty sources): bare legacy sentence,
2451        // no trail is claimed.
2452        let internal = EngineError::SchemaNotFound {
2453            mem: "specs".to_string(),
2454            pin: "x@1.0.0".to_string(),
2455            sources: Vec::new(),
2456            install_hint: None,
2457        };
2458        assert_eq!(
2459            internal.to_string(),
2460            "mem specs: schema pin \"x@1.0.0\" did not resolve in any schema source",
2461        );
2462    }
2463
2464    /// The install-hint probe attaches the authoring-package pointer
2465    /// exactly when a loadable package with the pin's name sits in the
2466    /// workspace root while NO source holds any version of the name —
2467    /// and stays silent for a version mismatch (installed at another
2468    /// version), for an absent package, and for a non-`SchemaNotFound`
2469    /// error.
2470    #[test]
2471    fn schema_install_probe_hints_only_for_uninstalled_authoring_package() {
2472        // Workspace root carrying the memstead-schema `examples/minimal`
2473        // package (name `recipe`) as an authoring folder.
2474        let tmp = tempfile::TempDir::new().unwrap();
2475        let src_pkg = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2476            .join("../memstead-schema/examples/minimal");
2477        let dst = tmp.path().join("recipe");
2478        std::fs::create_dir_all(dst.join("types")).unwrap();
2479        std::fs::copy(src_pkg.join("schema.yaml"), dst.join("schema.yaml")).unwrap();
2480        for entry in std::fs::read_dir(src_pkg.join("types")).unwrap().flatten() {
2481            std::fs::copy(entry.path(), dst.join("types").join(entry.file_name())).unwrap();
2482        }
2483
2484        let requested: semver::Version = "0.1.0".parse().unwrap();
2485        let not_found = || EngineError::SchemaNotFound {
2486            mem: "specs".to_string(),
2487            pin: "recipe@0.1.0".to_string(),
2488            sources: SchemaSourceDiagnostic::for_failed_pin("recipe", &requested, &[]),
2489            install_hint: None,
2490        };
2491
2492        // Uninstalled + authored → hint attaches, message + details
2493        // point at `memstead schema install`.
2494        let hinted = not_found().with_schema_install_probe(Some(tmp.path()));
2495        let msg = hinted.to_string();
2496        assert!(
2497            msg.contains("memstead schema install"),
2498            "hint must name the install command: {msg}"
2499        );
2500        assert!(msg.contains("recipe"), "hint names the package: {msg}");
2501        let d = hinted.details();
2502        assert!(
2503            d["install_hint"]["command"]
2504                .as_str()
2505                .unwrap()
2506                .starts_with("memstead schema install"),
2507            "details carry the hint: {d}"
2508        );
2509
2510        // No workspace root → no concrete package hint; the message
2511        // falls back to the generic install path.
2512        let no_root = not_found().with_schema_install_probe(None);
2513        let no_root_msg = no_root.to_string();
2514        assert!(
2515            no_root_msg.contains("memstead schema install <package-dir>"),
2516            "generic install path without a probe hit: {no_root_msg}"
2517        );
2518        assert!(
2519            !no_root_msg.contains(&tmp.path().display().to_string()),
2520            "no concrete package path without a probe hit: {no_root_msg}"
2521        );
2522
2523        // No such authoring package → same generic fallback, no
2524        // concrete path.
2525        let other_tmp = tempfile::TempDir::new().unwrap();
2526        let absent = not_found().with_schema_install_probe(Some(other_tmp.path()));
2527        let absent_msg = absent.to_string();
2528        assert!(
2529            absent_msg.contains("memstead schema install <package-dir>"),
2530            "generic install path when no package exists: {absent_msg}"
2531        );
2532        assert!(
2533            !absent_msg.contains(&other_tmp.path().display().to_string()),
2534            "no concrete package path when no package exists: {absent_msg}"
2535        );
2536
2537        // Version mismatch against an installed package (some source
2538        // holds versions of the name) → no hint even though the
2539        // authoring package exists.
2540        let mismatch_req: semver::Version = "99.0.0".parse().unwrap();
2541        let mismatch = EngineError::SchemaNotFound {
2542            mem: "specs".to_string(),
2543            pin: "default@99.0.0".to_string(),
2544            sources: SchemaSourceDiagnostic::for_failed_pin("default", &mismatch_req, &[]),
2545            install_hint: None,
2546        }
2547        .with_schema_install_probe(Some(tmp.path()));
2548        let mismatch_msg = mismatch.to_string();
2549        assert!(
2550            !mismatch_msg.contains("schema install"),
2551            "version mismatch must not hint install: {mismatch_msg}"
2552        );
2553        assert!(
2554            mismatch_msg.contains("memstead mem set-schema specs default@1.3.0"),
2555            "version mismatch hints version repair instead: {mismatch_msg}"
2556        );
2557
2558        // Non-SchemaNotFound errors pass through unchanged.
2559        let other = EngineError::UnknownMem("specs".to_string())
2560            .with_schema_install_probe(Some(tmp.path()));
2561        assert_eq!(other.code(), "UNKNOWN_MEM");
2562    }
2563
2564    /// The ambiguous-grammar case suggests a
2565    /// colon-form (`mem:slug`), which is NOT a bare slug — it must not
2566    /// be promoted to `proposed_slug`.
2567    #[test]
2568    fn invalid_wiki_link_colon_form_suggestion_is_not_a_proposed_slug() {
2569        let err = EngineError::InvalidWikiLinkTarget {
2570            raw: "team/sub--thing".to_string(),
2571            suggested: Some("team/sub:thing".to_string()),
2572            section: "purpose".to_string(),
2573            link_source: "body_link".to_string(),
2574            reason: "ambiguous".to_string(),
2575        };
2576        let d = err.details();
2577        assert!(
2578            d["proposed_slug"].is_null(),
2579            "colon-form must not be a proposed_slug: {d}"
2580        );
2581        assert_eq!(d["suggested"], "team/sub:thing");
2582    }
2583
2584    /// A bad `--since` cursor is the typed `INVALID_CURSOR`
2585    /// code carrying the untruncated SHA in `details.since`.
2586    #[test]
2587    fn invalid_changes_cursor_code_and_details() {
2588        let sha = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
2589        let err = EngineError::InvalidChangesCursor {
2590            mem: "specs".to_string(),
2591            since: sha.to_string(),
2592        };
2593        assert_eq!(err.code(), "INVALID_CURSOR");
2594        let d = err.details();
2595        assert_eq!(d["mem"], "specs");
2596        assert_eq!(
2597            d["since"], sha,
2598            "the offending SHA must ride untruncated in details"
2599        );
2600    }
2601}
2602
2603#[cfg(test)]
2604mod inline_list_tests {
2605    use super::*;
2606
2607    #[test]
2608    fn empty_list_renders_empty_string() {
2609        let items: Vec<String> = Vec::new();
2610        assert_eq!(format_inline_list_overflow(&items, "x"), "");
2611    }
2612
2613    #[test]
2614    fn list_at_cap_renders_all_no_overflow_suffix() {
2615        let items = vec!["a".to_string(), "b".to_string(), "c".to_string()];
2616        assert_eq!(format_inline_list_overflow(&items, "x"), "a, b, c");
2617    }
2618
2619    #[test]
2620    fn list_under_cap_renders_all_no_overflow_suffix() {
2621        let items = vec!["a".to_string(), "b".to_string()];
2622        assert_eq!(format_inline_list_overflow(&items, "x"), "a, b");
2623    }
2624
2625    #[test]
2626    fn list_over_cap_appends_count_and_field_name() {
2627        let items: Vec<String> = (0..23).map(|i| format!("id{i}")).collect();
2628        let rendered = format_inline_list_overflow(&items, "referrers");
2629        assert_eq!(rendered, "id0, id1, id2 +20 more — see details.referrers");
2630    }
2631
2632    #[test]
2633    fn list_six_items_truncates_to_three_plus_three() {
2634        let items: Vec<String> = (0..6).map(|i| format!("t{i}")).collect();
2635        let rendered = format_inline_list_overflow(&items, "missing");
2636        assert_eq!(rendered, "t0, t1, t2 +3 more — see details.missing");
2637    }
2638
2639    #[test]
2640    fn has_incoming_refs_display_inlines_first_three_referrer_ids() {
2641        let referrers: Vec<ReferrerInfo> = (0..23)
2642            .map(|i| ReferrerInfo {
2643                from_id: format!("specs--ref{i}"),
2644                rel_types: vec!["USES".to_string()],
2645                mem: "specs".to_string(),
2646            })
2647            .collect();
2648        let err = EngineError::HasIncomingRefs {
2649            id: "specs--hub".to_string(),
2650            referrers,
2651        };
2652        let s = err.to_string();
2653        // First three ids appear inline; the rest are summarised plus a
2654        // pointer to `details.referrers` on the structured channel.
2655        assert!(
2656            s.contains("specs--ref0, specs--ref1, specs--ref2"),
2657            "got: {s}"
2658        );
2659        assert!(s.contains("+20 more — see details.referrers"), "got: {s}");
2660        // Pre-fix the message only carried the count; check the count
2661        // still appears so callers parsing it for "N references" keep
2662        // working.
2663        assert!(s.contains("23 incoming reference"), "got: {s}");
2664    }
2665
2666    #[test]
2667    fn wiki_link_without_relation_display_lists_all_when_under_cap() {
2668        let missing = vec![
2669            MissingWikiLink {
2670                section_key: "specifies".to_string(),
2671                target_id: "specs--a".to_string(),
2672            },
2673            MissingWikiLink {
2674                section_key: "specifies".to_string(),
2675                target_id: "specs--b".to_string(),
2676            },
2677            MissingWikiLink {
2678                section_key: "rationale".to_string(),
2679                target_id: "specs--c".to_string(),
2680            },
2681        ];
2682        let err = EngineError::WikiLinkWithoutRelation {
2683            from_id: "specs--src".to_string(),
2684            missing,
2685        };
2686        let s = err.to_string();
2687        assert!(s.contains("specifies→specs--a"), "got: {s}");
2688        assert!(s.contains("specifies→specs--b"), "got: {s}");
2689        assert!(s.contains("rationale→specs--c"), "got: {s}");
2690        assert!(!s.contains("more — see details"), "got: {s}");
2691    }
2692
2693    #[test]
2694    fn wiki_link_without_relation_display_truncates_at_cap_with_pointer() {
2695        let missing: Vec<MissingWikiLink> = (0..6)
2696            .map(|i| MissingWikiLink {
2697                section_key: format!("s{i}"),
2698                target_id: format!("specs--t{i}"),
2699            })
2700            .collect();
2701        let err = EngineError::WikiLinkWithoutRelation {
2702            from_id: "specs--src".to_string(),
2703            missing,
2704        };
2705        let s = err.to_string();
2706        assert!(
2707            s.contains("s0→specs--t0, s1→specs--t1, s2→specs--t2"),
2708            "got: {s}"
2709        );
2710        assert!(s.contains("+3 more — see details.missing"), "got: {s}");
2711    }
2712
2713    #[test]
2714    fn relation_has_body_links_display_inlines_section_keys() {
2715        let err = EngineError::RelationHasBodyLinks {
2716            from_id: "specs--src".to_string(),
2717            to_id: "specs--dst".to_string(),
2718            rel_type: "USES".to_string(),
2719            body_links: vec!["specifies".to_string(), "rationale".to_string()],
2720        };
2721        let s = err.to_string();
2722        assert!(s.contains("specifies, rationale"), "got: {s}");
2723        assert!(!s.contains("more — see details"), "got: {s}");
2724    }
2725
2726    // --- prose_render -----------------------------------------------
2727    // The text
2728    // channel inlines full recovery payloads (no `+N more — see
2729    // details.X` pointer). Display stays terse for logs; prose_render
2730    // is the rich method MCP / CLI surfaces call for `content[0].text`.
2731
2732    #[test]
2733    fn prose_render_has_incoming_refs_inlines_every_referrer() {
2734        let referrers = (0..7)
2735            .map(|i| ReferrerInfo {
2736                from_id: format!("specs--r{i}"),
2737                rel_types: vec!["DEPENDS_ON".to_string()],
2738                mem: "specs".to_string(),
2739            })
2740            .collect();
2741        let err = EngineError::HasIncomingRefs {
2742            id: "specs--target".to_string(),
2743            referrers,
2744        };
2745        let prose = err.prose_render();
2746        for i in 0..7 {
2747            assert!(
2748                prose.contains(&format!("specs--r{i}")),
2749                "every referrer must appear inline; missing r{i} in: {prose}"
2750            );
2751        }
2752        assert!(!prose.contains("see details"), "got: {prose}");
2753        // Display stays terse with the overflow suffix.
2754        let display = err.to_string();
2755        assert!(
2756            display.contains("+4 more — see details.referrers"),
2757            "got: {display}"
2758        );
2759    }
2760
2761    #[test]
2762    fn prose_render_required_field_unset_inlines_field_description_and_rules() {
2763        // Update-path semantic: `on_create: false` → "cannot unset".
2764        let err = EngineError::RequiredFieldUnset {
2765            field: "verified_on".to_string(),
2766            entity_type: "requirement".to_string(),
2767            field_description: Some("ISO-8601 date the requirement was last validated".to_string()),
2768            enum_values: vec![],
2769            type_write_rules: vec!["bump verified_on on every status change".to_string()],
2770            on_create: false,
2771            missing: Vec::new(),
2772        };
2773        let prose = err.prose_render();
2774        assert!(
2775            prose.contains("ISO-8601 date"),
2776            "field_description missing: {prose}"
2777        );
2778        assert!(
2779            prose.contains("bump verified_on"),
2780            "type_write_rules missing: {prose}"
2781        );
2782        assert!(!prose.contains("see details"), "got: {prose}");
2783        assert!(
2784            prose.contains("cannot unset"),
2785            "update-path wording must say 'cannot unset': {prose}"
2786        );
2787    }
2788
2789    /// Create
2790    /// path renders "not provided" instead of "cannot unset" — the
2791    /// pre-fix wording was misleading on a path where nothing was
2792    /// ever set in the first place.
2793    #[test]
2794    fn prose_render_required_field_unset_create_path_uses_not_provided_wording() {
2795        let err = EngineError::RequiredFieldUnset {
2796            field: "verified_on".to_string(),
2797            entity_type: "requirement".to_string(),
2798            field_description: Some("ISO-8601 date the requirement was last validated".to_string()),
2799            enum_values: vec![],
2800            type_write_rules: vec![],
2801            on_create: true,
2802            missing: Vec::new(),
2803        };
2804        let prose = err.prose_render();
2805        assert!(
2806            prose.contains("not provided"),
2807            "create-path wording must say 'not provided': {prose}"
2808        );
2809        assert!(
2810            !prose.contains("cannot unset"),
2811            "create-path wording must NOT say 'cannot unset': {prose}"
2812        );
2813        // Same Display dispatch — `to_string()` mirrors `prose_render`'s
2814        // create-path lead.
2815        let display = err.to_string();
2816        assert!(
2817            display.contains("not provided"),
2818            "Display must match: {display}"
2819        );
2820        assert!(
2821            !display.contains("cannot unset"),
2822            "Display must match: {display}"
2823        );
2824    }
2825
2826    /// The
2827    /// create-path multi-field accumulator surfaces every required-
2828    /// no-default field unset in `details.missing[]`. Each entry
2829    /// carries `{field, description, enum_values, write_rules}` so
2830    /// the agent fixes the whole set in one retry. The singular
2831    /// `details.field` echoes `missing[0].field` for back-compat.
2832    #[test]
2833    fn details_required_field_unset_multi_field_envelope_shape() {
2834        use crate::runtime_validator::MissingRequiredField;
2835        let err = EngineError::RequiredFieldUnset {
2836            field: "decided_on".to_string(),
2837            entity_type: "decision".to_string(),
2838            field_description: Some("Date the decision was accepted. ISO YYYY-MM-DD.".to_string()),
2839            enum_values: vec![],
2840            type_write_rules: vec!["status transitions: proposed → accepted".to_string()],
2841            on_create: true,
2842            missing: vec![
2843                MissingRequiredField {
2844                    entity_type: "decision".to_string(),
2845                    key: "decided_on".to_string(),
2846                    description: "Date the decision was accepted. ISO YYYY-MM-DD.".to_string(),
2847                    enum_values: vec![],
2848                },
2849                MissingRequiredField {
2850                    entity_type: "decision".to_string(),
2851                    key: "deciders".to_string(),
2852                    description: "Who made the call. Comma-separated handles.".to_string(),
2853                    enum_values: vec![],
2854                },
2855            ],
2856        };
2857        let details = err.details();
2858        // Back-compat: singular `field` echoes the first-missing entry.
2859        assert_eq!(details["field"].as_str(), Some("decided_on"));
2860        // Multi-field accumulator surfaces every entry in
2861        // declaration order.
2862        let missing = details["missing"].as_array().expect("missing[] array");
2863        assert_eq!(missing.len(), 2);
2864        assert_eq!(missing[0]["field"].as_str(), Some("decided_on"));
2865        assert_eq!(missing[1]["field"].as_str(), Some("deciders"));
2866        // First entry's `field` agrees with the singular shape.
2867        assert_eq!(details["field"], missing[0]["field"]);
2868        // Per-entry `write_rules` echoes the type-level rules for
2869        // self-containment.
2870        assert_eq!(missing[0]["write_rules"], details["type_write_rules"]);
2871        // Prose mentions both field names so the agent reading the
2872        // text channel sees the whole set without crossing into the
2873        // structured channel.
2874        let prose = err.prose_render();
2875        assert!(prose.contains("decided_on"), "got: {prose}");
2876        assert!(prose.contains("deciders"), "got: {prose}");
2877    }
2878
2879    /// The unset path's singular shape is
2880    /// preserved — `missing[]` is empty (the user targeted one field
2881    /// by definition); the singular fields above are authoritative.
2882    /// The typed code stays `REQUIRED_FIELD_UNSET`.
2883    #[test]
2884    fn details_required_field_unset_singular_shape_for_unset_path() {
2885        let err = EngineError::RequiredFieldUnset {
2886            field: "decided_on".to_string(),
2887            entity_type: "decision".to_string(),
2888            field_description: Some("…".to_string()),
2889            enum_values: vec![],
2890            type_write_rules: vec![],
2891            on_create: false,
2892            missing: Vec::new(),
2893        };
2894        let details = err.details();
2895        assert_eq!(details["field"].as_str(), Some("decided_on"));
2896        let missing = details["missing"]
2897            .as_array()
2898            .expect("missing[] array present");
2899        assert!(missing.is_empty(), "unset-path missing[] must be empty");
2900        assert_eq!(err.code(), "REQUIRED_FIELD_UNSET");
2901    }
2902
2903    #[test]
2904    fn prose_render_missing_required_section_enumerates_each_section_with_write_rules() {
2905        use crate::runtime_validator::MissingRequiredSection;
2906        let sections = vec![
2907            MissingRequiredSection {
2908                entity_type: "spec".to_string(),
2909                key: "purpose".to_string(),
2910                heading: "Purpose".to_string(),
2911                write_rules: vec!["one-sentence statement of intent".to_string()],
2912            },
2913            MissingRequiredSection {
2914                entity_type: "spec".to_string(),
2915                key: "scope".to_string(),
2916                heading: "Scope".to_string(),
2917                write_rules: vec!["what is in and out of scope".to_string()],
2918            },
2919        ];
2920        let mut type_guidance: std::collections::BTreeMap<String, Vec<String>> = Default::default();
2921        type_guidance.insert(
2922            "spec".to_string(),
2923            vec!["specs are immutable once stable".to_string()],
2924        );
2925        let err = EngineError::MissingRequiredSection {
2926            entity_type: "spec".to_string(),
2927            missing_count: 2,
2928            sections,
2929            type_guidance,
2930            pre_announced_missing_fields: Vec::new(),
2931        };
2932        let prose = err.prose_render();
2933        assert!(prose.contains("purpose"), "got: {prose}");
2934        assert!(prose.contains("scope"), "got: {prose}");
2935        assert!(
2936            prose.contains("one-sentence statement of intent"),
2937            "got: {prose}"
2938        );
2939        assert!(
2940            prose.contains("specs are immutable once stable"),
2941            "got: {prose}"
2942        );
2943        assert!(!prose.contains("see details"), "got: {prose}");
2944    }
2945
2946    #[test]
2947    fn prose_render_relationship_cycle_inlines_existing_path() {
2948        use crate::entity::EntityId;
2949        let path = vec![
2950            EntityId::canonical("specs--a"),
2951            EntityId::canonical("specs--b"),
2952            EntityId::canonical("specs--c"),
2953            EntityId::canonical("specs--a"),
2954        ];
2955        let err = EngineError::RelationshipCycle {
2956            rel_type: "PART_OF".to_string(),
2957            from: EntityId::canonical("specs--a"),
2958            to: EntityId::canonical("specs--c"),
2959            existing_path: path,
2960            path_truncated: false,
2961            acyclic_set: None,
2962            existing_path_rel_types: None,
2963        };
2964        let prose = err.prose_render();
2965        assert!(
2966            prose.contains("specs--a → specs--b → specs--c → specs--a"),
2967            "got: {prose}"
2968        );
2969        assert!(!prose.contains("see details"), "got: {prose}");
2970    }
2971
2972    #[test]
2973    fn prose_render_falls_back_to_display_for_trivial_variants() {
2974        // ReadOnlyMount has no list payload — Display already inlines
2975        // the recovery context.
2976        let err = EngineError::ReadOnlyMount("archive-2024".to_string());
2977        assert_eq!(err.prose_render(), err.to_string());
2978    }
2979
2980    /// A slug collision names the occupying title on both channels —
2981    /// two distinct titles can derive one id, and the id alone does
2982    /// not tell the caller which one is already there.
2983    #[test]
2984    fn already_exists_names_the_occupying_title_on_both_channels() {
2985        let err = EngineError::AlreadyExists {
2986            id: "muehle--bösenberg-grundstücks-gmbh-co-kg".to_string(),
2987            existing_title: "Bösenberg Grundstücks GmbH Co KG".to_string(),
2988            existing_is_stub: false,
2989        };
2990        assert!(
2991            err.to_string()
2992                .contains("occupied by 'Bösenberg Grundstücks GmbH Co KG'"),
2993            "got: {err}"
2994        );
2995        let details = err.details();
2996        assert_eq!(
2997            details["existing_title"],
2998            "Bösenberg Grundstücks GmbH Co KG"
2999        );
3000        assert_eq!(details["existing_is_stub"], false);
3001        assert_eq!(details["id"], "muehle--bösenberg-grundstücks-gmbh-co-kg");
3002    }
3003
3004    /// A stub occupant states it is a stub; a titleless stub must not
3005    /// render as an empty or missing title.
3006    #[test]
3007    fn already_exists_stub_occupant_never_renders_an_empty_title() {
3008        let titled = EngineError::AlreadyExists {
3009            id: "specs--x".to_string(),
3010            existing_title: "X".to_string(),
3011            existing_is_stub: true,
3012        };
3013        assert!(
3014            titled.to_string().contains("a stub titled 'X'"),
3015            "got: {titled}"
3016        );
3017
3018        let untitled = EngineError::AlreadyExists {
3019            id: "specs--x".to_string(),
3020            existing_title: String::new(),
3021            existing_is_stub: true,
3022        };
3023        let msg = untitled.to_string();
3024        assert!(msg.contains("occupied by a stub"), "got: {msg}");
3025        assert!(!msg.contains("''"), "empty title must not render: {msg}");
3026    }
3027}