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