Skip to main content

memstead_base/ops/warning_hint/
mod.rs

1//! The typed non-fatal warning engine operations surface: the `WarningHint` enum and the companion types its variants carry, the closed `MountUnbackedReason` vocabulary, and the custom `Serialize` that renders every variant as the uniform `{ code, message, details }` envelope.
2
3use super::*;
4
5mod display;
6mod methods;
7
8/// Typed non-fatal issue surfaced from engine operations. Serialises as the
9/// uniform `{ code, message, details }` envelope so a generic warning handler
10/// (log sink, UI, alerting) can read `code` + `message` without branching on
11/// variant. `Display` renders the agent-facing text, reachable via
12/// [`WarningHint::message`]; per-variant structured fields land under
13/// `details`, their shape keyed by `code`.
14///
15/// Shared across `CreateResult`, `RelateResult`, and `HealthSummary`. New
16/// variants are additive; they widen the enum rather than fork a per-site
17/// type so wire-level warning consumers keep a single discriminated union
18/// to branch on. The wire shape matches what [`envelope`] produces for the
19/// MCP error channel, so one decoder handles both surfaces.
20#[derive(Debug, Clone)]
21pub enum WarningHint {
22    /// A required section was empty or missing at create time. Carries
23    /// the type and section keys plus the section's own `write_rules`
24    /// so the agent can self-correct with a follow-up `memstead_update`.
25    /// Type-level `write_rules` no longer ride per warning — they
26    /// ship once at the mutation-response top level on
27    /// `type_guidance` keyed by `entity_type` (F9). Decoders look up
28    /// the guidance via `entity_type` against the top-level map.
29    MissingRequiredSection {
30        entity_type: String,
31        key: String,
32        heading: String,
33        write_rules: Vec<String>,
34    },
35    /// A required metadata field was not supplied at create time and the
36    /// schema does not auto-fill the value (no `default_value`, no
37    /// `init_timestamp`, no `auto_timestamp`). The entity still lands —
38    /// the generator may write an empty / today's-date placeholder into
39    /// the frontmatter — but the warning surfaces the gap so the agent
40    /// follows up via `memstead_update` rather than leaving the entity in a
41    /// stuck state. Payload mirrors [`Self::MissingRequiredSection`] in
42    /// shape so a single decoder handles both. Wire-equivalent shape
43    /// with `EngineError::RequiredFieldUnset`'s `details` payload, since
44    /// the recovery path is the same (read the description / allowed
45    /// enum values from the envelope rather than re-fetching the
46    /// schema).
47    MissingRequiredField {
48        entity_type: String,
49        key: String,
50        description: String,
51        enum_values: Vec<String>,
52    },
53    /// An undeclared relationship was admitted because the mem's schema
54    /// is in open mode. The caller can still suggest the name be added to
55    /// the schema vocabulary.
56    UndeclaredRelationshipOpen { rel_type: String, message: String },
57    /// `memstead_relate` was asked to add an edge that already exists. The
58    /// op is a successful no-op — the warning surfaces what would otherwise
59    /// be silent so an agent relying on `renames` / side-effects can notice
60    /// the call didn't change the graph.
61    DuplicateRelationship {
62        rel_type: String,
63        from: EntityId,
64        to: EntityId,
65    },
66    /// `memstead_relate` with `remove: true` was asked to drop an edge that
67    /// wasn't present. Successful no-op, surfaced so an agent operating on
68    /// a stale mental model sees the mismatch.
69    NoSuchRelationship {
70        rel_type: String,
71        from: EntityId,
72        to: EntityId,
73    },
74    /// An `include` key passed to `memstead_health` was outside the accepted
75    /// set. The key is ignored; the allowed list is echoed back verbatim so
76    /// an agent with a typo can correct on the next call without opening a
77    /// schema doc.
78    UnknownIncludeKey { key: String, allowed: Vec<String> },
79    /// A paged/bounded parameter exceeded its cap. The cap is authoritative
80    /// so the op still ran, but the warning surfaces what the caller
81    /// requested vs. what was served.
82    LimitClamped { requested: usize, actual: usize },
83    /// `memstead_rename` was asked to change the title but normalisation
84    /// (lowercase, diacritic-folding, punctuation-strip, hyphen-collapse)
85    /// mapped the requested title to the existing slug — so the id is
86    /// unchanged and nothing is written to disk. Surfaced so autonomous
87    /// skills don't mistake the silent short-circuit for a successful
88    /// cosmetic rewrite.
89    TitleNormalizedToSlugNoop {
90        requested_title: String,
91        current_slug: String,
92    },
93    /// The title grammar admits any single-line text, but the slug
94    /// alphabet stays narrow — this create/rename derived an id that
95    /// dropped one or more title characters (`&`, `.`, `§`, …). The
96    /// entity lands with the verbatim title; the warning keeps the
97    /// title↔id divergence visible without being fatal, naming each
98    /// distinct dropped character and the derived slug.
99    TitleCharsDroppedFromSlug {
100        title: String,
101        dropped_chars: Vec<char>,
102        slug: String,
103    },
104    /// `memstead_update` produced a post-mutation entity whose regenerated
105    /// markdown is bytes-identical to the on-disk content — no field,
106    /// section, metadata value, relation, or auto-timestamp actually
107    /// changed. The op is a successful no-op: no disk write, no
108    /// commit, `content_hash` unchanged. Surfaced so autonomous skills
109    /// branching on `write_id != ""` see an explicit signal, and
110    /// `expected_hash`-based polling stays stable across the no-op.
111    /// Mirrors `TitleNormalizedToSlugNoop` for the rename surface.
112    UpdateNoop { id: EntityId },
113    /// `memstead_search` was called with both `stub=true` and `entity_type`
114    /// set. Stubs carry no `entity_type` (they are ID-only placeholders),
115    /// so the combined filter excludes every stub — the call is an empty
116    /// set by construction. Surfaced so an agent doesn't interpret the
117    /// empty result as "no stubs of this type exist" when in fact no
118    /// stub can ever satisfy the filter. Drop `entity_type` to list stubs.
119    StubFilterExcludesAll { entity_type: String },
120    /// `memstead_search(filters: {<key>: ...})` named a filter key that the
121    /// queried type does not declare. The wire `code()` discriminates
122    /// the two outcomes, so a consumer branches on `code` alone:
123    /// - `declared_on_other_types` **empty** → no reachable schema
124    ///   declares the key → `UNKNOWN_FILTER_KEY`; the filter is truly
125    ///   ignored and the result set equals the same search without it.
126    /// - `declared_on_other_types` **non-empty** → the key is declared
127    ///   on other type(s) and the filter was applied with strict
128    ///   type-narrowing (result restricted to the declaring type(s), or
129    ///   emptied when the call scoped to a non-declaring type) →
130    ///   `FILTER_TYPE_SCOPED`.
131    ///
132    /// `declared_on_other_types` stays on the wire as enrichment, not as
133    /// the disambiguator.
134    UnknownFilterKey {
135        key: String,
136        /// `entity_type` the search call scoped to (`None` for an
137        /// unscoped call).
138        scoped_type: Option<String>,
139        /// Types where the filter IS declared, sorted alphabetically.
140        /// Empty when no reachable schema declares the key at all.
141        declared_on_other_types: Vec<String>,
142    },
143    /// `memstead_search(filters: {<field>: ...})` named a field that the
144    /// schema declares but with `filterable: none` — the filter is
145    /// ignored, the hit set is unconstrained by it.
146    FieldNotFilterable { field: String },
147    /// `memstead_search(filters: {<csv-field>: "a,b"})` passed a comma-bearing
148    /// value to a csv-array field. csv fields match a *single* member, so
149    /// the whole rendered value (e.g. the `tags: dedup,retry` an entity
150    /// displays) can never equal any one member — the filter matches
151    /// nothing. Surfaced so an agent that copied the rendered value gets a
152    /// recoverable signal (split into repeated single-member filters)
153    /// rather than an empty result indistinguishable from a true
154    /// no-match. The filter still applies as written (matches nothing);
155    /// this only adds the advisory.
156    FilterValueMultiMember { key: String, value: String },
157    /// `memstead_search(filters: {<field>: <value>})` passed a value the
158    /// schema field constrains with an `enum_values` allow-list, but the
159    /// value (or, for a csv-array field, one of its comma members) is not a
160    /// member. The filter still applies as written and matches nothing for
161    /// that value, so an empty result is otherwise indistinguishable from a
162    /// true no-match — this surfaces the typo plus the allowed values so an
163    /// agent corrects without opening the schema. Reuses the
164    /// `INVALID_ENUM_VALUE` code from the mutation surface.
165    FilterValueNotInEnum {
166        key: String,
167        value: String,
168        allowed: Vec<String>,
169    },
170    /// `memstead_search(related_to: <id>)` reached a neighbourhood larger
171    /// than the cap. The results were ranked by proximity (nearer first)
172    /// and bounded to the nearest `kept` of `total` reachable entities so a
173    /// hub can't flood the caller. Surfaced so the agent knows the
174    /// neighbourhood was truncated — narrow with `depth`/filters for more.
175    NeighbourhoodCapped { kept: usize, total: usize },
176    /// `memstead_search` trimmed the returned page to fit the token budget.
177    /// The highest-ranked `kept` hits that fit under `budget` are returned;
178    /// the rest of the page is dropped so the response stays under the MCP
179    /// transport cap. `_total` still reflects the full match count — page the
180    /// remainder with `offset`, narrow the query, or raise `token_budget`.
181    SearchResultsTruncated { kept: usize, budget: usize },
182    /// `memstead_search(range_filters: {<key>: ...})` named a key that
183    /// doesn't follow the `min_<field>` / `max_<field>` / `<field>_before`
184    /// / `<field>_after` grammar. The key is ignored.
185    RangeFilterKeyMalformed { key: String },
186    /// `memstead_search(range_filters: {<key>: ...})` named a range-filter
187    /// key whose underlying field the queried type does not declare.
188    /// Same shape and same one-code-per-outcome split as
189    /// [`Self::UnknownFilterKey`]: `code()` is `UNKNOWN_RANGE_FILTER_FIELD`
190    /// when `declared_on_other_types` is empty (truly ignored, result =
191    /// unfiltered) and `RANGE_FILTER_TYPE_SCOPED` when non-empty (applied
192    /// with strict type-narrowing). Includes the literal `key` (the
193    /// prefixed/suffixed form the caller sent) alongside the bare `field`.
194    UnknownRangeFilterField {
195        field: String,
196        /// The literal filter key the caller sent, e.g. `min_count`.
197        key: String,
198        scoped_type: Option<String>,
199        declared_on_other_types: Vec<String>,
200    },
201    /// `memstead_search(range_filters: {<field>: ...})` named a field that
202    /// the schema declares but with a filterability other than `range`.
203    /// The range filter is ignored.
204    FieldNotRangeFilterable { field: String },
205    /// `memstead_search` could not query a target mem's search index —
206    /// either the mem has no index yet (`reason: "missing_index"`)
207    /// or a tantivy execution failure surfaced (`reason:
208    /// "query_failed"` plus the error string).
209    SearchMemIndexUnavailable {
210        mem: String,
211        /// Discriminator: `"missing_index"` or `"query_failed"`.
212        reason: &'static str,
213        /// The underlying error string when `reason == "query_failed"`;
214        /// `None` for `"missing_index"`.
215        error: Option<String>,
216    },
217    // There is deliberately no `RenameSimilarityClamped` variant:
218    // out-of-range `rename_similarity` hard-refuses
219    // (`EngineError::RenameSimilarityOutOfRange` → typed
220    // `INVALID_INPUT`) rather than clamping, so the warning channel has
221    // no story to tell and the typed-warning vocabulary tracks the live
222    // wire shape.
223    /// `memstead_create` (or `memstead_rename`) received a `title` with leading
224    /// or trailing whitespace. The engine silently strips the surround
225    /// before slug derivation and storage; the warning records what the
226    /// caller sent vs. what landed so the audit trail can spot the
227    /// drift. Internal whitespace (between words) is preserved
228    /// untouched. Fully-whitespace titles are still refused at the
229    /// validator boundary (those collapse to empty).
230    TitleTrimmed { original: String, trimmed: String },
231    /// An inline wiki-link resolved to an ID of the form
232    /// `<current-mem>--<other-known-mem-suffix>--<slug>`. This is
233    /// almost always drift from a mem-rename — the author wrote
234    /// `[[plugin--slug]]` expecting `plugin` to be the mem prefix, but
235    /// the current mem is `test-mem-plugin`, so the literal
236    /// resolution nests the prefix. Detection only — the load path still
237    /// creates the stub (no silent rewrite). Fix via `memstead_update
238    /// patch_sections` to either the bare slug or the fully-qualified ID.
239    /// Emitted at load / reload / attach time and carried through
240    /// `HealthSummary.warnings`; mutation paths never emit this warning
241    /// to avoid noise on every edit.
242    SuspiciousNestedPrefix {
243        from: EntityId,
244        resolved_id: EntityId,
245        /// Stripped-and-resolved candidate via the two-pass resolver
246        /// (cross-mem lookup first, bare-slug fallback second). `None`
247        /// when no real entity was found — the author must disambiguate.
248        candidate_target: Option<EntityId>,
249        section: String,
250        /// Whether the link's prefix (`resolved_id.mem()`) is itself a
251        /// mounted mem. `true` means the link is a well-formed cross-mem
252        /// reference whose target is missing in that mem (no rename
253        /// happened); `false` means the prefix only resembles a mem
254        /// (it matches a roster member's last name segment), the
255        /// classic mem-rename drift. The message says which, instead
256        /// of calling every case rename drift: on this project's own graph all
257        /// eight recorded hits were missing targets in mounted mems.
258        prefix_mounted: bool,
259    },
260    /// Inline `[[wiki-link]]` syntax in entity section bodies parsed to
261    /// targets that did not yet resolve, so the engine auto-created stub
262    /// entities for them. A common authoring hazard: an agent illustrating
263    /// link syntax in prose (`[[example:slug]]`) inadvertently creates
264    /// ghost stubs and a REFERENCES edge from the prose entity to each.
265    /// Surfaced so the agent reviews the list and either replaces the
266    /// inline literal with a fenced/quoted form or removes the entity if
267    /// the stub was not intended. Carries the source entity id (`from`)
268    /// and every newly-stubbed `target` id created by THIS call.
269    InlineWikiLinkAutoStubbed {
270        from: EntityId,
271        stubs: Vec<EntityId>,
272    },
273    /// A body wiki-link resolved to the entity's own id, so the
274    /// alias-synthesis pass dropped the would-be self-referential edge
275    /// (F11) — a self-edge carries no navigational value and would render
276    /// as both an Outgoing and an Incoming neighbour of itself. The
277    /// create/update still succeeds (the author may have written their
278    /// own slug); this warns so the dropped link is observable, matching
279    /// the alias pass's other side-effect warnings (`AUTO_STUB_CREATED` /
280    /// `INLINE_WIKI_LINK_AUTO_STUBBED`).
281    SelfLinkIgnored { id: EntityId },
282    /// A body wiki-link crossed into a destination whose SCHEMA the
283    /// source schema declares no cross-mem entry for (and no wildcard),
284    /// so the alias-synthesis pass emitted no edge — the schema
285    /// legitimately declines it, and the write still succeeds. Before
286    /// this warning the link became inert prose SILENTLY (found by the
287    /// graph-plans 02 grading: a default-schema scratch mem citing a
288    /// planning mem, 2026-08-28); the write knows it dropped the edge,
289    /// so it says so, naming the target and the declaration gap. The
290    /// remedy is schema-side: declare the destination schema (or a
291    /// wildcard) under `cross_mem_relationships`.
292    CrossSchemaLinkUndeclared {
293        /// The entity carrying the link.
294        from: EntityId,
295        /// The link's resolved target.
296        target: EntityId,
297        /// The source mem's schema (`name@version` display form).
298        source_schema: String,
299        /// The target mem's schema name — the missing `to_schema` entry.
300        target_schema: String,
301    },
302    /// `memstead_relate` to a cross-mem target whose mem is not (yet)
303    /// mounted in the workspace. The cross-mem link policy permits
304    /// the edge, so the engine auto-stubs the target as a forward
305    /// reference — but with the target mem entirely absent from
306    /// `writable_mems()`, the stub has no `_mem_schema` resolution
307    /// and any later read sees an indeterminate-schema entity. The
308    /// warning makes the missing-mem state visible so an operator
309    /// can distinguish a typo (intended `B` but typed `b`) from a
310    /// deliberate forward reference that expects the mem to be
311    /// created later. (F4)
312    CrossMemTargetMemUncreated {
313        from_mem: String,
314        to_mem: String,
315        target_id: EntityId,
316    },
317    /// A mutation landed without a `note` field while the workspace
318    /// config's `[mutations].require_notes = true` — provenance is
319    /// best-effort, so the engine completes the commit but flags the
320    /// absence so autonomous skills can audit their coverage. The
321    /// mutation still writes to disk and produces a commit; this warning
322    /// exists purely to surface the missed opportunity for a human- /
323    /// agent-readable body line. `tool` carries the MCP tool name
324    /// (`memstead_create`, `memstead_update`, …) so consumers can attribute the
325    /// gap without re-deriving it from the response context.
326    NoteMissing { tool: String },
327    /// A create supplied a value for an auto-managed metadata field
328    /// (`init_timestamp` like `created_date`, or `auto_timestamp` like
329    /// `last_modified`); the engine owns those values, so the supplied
330    /// one was discarded and the engine value stamped instead. The
331    /// entity still lands — this warning closes the silent-drop gap so
332    /// the agent learns its input had no effect without a follow-up
333    /// read. `field` names the discarded key; `supplied` echoes the
334    /// rejected value. (The `memstead_update` path refuses the same keys
335    /// outright with `READ_ONLY_FIELD`; create's posture is
336    /// stamp-and-proceed, so it warns rather than refusing.)
337    IgnoredReadonlyField { field: String, supplied: String },
338    /// The workspace is embedded inside another git repository
339    /// (`outer_repo_root`) whose `.gitignore` does not list
340    /// `mem-repo/`. Without that ignore line, the outer repo would
341    /// either swallow `mem-repo-git` as a nested untracked tree or
342    /// (worse) record it as a submodule via gitlink — both shapes
343    /// silently corrupt the mem-repo identity.
344    ///
345    /// Surfaced from `memstead_health` so the agent / operator can fix
346    /// the outer repo's `.gitignore` (or pass `--no-gitignore` at
347    /// `memstead mem-repo init`/`migrate-from-disk` time and accept the
348    /// risk explicitly).
349    OuterRepoNotIgnoringMemRepo {
350        outer_repo_root: String,
351        workspace_root: String,
352    },
353    /// One or more `required_outgoing` blocks on the entity's type are
354    /// not yet satisfied by its post-application outgoing edges. Tier-2
355    /// — the create/update lands; the warning surfaces every unsatisfied
356    /// block in a single payload so the agent can emit one batched
357    /// `memstead_relate` follow-up.
358    MissingRequiredOutgoing {
359        entity_type: String,
360        entity_id: EntityId,
361        /// Each entry mirrors one unsatisfied `RequiredOutgoing` block:
362        /// the alternative relationship names plus the rendered
363        /// cardinality literal (`"at_least_one"`).
364        missing: Vec<MissingRequiredOutgoingBlock>,
365    },
366    /// A successful write moved a declared aggregate signal across a
367    /// threshold, in either direction. Out-of-band diagnostics beside
368    /// the success payload — never error-shaped, never changing the
369    /// mutation's success semantics (a signal crossing on a
370    /// successful write must not read as a failed write). Levels are
371    /// the wire literals `none` / `notice` / `warn`.
372    SignalThresholdCrossed {
373        entity_id: EntityId,
374        signal: String,
375        value: u64,
376        old_level: String,
377        new_level: String,
378    },
379    /// The written entity violates warn-tier declared `constraints`
380    /// of its type (e.g. `requires_when`: a field required under the
381    /// current value of another field is unset). Block-tier violations
382    /// refuse instead ([`EngineError::ConstraintUnsatisfied`]) — the
383    /// warning only ever carries `severity: warn` entries.
384    ConstraintUnsatisfied {
385        entity_type: String,
386        entity_id: EntityId,
387        violations: Vec<crate::ops::health::UnsatisfiedConstraint>,
388    },
389    /// A markdown file declared the same `## <Heading>` twice or more for a
390    /// schema-declared section key. The parser keeps the first occurrence's
391    /// body and drops the rest — the duplicate headers and their bodies are
392    /// removed from the storage value, so the next read-modify-write cycle
393    /// emits a single heading. Surfaced so the operator (or the next ingest
394    /// cycle) sees that content was discarded; common cause is an agent
395    /// appending a section instead of replacing it.
396    ///
397    /// Emitted at load / reload / attach time only; mutation paths do not
398    /// re-parse the just-written file.
399    DuplicateSectionHeading {
400        entity_id: EntityId,
401        section_key: String,
402        heading: String,
403        occurrences: usize,
404    },
405    /// The engine detected that a sibling writer (another `Engine`
406    /// instance, an out-of-band `git pull`, etc.) advanced the on-disk
407    /// HEAD of `mem` past the engine's cached `last_known_head`, so
408    /// the engine reloaded that mem's slice of the in-memory store
409    /// before serving the current call. The response carries fresh
410    /// content; the warning explains why state shifted under the
411    /// caller. Agents that need the per-entity diff call
412    /// `memstead_changes_since` with the supplied `old_head`.
413    MemReloaded {
414        mem: String,
415        old_head: String,
416        new_head: String,
417        entities_loaded: usize,
418    },
419    /// `MEM_ROSTER_CHANGED`: the mount roster changed since the engine last
420    /// reconciled it (a mem registered or unregistered by another process),
421    /// and the engine applied the change before serving this call: `added`
422    /// mems mounted cold, `removed` mems unmounted (their cached hashes are
423    /// void, an operation naming one refuses `MEM_UNMOUNTED`),
424    /// `quarantined` mems failed to mount under the boot rules and are on
425    /// the quarantine roster with their reason, `failures` names anything
426    /// that could not be applied (that part is retried next operation).
427    MemRosterChanged {
428        added: Vec<String>,
429        removed: Vec<String>,
430        quarantined: Vec<String>,
431        failures: Vec<String>,
432    },
433    /// `OUT_OF_BAND_EDITS_UNDETECTED`: this folder mem's drift cursor is its
434    /// own change ledger, which only the engine writes, so an edit made to the
435    /// files by anything else advances nothing.
436    ///
437    /// The engine keeps serving pre-edit content and `changes_since` reports
438    /// the edit as never having happened. It is not fixable cheaply: the
439    /// staleness probe runs before every operation, and turning it into a
440    /// directory walk would change the cost profile of the whole folder
441    /// backend. So the engine says it cannot detect them rather than staying
442    /// quiet, and `memstead health --include ledger` reconciles on demand.
443    ///
444    /// Never fires for a git-branch mem: its change set is a real two-tree
445    /// diff, so the condition cannot arise.
446    OutOfBandEditsUndetected { mem: String },
447    /// A destination entity of a projection binding names an in-scope source
448    /// artifact in its prose and carries no anchor on it — a claim no verify
449    /// watches on the entity's behalf. Read off the binding's findings store
450    /// (the `unanchored-mention` class the verify pass records); warn-level,
451    /// never a refusal. Remedy: anchor the artifact on the entity
452    /// (`memstead_update` with `anchors`), or exclude the artifact with a
453    /// rationale (`memstead projection exclude`).
454    UnanchoredMention {
455        mem: String,
456        binding: String,
457        entity: EntityId,
458        artifact: String,
459        section: String,
460    },
461    /// A config write found the stored config had moved on from what this
462    /// engine last observed: another writer changed it in between.
463    ///
464    /// The write still lands. It is applied to the CONFIG THAT IS THERE, not
465    /// to the engine's cached copy, so the intervening writer's fields
466    /// survive; `fields` names what they had changed. The warning exists
467    /// because a caller who set one field and finds three different is owed
468    /// the explanation on the response that did it, not in a log.
469    ///
470    /// Never fires in a single-writer workspace: the cached copy equals the
471    /// file there, so there is nothing to report.
472    ConfigWriteIntervened { mem: String, fields: Vec<String> },
473    /// A mutation verb was given an entity id without its mem prefix
474    /// and exactly one mounted mem carried an entity of that slug, so
475    /// the verb acted on that entity. Announced, never silent: the
476    /// caller learns the full id the write landed on, and a second
477    /// mem gaining the slug later turns the same call into an
478    /// `ENTITY_ID_MISSING_MEM` refusal rather than a silent retarget.
479    ShortIdResolved { given: String, resolved: EntityId },
480    /// `memstead_relate` add path landed on a not-yet-real target id and
481    /// the engine materialised a stub at that id (in-memory upsert; the
482    /// file lands when a follow-up `memstead_create` promotes the stub).
483    /// Pre-fix surfaced through a top-level `stub_warning: Option<String>`
484    /// field on the relate response — agents iterating `warnings[]` to
485    /// surface non-fatal findings silently skipped the auto-stub case.
486    /// Carries the materialised stub id so the agent can pin a
487    /// follow-up `memstead_create` (or `memstead_relate remove=true` to drop
488    /// the edge before authoring). `pending` marks the dry-run path:
489    /// the rehearsal validated the add and REPORTS the would-be stub
490    /// without writing it — the code stays `AUTO_STUB_CREATED`
491    /// (response-shape stability), only the message branches, so a
492    /// rehearsed response never claims a performed effect.
493    AutoStubCreated { stub_id: EntityId, pending: bool },
494    /// A duplicate-add `memstead_relate` on a derivation-declared
495    /// rel-type refreshed the edge's baseline —
496    /// the agent's explicit "I have reviewed the target's change; the
497    /// derivation still holds". Sidecar-only: `_hash` unchanged, the
498    /// edge unchanged; the response carries this warning so the
499    /// refresh is stated rather than a bare no-op.
500    DerivationBaselineRefreshed {
501        from: EntityId,
502        rel_type: String,
503        to: EntityId,
504    },
505    /// A relation parsed from an entity's `## Relationships` section
506    /// at load time failed validation against the source mem's
507    /// schema (or wiki-link grammar). The entity itself loads
508    /// normally; the offending relation is dropped from the
509    /// in-memory store. `reason` discriminates:
510    /// - `unknown_rel_type` — the rel-type is not declared in the
511    ///   source mem's schema and the schema is in `strict` mode.
512    /// - `shape` — the `(source_type, target_type)` pair is not
513    ///   allowed by the rel-type's `source_types` / `target_types`.
514    /// - `cycle` — adding this relation would close a cycle in an
515    ///   acyclic-declared subgraph (emitted by the post-load
516    ///   second-pass cycle check; not yet implemented).
517    ///
518    /// Hand-edits, external tooling, and embedder editor
519    /// surfaces can inject relations that bypass `memstead_relate`; the
520    /// parse-path validation catches those. Mutation-path writes
521    /// pre-validated by the engine never trip this warning.
522    ///
523    /// `origin` discriminates the source mount's capability:
524    /// `"writable"` (the operator can fix the source markdown via
525    /// `memstead_update` / `memstead_relate` and re-run) or `"readonly"`
526    /// (the source mem is mounted read-only — purely diagnostic,
527    /// the operator either uninstalls the archive or accepts the
528    /// dropped relation).
529    ///
530    /// `recovery` carries an abstract-action payload sufficient to
531    /// reverse the drop without consulting another response. `Some`
532    /// when `origin == "writable"` — the engine can rewrite the
533    /// source markdown via the mutation surface, so a consumer (an
534    /// agent walking `memstead_health`, a bulk-fix orchestrator, a
535    /// UI drift panel) maps `kind` to the concrete call on
536    /// whichever MCP / CLI surface it uses. `None` when
537    /// `origin == "readonly"` — the source markdown is not reachable
538    /// via the engine, so no abstract action exists; the warning's
539    /// message names the operator-level path (uninstall the archive
540    /// or accept the drop).
541    ParsedRelationInvalid {
542        entity_id: EntityId,
543        rel_type: String,
544        target: EntityId,
545        reason: String,
546        origin: String,
547        recovery: Option<ParsedRelationRecovery>,
548    },
549    /// `memstead_delete` (or `memstead_rename`, when implemented) on a
550    /// Write-Mem entity that had **no** Write-Mem referrers but
551    /// **does** have ReadOnly-mount referrers. The on-disk file is
552    /// removed and committed; the in-memory entity is demoted to a
553    /// stub at the same id so the surviving incoming edges from the
554    /// ReadOnly mount(s) keep a valid target. The agent sees
555    /// `memstead_entity <id>` returning a stub immediately and not
556    /// stale data after a server reload — fresh boot from disk
557    /// reconstructs the same stub via the parser's auto-stub-on-
558    /// unresolved-link path. `referrers` carries the surviving
559    /// ReadOnly source ids so the agent can either accept the stub
560    /// or uninstall the archive.
561    ResidualStubForReadOnlyReferrers {
562        id: EntityId,
563        referrers: Vec<EntityId>,
564    },
565    /// `memstead_mem_delete` was called with `delete_files: true` but
566    /// at least one part of the symmetric cleanup did not complete.
567    /// The mem is already unregistered from the router; this
568    /// warning surfaces what survived so an agent reading
569    /// `files_deleted: false` doesn't trigger redundant cleanup or
570    /// blame the wrong layer. `reason` discriminates:
571    /// - `rmdir_failed` — folder-backed mem directory survived
572    ///   `remove_dir_all` (filesystem permission, busy handle, …).
573    ///   `path` names the directory; `error` carries the OS-level
574    ///   diagnostic.
575    /// - `backend_prune_failed` — git-branch backend rejected the
576    ///   ref-edit transaction that prunes
577    ///   `refs/heads/<branch_leaf>` + `__MEMSTEAD:mems/.../config.json`
578    ///   (gitdir IO, concurrent writer racing the ref). `path` is
579    ///   `None`; `error` carries the wrapped backend message.
580    ///
581    /// One emission per failed step — both can land in the same
582    /// response when a folder mount somehow has both an rmdir
583    /// failure and a backend cleanup failure (rare; the folder
584    /// backend's `delete_artifacts` is a no-op default).
585    MemFilesNotDeleted {
586        mem: String,
587        reason: String,
588        path: Option<String>,
589        error: Option<String>,
590    },
591    /// `memstead mem init` detected a pre-existing branch + config
592    /// blob carrying the `unregistered_at` tombstone marker that
593    /// `memstead mem unregister` writes — the operator's deliberate
594    /// "preserve for re-attach" signal. The create path adopted the
595    /// residual entities, cleared the tombstone, and registered the
596    /// branch as a writable mount. Audit visibility for the
597    /// reattach so an agent reading the warnings sees what shape
598    /// the new mount took. `unregistered_at` carries the ISO-8601
599    /// timestamp the tombstone recorded so the operator can correlate
600    /// the reattach with a prior unregister event.
601    MemReattachedAfterUnregister {
602        mem: String,
603        unregistered_at: String,
604    },
605    /// One-time boot migration: legacy `readMems` entries found in a
606    /// writable mem's config were converted into workspace-level
607    /// read-only mounts and the legacy key was removed from the
608    /// config. `mems` lists the migrated read-mem names,
609    /// `from_host_mems` the writable mems whose configs carried them.
610    /// A second boot is silent — the source key is gone.
611    ReadMemsMigratedToMounts {
612        mems: Vec<String>,
613        from_host_mems: Vec<String>,
614    },
615    /// Boot-honesty skew: the mem's engine-owned mutation stamp
616    /// (`MemConfig.mutation_stamp`, written after mutations) records a
617    /// different engine version than the running binary. Informative,
618    /// never fatal — the next mutation under this binary re-stamps.
619    /// Absence of a stamp (a pre-stamp mem) never fires this; only a
620    /// present, disagreeing stamp does. Surfaces on boot output and
621    /// `memstead health` without an include gate.
622    EngineVersionSkew {
623        mem: String,
624        /// Engine version the last mutation was performed under.
625        stamped_engine: String,
626        /// Engine version of the running binary.
627        running_engine: String,
628        /// Resolved schema the last mutation validated against.
629        stamped_schema: String,
630        /// Which way the versions differ. Present because "they differ" left
631        /// the reader to work out whether their binary was ahead of the mem
632        /// or behind it, which is the only part that changes what they should
633        /// do.
634        direction: crate::build_info::SkewDirection,
635    },
636    /// Generation-behind hint: the mem's pinned schema resolved from
637    /// the BUILT-IN catalogue and the catalogue registers at least
638    /// one strictly-higher version of the same name (real semver
639    /// ordering). Warn-tier, ungated, never blocking — retention
640    /// seals every shipped version, so the pin keeps working; the
641    /// hint names the newest available generation and the migration
642    /// verb. Locally-installed (workspace-storage) pins are silent:
643    /// the engine only knows generations for built-ins. Surfaces on
644    /// boot output and `memstead health` without an include gate,
645    /// like the skew hint above.
646    SchemaGenerationsBehind {
647        mem: String,
648        /// The pinned ref (`name@version`).
649        pinned: String,
650        /// The newest built-in version registered under the same name.
651        newest: String,
652    },
653    /// The mem was created on storage with no version control (a
654    /// folder mount). Provenance means something WEAKER there than the
655    /// headline "every mutation a reasoned commit": mutations ARE
656    /// recorded — each lands in the folder backend's changelog ledger
657    /// (`.memstead/changes.jsonl`) with its provenance note — but
658    /// there are no commits, the `write_id` every mutation returns
659    /// is a synthetic token rather than a commit and is not a change
660    /// cursor (poll with the last ledger entry's `ts`), and the
661    /// content is not durable until the surrounding repository
662    /// commits it. Emitted once, at
663    /// creation, to whoever is actually acting; never a refusal —
664    /// folder mems are a supported storage class.
665    FolderMemProvenance { mem: String },
666    /// Authoring-drift health axis: a pinned schema's sealed copy
667    /// carries an install-provenance stamp, and the authoring path it
668    /// names is GONE from the working tree. Distinct from
669    /// [`WarningHint::SchemaAuthoringSourceDiverged`] — a missing
670    /// package and a diverged one need different actions. Only
671    /// stamped schemas are checked: on git-branch workspaces the
672    /// authoring folder is typically absent for unstamped seals, so a
673    /// naive existence check would warn on healthy workspaces.
674    SchemaAuthoringSourceMissing {
675        schema_ref: String,
676        stamped_path: String,
677        mems: Vec<String>,
678    },
679    /// Authoring-drift health axis: the stamped authoring path exists
680    /// but its package no longer parses EQUIVALENT to the sealed copy
681    /// the engine runs on (parsed-schema comparison, never raw bytes —
682    /// editor-header comment lines and serialisation reordering do not
683    /// trip it). `detail` says how: a load failure's message, or the
684    /// parsed-difference marker.
685    SchemaAuthoringSourceDiverged {
686        schema_ref: String,
687        stamped_path: String,
688        mems: Vec<String>,
689        detail: String,
690    },
691    /// Low-tier rot axis for UNSTAMPED pins — distinct from the two
692    /// stamped variants above, whose no-false-positive contract stays
693    /// untouched. The pinned schema's sealed package still loads
694    /// tolerantly (the mem runs fine), but its content no longer passes
695    /// current-language AUTHORING validation — so the package is, as of
696    /// the seal, no longer installable, and the (unstamped, therefore
697    /// unlocatable) authoring source it was sealed from has rotted the
698    /// same way unless someone has since fixed it. `detail` carries the
699    /// authoring-tier load error. Remedy: re-author the package under
700    /// the current language and `memstead schema install` it — which
701    /// re-seals AND stamps, handing the check over to the divergence
702    /// axis. An unstamped package that still parses under the authoring
703    /// tier produces no hint.
704    SchemaUnstampedSourceRot {
705        schema_ref: String,
706        mems: Vec<String>,
707        detail: String,
708    },
709    /// A `## Relationships` row was followed by trailing content that
710    /// did not match the canonical em-dash delimiter (` — `, U+2014
711    /// framed by spaces) — ASCII `--`, ASCII `-`, en-dash U+2013, or
712    /// minus U+2212. The relation parses with `description: None`;
713    /// the trailing content is NOT preserved on the in-memory
714    /// `Relationship`, so the next render of this entity normalises
715    /// the row to the simple form `- **TYPE**: [[X]]`. The warning is
716    /// the operator's signal that content was dropped — restore the
717    /// description with an explicit em-dash if it should round-trip.
718    /// Emitted at parse time (load / reload / attach); mutation paths
719    /// never trip it because they go through the typed `description`
720    /// parameter rather than markdown text.
721    AmbiguousDescriptionDelimiter {
722        from: EntityId,
723        rel_type: String,
724        target: EntityId,
725        /// Literal trailing content captured between `]]` and end of
726        /// line — surfaced verbatim so the operator can paste the
727        /// intended text back in with a canonical delimiter.
728        trailing: String,
729    },
730    /// Parse-time variant of [`crate::EngineError::MissingRequiredDescription`].
731    /// A hand-edited `## Relationships` row used a rel-type whose
732    /// schema declares `per_edge_description: required` without a
733    /// trailing description. The relation still loads (the engine
734    /// does not block the file from booting), but the warning
735    /// surfaces the gap so the operator follows up with `memstead_update`
736    /// / `memstead_relate` to author the missing description.
737    ParseMissingRequiredDescription {
738        from: EntityId,
739        rel_type: String,
740        target: EntityId,
741    },
742    /// Parse-time variant of [`crate::EngineError::DescriptionNotPermitted`].
743    /// A hand-edited `## Relationships` row used a rel-type whose
744    /// schema declares `per_edge_description: forbidden` together
745    /// with a trailing em-dash description. The relation still loads
746    /// (the engine does not block the file from booting); the
747    /// description is dropped from the in-memory `Relationship` and
748    /// the next render normalises the row to the simple form. The
749    /// warning surfaces the violation so the operator either removes
750    /// the text from disk or asks the schema author to widen the
751    /// rel-type's posture.
752    ParseDescriptionNotPermitted {
753        from: EntityId,
754        rel_type: String,
755        target: EntityId,
756    },
757    /// A mem's `Mount.schema` expectation (the pin recorded in the
758    /// workspace `mounts.json`) disagreed with the authoritative pin in
759    /// the mem's own per-mem config. Boot resolves the effective
760    /// schema from the mem config (authoritative — a copied/cloned
761    /// mem is self-resolvable); this warning surfaces the discrepancy
762    /// so neither value is silently dropped. Recovery: align the
763    /// `mounts.json` entry to the mem's config, or correct the config.
764    SchemaPinMismatch {
765        /// Mem whose mount expectation and config pin disagree.
766        mem: String,
767        /// Authoritative pin from the mem's per-mem config.
768        config_pin: String,
769        /// Expectation pin recorded on the workspace mount.
770        mount_pin: String,
771    },
772    /// A mount resolved to nothing: the storage it names does not
773    /// exist (`missing_ref` for a git-branch mount whose branch was
774    /// never created or was deleted, `missing_path` for a folder or
775    /// archive mount whose path is gone) or exists and holds no
776    /// entity (`empty`). Before this warning a mount pointing at a
777    /// nonexistent branch sat in the writable roster with zero
778    /// entities and nothing said so (this project's own workspace carried two
779    /// such mounts for weeks). Emitted at boot and on reload; a mount
780    /// that resolves to at least one entity is silent. Lazy mounts are
781    /// probed for storage presence only (the entity walk is deferred),
782    /// so `empty` is reported for eager mounts.
783    MountUnbacked {
784        /// The mount's mem name.
785        mem: String,
786        /// Why it is unbacked.
787        reason: MountUnbackedReason,
788        /// What the mount names: the branch ref, the folder path or
789        /// the archive path, for the operator's repair.
790        location: String,
791    },
792    /// A mutation wrote a section whose emitted heading differs from a
793    /// heading already present in the file that derives to the same
794    /// section key. The write still commits — refusing would strand
795    /// entities written before the round-trip gate existed — but the
796    /// divergence is surfaced so the caller sees the file's heading
797    /// text shifting under it (the regenerated file carries the
798    /// schema's declared heading; the previous text is replaced).
799    SectionHeadingDivergence {
800        entity_id: EntityId,
801        section_key: String,
802        /// Heading the mutation is writing (the schema's declared one).
803        writing_heading: String,
804        /// Different heading the file carried for the same key.
805        existing_heading: String,
806    },
807    /// A mem's resolved (already-installed) schema declares one or
808    /// more sections whose heading does not derive back to its key —
809    /// the condition new installs are refused for
810    /// (`check_section_heading_roundtrip`). Sealed schemas keep
811    /// loading by contract (refusing at boot would brick the
812    /// workspace), so the violation surfaces here instead: every write
813    /// against such a section forks its content into a second heading
814    /// or the catch-all. Recovery: fix the schema's heading/key pairs
815    /// and reinstall.
816    SchemaHeadingRoundtripViolation {
817        /// Mem whose pinned schema violates the rule.
818        mem: String,
819        /// The pinned `<name>@<version>`.
820        schema_ref: String,
821        /// Every offending `(type, key, heading, derived_key)` tuple.
822        violations: Vec<SchemaHeadingViolation>,
823    },
824}
825
826/// Wire-shape entry inside `SchemaHeadingRoundtripViolation.violations`
827/// — one section whose declared heading does not derive back to its
828/// declared key. Mirrors `memstead_schema::HeadingKeyViolation`, kept
829/// as a local struct so the warning's JSON shape is owned here.
830#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
831pub struct SchemaHeadingViolation {
832    pub type_name: String,
833    pub key: String,
834    pub heading: String,
835    pub derived_key: String,
836}
837
838impl From<&memstead_schema::HeadingKeyViolation> for SchemaHeadingViolation {
839    fn from(v: &memstead_schema::HeadingKeyViolation) -> Self {
840        Self {
841            type_name: v.type_name.clone(),
842            key: v.key.clone(),
843            heading: v.heading.clone(),
844            derived_key: v.derived_key.clone(),
845        }
846    }
847}
848
849/// Wire-shape entry inside `MissingRequiredOutgoing.missing`. Lists the
850/// relationship-name alternatives and the rendered cardinality literal
851/// for one unsatisfied `RequiredOutgoing` block. Custom struct so the
852/// JSON output is `{ "relationships": [...], "cardinality": "at_least_one" }`
853/// — identical to the schema YAML shape, so an agent can copy the
854/// envelope's `details.missing` entry directly into a `memstead_relate`
855/// plan without renaming fields.
856#[derive(Debug, Clone, Serialize)]
857pub struct MissingRequiredOutgoingBlock {
858    pub relationships: Vec<String>,
859    pub cardinality: String,
860    /// The block's declared severity. Serialized only for `block` —
861    /// warn is the default the vocabulary has always had, and existing
862    /// consumers keep their byte-identical `{ relationships,
863    /// cardinality }` shape.
864    #[serde(skip_serializing_if = "severity_is_warn")]
865    pub severity: memstead_schema::ConstraintSeverity,
866    /// The condition that armed a conditional block (`when_field` /
867    /// `when_value` on the declaration). Serialized only when present,
868    /// so unconditional blocks keep their byte-identical shape — and
869    /// the reader of a refusal, warning, or health finding sees which
870    /// trigger armed the obligation.
871    #[serde(skip_serializing_if = "Option::is_none")]
872    pub when_field: Option<String>,
873    #[serde(skip_serializing_if = "Option::is_none")]
874    pub when_value: Option<String>,
875}
876
877fn severity_is_warn(s: &memstead_schema::ConstraintSeverity) -> bool {
878    *s == memstead_schema::ConstraintSeverity::Warn
879}
880
881/// Abstract recovery action attached to a `PARSED_RELATION_INVALID`
882/// warning when the source mem is writable. The shape is tool-
883/// agnostic: it names *what* to do, not *which tool* to call. A
884/// consumer (agent, bulk-fix orchestrator, app surface) maps `kind`
885/// to the concrete call on whichever MCP / CLI path it
886/// uses; the warning's payload itself does not drift when the
887/// mutation surface evolves.
888///
889/// `kind` is the discriminator. Additive — new variants may land as
890/// the recovery taxonomy grows. Current values:
891///
892/// - `"remove_explicit_relation"` — drop the relation from the
893///   source entity's `## Relationships` section. Agents map this to
894///   `memstead_relate { from: source_id, to: target_id, type: rel_type,
895///   remove: true }`. The CLI maps it to the equivalent
896///   `memstead relate --remove` invocation. The bulk-fix consumer reads
897///   `source_id`, `target_id`, `rel_type` straight from the payload.
898///
899/// The mirrored `source_id` / `target_id` / `rel_type` fields are
900/// redundant with the warning's `entity_id` / `target` / `rel_type`
901/// — duplication is intentional. A consumer that branches on
902/// `recovery` and forwards the payload downstream does not need to
903/// stitch the warning's top-level fields back in.
904#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
905pub struct ParsedRelationRecovery {
906    pub kind: String,
907    pub source_id: EntityId,
908    pub target_id: EntityId,
909    pub rel_type: String,
910}
911
912impl ParsedRelationRecovery {
913    /// Stable discriminator for the "drop the relation from the
914    /// source markdown" recovery — the only abstract action this
915    /// warning emits today.
916    pub const KIND_REMOVE_EXPLICIT_RELATION: &'static str = "remove_explicit_relation";
917
918    /// Constructor for the standard `remove_explicit_relation`
919    /// recovery — the only shape produced by the parser today.
920    /// Emission sites use this so the discriminator string lives in
921    /// one place.
922    pub fn remove_explicit_relation(
923        source_id: EntityId,
924        target_id: EntityId,
925        rel_type: String,
926    ) -> Self {
927        Self {
928            kind: Self::KIND_REMOVE_EXPLICIT_RELATION.to_string(),
929            source_id,
930            target_id,
931            rel_type,
932        }
933    }
934}
935
936/// Per-entry result of an `apply_parse_recovery` call. One entry per
937/// `PARSED_RELATION_INVALID` warning the engine observed at the call
938/// site: the bulk-fix dispatches the writable-origin recoveries and
939/// reports the read-only-origin warnings as skipped. Wire-equivalent
940/// across the MCP and CLI surfaces; the renderer chooses the
941/// shape it prefers.
942///
943/// `outcome` is the stable discriminator. Current values:
944/// - `"removed"` — the source entity was re-rendered; the parse-time-
945///   dropped row no longer appears in the on-disk markdown. `reason`
946///   is `None`.
947/// - `"skipped"` — the engine intentionally did not attempt the
948///   recovery. `reason` carries a stable code: `"readonly_mount"`
949///   (source mem is read-only and not engine-writable).
950/// - `"failed"` — the engine attempted the recovery and the underlying
951///   mutation surfaced a typed error. `reason` carries the engine's
952///   `UPPER_SNAKE_CASE` error code (`HASH_MISMATCH`,
953///   `WIKILINK_WITHOUT_RELATION`, etc.). The original entity-side
954///   drift survives and will surface again on the next reload.
955#[derive(Debug, Clone, Serialize)]
956pub struct ParseRecoveryEntry {
957    pub entity_id: EntityId,
958    pub rel_type: String,
959    pub target: EntityId,
960    pub outcome: String,
961    #[serde(default, skip_serializing_if = "Option::is_none")]
962    pub reason: Option<String>,
963}
964
965impl ParseRecoveryEntry {
966    pub const OUTCOME_REMOVED: &'static str = "removed";
967    pub const OUTCOME_SKIPPED: &'static str = "skipped";
968    pub const OUTCOME_FAILED: &'static str = "failed";
969
970    /// Stable reason value for read-only-origin warnings the bulk-fix
971    /// cannot act on — the source markdown is not engine-writable.
972    pub const REASON_READONLY_MOUNT: &'static str = "readonly_mount";
973}
974
975/// Outcome of `Engine::apply_parse_recovery`. Carries one
976/// `ParseRecoveryEntry` per parse-time-dropped relation observed at
977/// the call site plus the last successful commit sha for callers that
978/// want to poll `memstead_changes_since` for the per-entity diff. An empty
979/// `entries` list means the workspace was already clean.
980///
981/// Idempotency: re-running on a workspace where the writable drops
982/// were already cleaned produces an empty `entries` list (no work,
983/// no commits, no errors).
984#[derive(Debug, Clone, Default, Serialize)]
985pub struct ParseRecoveryReport {
986    #[serde(default, skip_serializing_if = "Vec::is_empty")]
987    pub entries: Vec<ParseRecoveryEntry>,
988    /// The backend's identity for the last successful per-source
989    /// re-render the bulk-fix performed — a commit SHA on a git-branch
990    /// mem, a synthetic token on a folder mem, and never a change
991    /// cursor. Empty when no recovery wrote to disk
992    /// (workspace already clean, only read-only warnings, or every
993    /// writable attempt failed).
994    #[serde(default, skip_serializing_if = "String::is_empty")]
995    pub write_id: String,
996}
997
998/// Closed vocabulary of [`WarningHint::MountUnbacked`] reasons, serialised
999/// as the lowercase `details.reason` value.
1000#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1001pub enum MountUnbackedReason {
1002    /// Git-branch mount: the branch ref does not exist.
1003    MissingRef,
1004    /// Folder or archive mount: the path does not exist.
1005    MissingPath,
1006    /// The storage exists and holds no entity.
1007    Empty,
1008}
1009
1010impl MountUnbackedReason {
1011    /// The wire value (`missing_ref` / `missing_path` / `empty`).
1012    pub fn as_str(self) -> &'static str {
1013        match self {
1014            Self::MissingRef => "missing_ref",
1015            Self::MissingPath => "missing_path",
1016            Self::Empty => "empty",
1017        }
1018    }
1019}
1020
1021impl Serialize for WarningHint {
1022    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1023        // Direct struct emission — avoids the intermediate `Value` allocation
1024        // `envelope(...).serialize(serializer)` would incur. Wire shape is
1025        // bit-identical to `envelope(...)`'s output; DRY lives at the
1026        // constructor level via the shared `envelope` helper used by the MCP
1027        // error path (`engine_err_with_suggestions`).
1028        let details = self.details_payload();
1029        let mut state = serializer.serialize_struct("WarningHint", 3)?;
1030        state.serialize_field("code", self.code())?;
1031        state.serialize_field("message", &self.message())?;
1032        state.serialize_field("details", &details)?;
1033        state.end()
1034    }
1035}