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