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`. 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    /// since 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 (a
287    /// default-schema scratch mem citing a planning mem, for example);
288    /// 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.
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    /// A mem under both `added` and `removed` changed capability (write
428    /// to read-only, or back): it was remounted and serves.
429    MemRosterChanged {
430        added: Vec<String>,
431        removed: Vec<String>,
432        quarantined: Vec<String>,
433        failures: Vec<String>,
434    },
435    /// `OUT_OF_BAND_EDITS_UNDETECTED`: this folder mem's drift cursor is its
436    /// own change ledger, which only the engine writes, so an edit made to the
437    /// files by anything else advances nothing.
438    ///
439    /// The engine keeps serving pre-edit content and `changes_since` reports
440    /// the edit as never having happened. It is not fixable cheaply: the
441    /// staleness probe runs before every operation, and turning it into a
442    /// directory walk would change the cost profile of the whole folder
443    /// backend. So the engine says it cannot detect them rather than staying
444    /// quiet, and `memstead health --include ledger` reconciles on demand.
445    ///
446    /// Never fires for a git-branch mem: its change set is a real two-tree
447    /// diff, so the condition cannot arise.
448    OutOfBandEditsUndetected { mem: String },
449    /// A destination entity of a projection binding names an in-scope source
450    /// artifact in its prose and carries no anchor on it — a claim no verify
451    /// watches on the entity's behalf. Read off the binding's findings store
452    /// (the `unanchored-mention` class the verify pass records); warn-level,
453    /// never a refusal. Remedy: anchor the artifact on the entity
454    /// (`memstead_update` with `anchors`), or exclude the artifact with a
455    /// rationale (`memstead projection exclude`).
456    UnanchoredMention {
457        mem: String,
458        binding: String,
459        entity: EntityId,
460        artifact: String,
461        section: String,
462    },
463    /// A config write found the stored config had moved on from what this
464    /// engine last observed: another writer changed it in between.
465    ///
466    /// The write still lands. It is applied to the CONFIG THAT IS THERE, not
467    /// to the engine's cached copy, so the intervening writer's fields
468    /// survive; `fields` names what they had changed. The warning exists
469    /// because a caller who set one field and finds three different is owed
470    /// the explanation on the response that did it, not in a log.
471    ///
472    /// Never fires in a single-writer workspace: the cached copy equals the
473    /// file there, so there is nothing to report.
474    ConfigWriteIntervened { mem: String, fields: Vec<String> },
475    /// A mutation verb was given an entity id without its mem prefix
476    /// and exactly one mounted mem carried an entity of that slug, so
477    /// the verb acted on that entity. Announced, never silent: the
478    /// caller learns the full id the write landed on, and a second
479    /// mem gaining the slug later turns the same call into an
480    /// `ENTITY_ID_MISSING_MEM` refusal rather than a silent retarget.
481    ShortIdResolved { given: String, resolved: EntityId },
482    /// `memstead_relate` add path landed on a not-yet-real target id and
483    /// the engine materialised a stub at that id (in-memory upsert; the
484    /// file lands when a follow-up `memstead_create` promotes the stub).
485    /// Pre-fix surfaced through a top-level `stub_warning: Option<String>`
486    /// field on the relate response — agents iterating `warnings[]` to
487    /// surface non-fatal findings silently skipped the auto-stub case.
488    /// Carries the materialised stub id so the agent can pin a
489    /// follow-up `memstead_create` (or `memstead_relate remove=true` to drop
490    /// the edge before authoring). `pending` marks the dry-run path:
491    /// the rehearsal validated the add and REPORTS the would-be stub
492    /// without writing it — the code stays `AUTO_STUB_CREATED`
493    /// (response-shape stability), only the message branches, so a
494    /// rehearsed response never claims a performed effect.
495    AutoStubCreated { stub_id: EntityId, pending: bool },
496    /// A duplicate-add `memstead_relate` on a derivation-declared
497    /// rel-type refreshed the edge's baseline —
498    /// the agent's explicit "I have reviewed the target's change; the
499    /// derivation still holds". Sidecar-only: `_hash` unchanged, the
500    /// edge unchanged; the response carries this warning so the
501    /// refresh is stated rather than a bare no-op.
502    DerivationBaselineRefreshed {
503        from: EntityId,
504        rel_type: String,
505        to: EntityId,
506    },
507    /// A relation parsed from an entity's `## Relationships` section
508    /// at load time failed validation against the source mem's
509    /// schema (or wiki-link grammar). The entity itself loads
510    /// normally; the offending relation is dropped from the
511    /// in-memory store. `reason` discriminates:
512    /// - `unknown_rel_type` — the rel-type is not declared in the
513    ///   source mem's schema and the schema is in `strict` mode.
514    /// - `shape` — the `(source_type, target_type)` pair is not
515    ///   allowed by the rel-type's `source_types` / `target_types`.
516    /// - `cycle` — adding this relation would close a cycle in an
517    ///   acyclic-declared subgraph (emitted by the post-load
518    ///   second-pass cycle check; not yet implemented).
519    ///
520    /// Hand-edits, external tooling, and embedder editor
521    /// surfaces can inject relations that bypass `memstead_relate`; the
522    /// parse-path validation catches those. Mutation-path writes
523    /// pre-validated by the engine never trip this warning.
524    ///
525    /// `origin` discriminates the source mount's capability:
526    /// `"writable"` (the operator can fix the source markdown via
527    /// `memstead_update` / `memstead_relate` and re-run) or `"readonly"`
528    /// (the source mem is mounted read-only — purely diagnostic,
529    /// the operator either uninstalls the archive or accepts the
530    /// dropped relation).
531    ///
532    /// `recovery` carries an abstract-action payload sufficient to
533    /// reverse the drop without consulting another response. `Some`
534    /// when `origin == "writable"` — the engine can rewrite the
535    /// source markdown via the mutation surface, so a consumer (an
536    /// agent walking `memstead_health`, a bulk-fix orchestrator, a
537    /// UI drift panel) maps `kind` to the concrete call on
538    /// whichever MCP / CLI surface it uses. `None` when
539    /// `origin == "readonly"` — the source markdown is not reachable
540    /// via the engine, so no abstract action exists; the warning's
541    /// message names the operator-level path (uninstall the archive
542    /// or accept the drop).
543    ParsedRelationInvalid {
544        entity_id: EntityId,
545        rel_type: String,
546        target: EntityId,
547        reason: String,
548        origin: String,
549        recovery: Option<ParsedRelationRecovery>,
550    },
551    /// `memstead_delete` (or `memstead_rename`, when implemented) on a
552    /// Write-Mem entity that had **no** Write-Mem referrers but
553    /// **does** have ReadOnly-mount referrers. The on-disk file is
554    /// removed and committed; the in-memory entity is demoted to a
555    /// stub at the same id so the surviving incoming edges from the
556    /// ReadOnly mount(s) keep a valid target. The agent sees
557    /// `memstead_entity <id>` returning a stub immediately and not
558    /// stale data after a server reload — fresh boot from disk
559    /// reconstructs the same stub via the parser's auto-stub-on-
560    /// unresolved-link path. `referrers` carries the surviving
561    /// ReadOnly source ids so the agent can either accept the stub
562    /// or uninstall the archive.
563    ResidualStubForReadOnlyReferrers {
564        id: EntityId,
565        referrers: Vec<EntityId>,
566    },
567    /// `memstead_mem_delete` was called with `delete_files: true` but
568    /// at least one part of the symmetric cleanup did not complete.
569    /// The mem is already unregistered from the router; this
570    /// warning surfaces what survived so an agent reading
571    /// `files_deleted: false` doesn't trigger redundant cleanup or
572    /// blame the wrong layer. `reason` discriminates:
573    /// - `rmdir_failed` — folder-backed mem directory survived
574    ///   `remove_dir_all` (filesystem permission, busy handle, …).
575    ///   `path` names the directory; `error` carries the OS-level
576    ///   diagnostic.
577    /// - `backend_prune_failed` — git-branch backend rejected the
578    ///   ref-edit transaction that prunes
579    ///   `refs/heads/<branch_leaf>` + `__MEMSTEAD:mems/.../config.json`
580    ///   (gitdir IO, concurrent writer racing the ref). `path` is
581    ///   `None`; `error` carries the wrapped backend message.
582    ///
583    /// One emission per failed step — both can land in the same
584    /// response when a folder mount somehow has both an rmdir
585    /// failure and a backend cleanup failure (rare; the folder
586    /// backend's `delete_artifacts` is a no-op default).
587    MemFilesNotDeleted {
588        mem: String,
589        reason: String,
590        path: Option<String>,
591        error: Option<String>,
592    },
593    /// `memstead mem init` detected a pre-existing branch + config
594    /// blob carrying the `unregistered_at` tombstone marker that
595    /// `memstead mem unregister` writes — the operator's deliberate
596    /// "preserve for re-attach" signal. The create path adopted the
597    /// residual entities, cleared the tombstone, and registered the
598    /// branch as a writable mount. Audit visibility for the
599    /// reattach so an agent reading the warnings sees what shape
600    /// the new mount took. `unregistered_at` carries the ISO-8601
601    /// timestamp the tombstone recorded so the operator can correlate
602    /// the reattach with a prior unregister event.
603    MemReattachedAfterUnregister {
604        mem: String,
605        unregistered_at: String,
606    },
607    /// One-time boot migration: legacy `readMems` entries found in a
608    /// writable mem's config were converted into workspace-level
609    /// read-only mounts and the legacy key was removed from the
610    /// config. `mems` lists the migrated read-mem names,
611    /// `from_host_mems` the writable mems whose configs carried them.
612    /// A second boot is silent — the source key is gone.
613    ReadMemsMigratedToMounts {
614        mems: Vec<String>,
615        from_host_mems: Vec<String>,
616    },
617    /// Boot-honesty skew: the mem's engine-owned mutation stamp
618    /// (`MemConfig.mutation_stamp`, written after mutations) records a
619    /// different engine version than the running binary. Informative,
620    /// never fatal — the next mutation under this binary re-stamps.
621    /// Absence of a stamp (a pre-stamp mem) never fires this; only a
622    /// present, disagreeing stamp does. Surfaces on boot output and
623    /// `memstead health` without an include gate.
624    EngineVersionSkew {
625        mem: String,
626        /// Engine version the last mutation was performed under.
627        stamped_engine: String,
628        /// Engine version of the running binary.
629        running_engine: String,
630        /// Resolved schema the last mutation validated against.
631        stamped_schema: String,
632        /// Which way the versions differ. Present because "they differ" left
633        /// the reader to work out whether their binary was ahead of the mem
634        /// or behind it, which is the only part that changes what they should
635        /// do.
636        direction: crate::build_info::SkewDirection,
637    },
638    /// Generation-behind hint: the mem's pinned schema resolved from
639    /// the BUILT-IN catalogue and the catalogue registers at least
640    /// one strictly-higher version of the same name (real semver
641    /// ordering). Warn-tier, ungated, never blocking — retention
642    /// seals every shipped version, so the pin keeps working; the
643    /// hint names the newest available generation and the migration
644    /// verb. Locally-installed (workspace-storage) pins are silent:
645    /// the engine only knows generations for built-ins. Surfaces on
646    /// boot output and `memstead health` without an include gate,
647    /// like the skew hint above.
648    SchemaGenerationsBehind {
649        mem: String,
650        /// The pinned ref (`name@version`).
651        pinned: String,
652        /// The newest built-in version registered under the same name.
653        newest: String,
654    },
655    /// The mem was created on storage with no version control (a
656    /// folder mount). Provenance means something WEAKER there than the
657    /// headline "every mutation a reasoned commit": mutations ARE
658    /// recorded — each lands in the folder backend's changelog ledger
659    /// (`.memstead/changes.jsonl`) with its provenance note — but
660    /// there are no commits, the `write_id` every mutation returns
661    /// is a synthetic token rather than a commit and is not a change
662    /// cursor (poll with the last ledger entry's `ts`), and the
663    /// content is not durable until the surrounding repository
664    /// commits it. Emitted once, at
665    /// creation, to whoever is actually acting; never a refusal —
666    /// folder mems are a supported storage class.
667    FolderMemProvenance { mem: String },
668    /// Authoring-drift health axis: a pinned schema's sealed copy
669    /// carries an install-provenance stamp, and the authoring path it
670    /// names is GONE from the working tree. Distinct from
671    /// [`WarningHint::SchemaAuthoringSourceDiverged`] — a missing
672    /// package and a diverged one need different actions. Only
673    /// stamped schemas are checked: on git-branch workspaces the
674    /// authoring folder is typically absent for unstamped seals, so a
675    /// naive existence check would warn on healthy workspaces.
676    SchemaAuthoringSourceMissing {
677        schema_ref: String,
678        stamped_path: String,
679        mems: Vec<String>,
680    },
681    /// Authoring-drift health axis: the stamped authoring path exists
682    /// but its package no longer parses EQUIVALENT to the sealed copy
683    /// the engine runs on (parsed-schema comparison, never raw bytes —
684    /// editor-header comment lines and serialisation reordering do not
685    /// trip it). `detail` says how: a load failure's message, or the
686    /// parsed-difference marker.
687    SchemaAuthoringSourceDiverged {
688        schema_ref: String,
689        stamped_path: String,
690        mems: Vec<String>,
691        detail: String,
692    },
693    /// Low-tier rot axis for UNSTAMPED pins — distinct from the two
694    /// stamped variants above, whose no-false-positive contract stays
695    /// untouched. The pinned schema's sealed package still loads
696    /// tolerantly (the mem runs fine), but its content no longer passes
697    /// current-language AUTHORING validation — so the package is, as of
698    /// the seal, no longer installable, and the (unstamped, therefore
699    /// unlocatable) authoring source it was sealed from has rotted the
700    /// same way unless someone has since fixed it. `detail` carries the
701    /// authoring-tier load error. Remedy: re-author the package under
702    /// the current language and `memstead schema install` it — which
703    /// re-seals AND stamps, handing the check over to the divergence
704    /// axis. An unstamped package that still parses under the authoring
705    /// tier produces no hint.
706    SchemaUnstampedSourceRot {
707        schema_ref: String,
708        mems: Vec<String>,
709        detail: String,
710    },
711    /// A `## Relationships` row was followed by trailing content that
712    /// did not match the canonical em-dash delimiter (` — `, U+2014
713    /// framed by spaces) — ASCII `--`, ASCII `-`, en-dash U+2013, or
714    /// minus U+2212. The relation parses with `description: None`;
715    /// the trailing content is NOT preserved on the in-memory
716    /// `Relationship`, so the next render of this entity normalises
717    /// the row to the simple form `- **TYPE**: [[X]]`. The warning is
718    /// the operator's signal that content was dropped — restore the
719    /// description with an explicit em-dash if it should round-trip.
720    /// Emitted at parse time (load / reload / attach); mutation paths
721    /// never trip it because they go through the typed `description`
722    /// parameter rather than markdown text.
723    AmbiguousDescriptionDelimiter {
724        from: EntityId,
725        rel_type: String,
726        target: EntityId,
727        /// Literal trailing content captured between `]]` and end of
728        /// line — surfaced verbatim so the operator can paste the
729        /// intended text back in with a canonical delimiter.
730        trailing: String,
731    },
732    /// Parse-time variant of [`crate::EngineError::MissingRequiredDescription`].
733    /// A hand-edited `## Relationships` row used a rel-type whose
734    /// schema declares `per_edge_description: required` without a
735    /// trailing description. The relation still loads (the engine
736    /// does not block the file from booting), but the warning
737    /// surfaces the gap so the operator follows up with `memstead_update`
738    /// / `memstead_relate` to author the missing description.
739    ParseMissingRequiredDescription {
740        from: EntityId,
741        rel_type: String,
742        target: EntityId,
743    },
744    /// Parse-time variant of [`crate::EngineError::DescriptionNotPermitted`].
745    /// A hand-edited `## Relationships` row used a rel-type whose
746    /// schema declares `per_edge_description: forbidden` together
747    /// with a trailing em-dash description. The relation still loads
748    /// (the engine does not block the file from booting); the
749    /// description is dropped from the in-memory `Relationship` and
750    /// the next render normalises the row to the simple form. The
751    /// warning surfaces the violation so the operator either removes
752    /// the text from disk or asks the schema author to widen the
753    /// rel-type's posture.
754    ParseDescriptionNotPermitted {
755        from: EntityId,
756        rel_type: String,
757        target: EntityId,
758    },
759    /// A mem's `Mount.schema` expectation (the pin recorded in the
760    /// workspace `mounts.json`) disagreed with the authoritative pin in
761    /// the mem's own per-mem config. Boot resolves the effective
762    /// schema from the mem config (authoritative — a copied/cloned
763    /// mem is self-resolvable); this warning surfaces the discrepancy
764    /// so neither value is silently dropped. Recovery: align the
765    /// `mounts.json` entry to the mem's config, or correct the config.
766    SchemaPinMismatch {
767        /// Mem whose mount expectation and config pin disagree.
768        mem: String,
769        /// Authoritative pin from the mem's per-mem config.
770        config_pin: String,
771        /// Expectation pin recorded on the workspace mount.
772        mount_pin: String,
773    },
774    /// A mount resolved to nothing: the storage it names does not
775    /// exist (`missing_ref` for a git-branch mount whose branch was
776    /// never created or was deleted, `missing_path` for a folder or
777    /// archive mount whose path is gone) or exists and holds no
778    /// entity (`empty`). Before this warning a mount pointing at a
779    /// nonexistent branch sat in the writable roster with zero
780    /// entities and nothing said so (this project's own workspace carried two
781    /// such mounts for weeks). Emitted at boot and on reload; a mount
782    /// that resolves to at least one entity is silent. Lazy mounts are
783    /// probed for storage presence only (the entity walk is deferred),
784    /// so `empty` is reported for eager mounts.
785    MountUnbacked {
786        /// The mount's mem name.
787        mem: String,
788        /// Why it is unbacked.
789        reason: MountUnbackedReason,
790        /// What the mount names: the branch ref, the folder path or
791        /// the archive path, for the operator's repair.
792        location: String,
793    },
794    /// A folder mem's last commit was decided and then cut off (a
795    /// crash, a kill, an IO error) before every file was in place, and
796    /// this load finished it before reading anything. The mem is whole:
797    /// the named files carry the content of that commit and the change
798    /// ledger carries its line. Emitted by the load that did the
799    /// completing, at boot or on reload.
800    InterruptedCommitCompleted {
801        /// The mem whose commit was completed.
802        mem: String,
803        /// Mem-relative paths the commit covered.
804        files: Vec<String>,
805    },
806    /// A write is in storage and a step after its commit failed: the
807    /// refresh of a checked-out worktree, the update of the engine's
808    /// in-memory view. The call still reports success, because the
809    /// write landed and resending it would write twice. Where the
810    /// failed step was the engine's own view, the engine reloaded the
811    /// mem from storage, so its view is level with what was written.
812    WriteFollowUpFailed {
813        /// The mem the write landed in.
814        mem: String,
815        /// The step that failed: `commit_apply` (a folder commit was cut
816        /// off after its commit point and completed at once),
817        /// `worktree_sync`, `store_update`, `policy_scrub` (a mem delete
818        /// whose grant scrub could not write the workspace config).
819        step: String,
820        /// The failure, as the step reported it.
821        detail: String,
822    },
823    /// A mutation wrote a section whose emitted heading differs from a
824    /// heading already present in the file that derives to the same
825    /// section key. The write still commits — refusing would strand
826    /// entities written before the round-trip gate existed — but the
827    /// divergence is surfaced so the caller sees the file's heading
828    /// text shifting under it (the regenerated file carries the
829    /// schema's declared heading; the previous text is replaced).
830    SectionHeadingDivergence {
831        entity_id: EntityId,
832        section_key: String,
833        /// Heading the mutation is writing (the schema's declared one).
834        writing_heading: String,
835        /// Different heading the file carried for the same key.
836        existing_heading: String,
837    },
838    /// A mem's resolved (already-installed) schema declares one or
839    /// more sections whose heading does not derive back to its key —
840    /// the condition new installs are refused for
841    /// (`check_section_heading_roundtrip`). Sealed schemas keep
842    /// loading by contract (refusing at boot would brick the
843    /// workspace), so the violation surfaces here instead: every write
844    /// against such a section forks its content into a second heading
845    /// or the catch-all. Recovery: fix the schema's heading/key pairs
846    /// and reinstall.
847    SchemaHeadingRoundtripViolation {
848        /// Mem whose pinned schema violates the rule.
849        mem: String,
850        /// The pinned `<name>@<version>`.
851        schema_ref: String,
852        /// Every offending `(type, key, heading, derived_key)` tuple.
853        violations: Vec<SchemaHeadingViolation>,
854    },
855}
856
857/// Wire-shape entry inside `SchemaHeadingRoundtripViolation.violations`
858/// — one section whose declared heading does not derive back to its
859/// declared key. Mirrors `memstead_schema::HeadingKeyViolation`, kept
860/// as a local struct so the warning's JSON shape is owned here.
861#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
862pub struct SchemaHeadingViolation {
863    pub type_name: String,
864    pub key: String,
865    pub heading: String,
866    pub derived_key: String,
867}
868
869impl From<&memstead_schema::HeadingKeyViolation> for SchemaHeadingViolation {
870    fn from(v: &memstead_schema::HeadingKeyViolation) -> Self {
871        Self {
872            type_name: v.type_name.clone(),
873            key: v.key.clone(),
874            heading: v.heading.clone(),
875            derived_key: v.derived_key.clone(),
876        }
877    }
878}
879
880/// Wire-shape entry inside `MissingRequiredOutgoing.missing`. Lists the
881/// relationship-name alternatives and the rendered cardinality literal
882/// for one unsatisfied `RequiredOutgoing` block. Custom struct so the
883/// JSON output is `{ "relationships": [...], "cardinality": "at_least_one" }`
884/// — identical to the schema YAML shape, so an agent can copy the
885/// envelope's `details.missing` entry directly into a `memstead_relate`
886/// plan without renaming fields.
887#[derive(Debug, Clone, Serialize)]
888pub struct MissingRequiredOutgoingBlock {
889    pub relationships: Vec<String>,
890    pub cardinality: String,
891    /// The block's declared severity. Serialized only for `block` —
892    /// warn is the default the vocabulary has always had, and existing
893    /// consumers keep their byte-identical `{ relationships,
894    /// cardinality }` shape.
895    #[serde(skip_serializing_if = "severity_is_warn")]
896    pub severity: memstead_schema::ConstraintSeverity,
897    /// The condition that armed a conditional block (`when_field` /
898    /// `when_value` on the declaration). Serialized only when present,
899    /// so unconditional blocks keep their byte-identical shape — and
900    /// the reader of a refusal, warning, or health finding sees which
901    /// trigger armed the obligation.
902    #[serde(skip_serializing_if = "Option::is_none")]
903    pub when_field: Option<String>,
904    #[serde(skip_serializing_if = "Option::is_none")]
905    pub when_value: Option<String>,
906}
907
908fn severity_is_warn(s: &memstead_schema::ConstraintSeverity) -> bool {
909    *s == memstead_schema::ConstraintSeverity::Warn
910}
911
912/// Abstract recovery action attached to a `PARSED_RELATION_INVALID`
913/// warning when the source mem is writable. The shape is tool-
914/// agnostic: it names *what* to do, not *which tool* to call. A
915/// consumer (agent, bulk-fix orchestrator, app surface) maps `kind`
916/// to the concrete call on whichever MCP / CLI path it
917/// uses; the warning's payload itself does not drift when the
918/// mutation surface evolves.
919///
920/// `kind` is the discriminator. Additive — new variants may land as
921/// the recovery taxonomy grows. Current values:
922///
923/// - `"remove_explicit_relation"` — drop the relation from the
924///   source entity's `## Relationships` section. Agents map this to
925///   `memstead_relate { from: source_id, to: target_id, type: rel_type,
926///   remove: true }`. The CLI maps it to the equivalent
927///   `memstead relate --remove` invocation. The bulk-fix consumer reads
928///   `source_id`, `target_id`, `rel_type` straight from the payload.
929///
930/// The mirrored `source_id` / `target_id` / `rel_type` fields are
931/// redundant with the warning's `entity_id` / `target` / `rel_type`
932/// — duplication is intentional. A consumer that branches on
933/// `recovery` and forwards the payload downstream does not need to
934/// stitch the warning's top-level fields back in.
935#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
936pub struct ParsedRelationRecovery {
937    pub kind: String,
938    pub source_id: EntityId,
939    pub target_id: EntityId,
940    pub rel_type: String,
941}
942
943impl ParsedRelationRecovery {
944    /// Stable discriminator for the "drop the relation from the
945    /// source markdown" recovery — the only abstract action this
946    /// warning emits today.
947    pub const KIND_REMOVE_EXPLICIT_RELATION: &'static str = "remove_explicit_relation";
948
949    /// Constructor for the standard `remove_explicit_relation`
950    /// recovery — the only shape produced by the parser today.
951    /// Emission sites use this so the discriminator string lives in
952    /// one place.
953    pub fn remove_explicit_relation(
954        source_id: EntityId,
955        target_id: EntityId,
956        rel_type: String,
957    ) -> Self {
958        Self {
959            kind: Self::KIND_REMOVE_EXPLICIT_RELATION.to_string(),
960            source_id,
961            target_id,
962            rel_type,
963        }
964    }
965}
966
967/// Per-entry result of an `apply_parse_recovery` call. One entry per
968/// `PARSED_RELATION_INVALID` warning the engine observed at the call
969/// site: the bulk-fix dispatches the writable-origin recoveries and
970/// reports the read-only-origin warnings as skipped. Wire-equivalent
971/// across the MCP and CLI surfaces; the renderer chooses the
972/// shape it prefers.
973///
974/// `outcome` is the stable discriminator. Current values:
975/// - `"removed"` — the source entity was re-rendered; the parse-time-
976///   dropped row no longer appears in the on-disk markdown. `reason`
977///   is `None`.
978/// - `"skipped"` — the engine intentionally did not attempt the
979///   recovery. `reason` carries a stable code: `"readonly_mount"`
980///   (source mem is read-only and not engine-writable).
981/// - `"failed"` — the engine attempted the recovery and the underlying
982///   mutation surfaced a typed error. `reason` carries the engine's
983///   `UPPER_SNAKE_CASE` error code (`HASH_MISMATCH`,
984///   `WIKILINK_WITHOUT_RELATION`, etc.). The original entity-side
985///   drift survives and will surface again on the next reload.
986#[derive(Debug, Clone, Serialize)]
987pub struct ParseRecoveryEntry {
988    pub entity_id: EntityId,
989    pub rel_type: String,
990    pub target: EntityId,
991    pub outcome: String,
992    #[serde(default, skip_serializing_if = "Option::is_none")]
993    pub reason: Option<String>,
994}
995
996impl ParseRecoveryEntry {
997    pub const OUTCOME_REMOVED: &'static str = "removed";
998    pub const OUTCOME_SKIPPED: &'static str = "skipped";
999    pub const OUTCOME_FAILED: &'static str = "failed";
1000
1001    /// Stable reason value for read-only-origin warnings the bulk-fix
1002    /// cannot act on — the source markdown is not engine-writable.
1003    pub const REASON_READONLY_MOUNT: &'static str = "readonly_mount";
1004}
1005
1006/// Outcome of `Engine::apply_parse_recovery`. Carries one
1007/// `ParseRecoveryEntry` per parse-time-dropped relation observed at
1008/// the call site plus the last successful commit sha for callers that
1009/// want to poll `memstead_changes_since` for the per-entity diff. An empty
1010/// `entries` list means the workspace was already clean.
1011///
1012/// Idempotency: re-running on a workspace where the writable drops
1013/// were already cleaned produces an empty `entries` list (no work,
1014/// no commits, no errors).
1015#[derive(Debug, Clone, Default, Serialize)]
1016pub struct ParseRecoveryReport {
1017    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1018    pub entries: Vec<ParseRecoveryEntry>,
1019    /// The backend's identity for the last successful per-source
1020    /// re-render the bulk-fix performed — a commit SHA on a git-branch
1021    /// mem, a synthetic token on a folder mem, and never a change
1022    /// cursor. Empty when no recovery wrote to disk
1023    /// (workspace already clean, only read-only warnings, or every
1024    /// writable attempt failed).
1025    #[serde(default, skip_serializing_if = "String::is_empty")]
1026    pub write_id: String,
1027}
1028
1029/// Closed vocabulary of [`WarningHint::MountUnbacked`] reasons, serialised
1030/// as the lowercase `details.reason` value.
1031#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1032pub enum MountUnbackedReason {
1033    /// Git-branch mount: the branch ref does not exist.
1034    MissingRef,
1035    /// Folder or archive mount: the path does not exist.
1036    MissingPath,
1037    /// The storage exists and holds no entity.
1038    Empty,
1039}
1040
1041impl MountUnbackedReason {
1042    /// The wire value (`missing_ref` / `missing_path` / `empty`).
1043    pub fn as_str(self) -> &'static str {
1044        match self {
1045            Self::MissingRef => "missing_ref",
1046            Self::MissingPath => "missing_path",
1047            Self::Empty => "empty",
1048        }
1049    }
1050}
1051
1052impl Serialize for WarningHint {
1053    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1054        // Direct struct emission — avoids the intermediate `Value` allocation
1055        // `envelope(...).serialize(serializer)` would incur. Wire shape is
1056        // bit-identical to `envelope(...)`'s output; DRY lives at the
1057        // constructor level via the shared `envelope` helper used by the MCP
1058        // error path (`engine_err_with_suggestions`).
1059        let details = self.details_payload();
1060        let mut state = serializer.serialize_struct("WarningHint", 3)?;
1061        state.serialize_field("code", self.code())?;
1062        state.serialize_field("message", &self.message())?;
1063        state.serialize_field("details", &details)?;
1064        state.end()
1065    }
1066}