memstead_base/ops/mod.rs
1//! Operation request/response types and the gix-free read paths
2//! (`health`, `search`).
3//!
4//! Per-entity delta envelopes for `memstead_changes_since` live in
5//! [`changes`] — backend-neutral so both the git-branch tree-diff
6//! and any future folder-backend JSONL-walk produce the same shape.
7//! Wire types for the agent-notes payload live in [`agent_notes`] —
8//! pure data shapes, no gix. The producer functions
9//! (`agent_notes_since`, `read_memstead_ref`) stay in
10//! `memstead-git-branch::ops::agent_notes` because they read from a
11//! gitdir.
12//! The git-touching operation submodules (`crud`, `export`) still
13//! live in `memstead-git-branch` and are re-exported into
14//! `memstead_git_branch::ops` for downstream callers.
15
16pub mod agent_notes;
17pub mod branch_reset;
18pub mod changes;
19pub mod commit_envelope;
20pub mod coverage;
21pub mod diff;
22pub mod export;
23pub mod health;
24pub mod health_compose;
25pub mod integrity;
26pub mod labelling;
27pub mod redaction;
28#[cfg(not(target_arch = "wasm32"))]
29pub mod search;
30pub mod signals;
31pub mod strict;
32pub mod transport;
33
34pub use agent_notes::{AgentNotesReport, CommitNote};
35pub use branch_reset::{BranchResetOutcome, StrandedCrossMemRef};
36pub use changes::{
37 BackendChanges, ChangeEnvelope, ChangesReport, EMPTY_TREE_SHA, MemChangedNotice,
38 NoticeByChange, NoticeChanges, RENAME_SIMILARITY_DEFAULT, RENAME_SIMILARITY_MAX,
39 RENAME_SIMILARITY_MIN, StoreLookup, folder_changes_since,
40};
41pub use commit_envelope::{CommitEnvelope, EntityChange};
42pub use diff::{Diff, DiffConfig, EntityDiff, IncomingRipple};
43pub use export::{MemExportBytes, MemExportError};
44pub use transport::{
45 FetchOutcome, PullOutcome, PushAllOutcome, PushOutcome, PushedRef, RefusedRef,
46 RemoteAddOutcome, RemoteRefState, RemoteRefStatus, RemoteStatusOutcome, UpdatedRef,
47};
48
49use crate::entity::EntityId;
50use indexmap::IndexMap;
51use schemars::JsonSchema;
52use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct};
53use std::collections::HashMap;
54use std::fmt;
55
56/// Allowed `include` keys for `memstead_overview` — single source of
57/// truth shared across the MCP server and the
58/// CLI's `overview` command. Mirrors `HEALTH_INCLUDE_KEYS` for
59/// the `health` surface. The CLI `--include` flag validates against
60/// this list and surfaces `UNKNOWN_INCLUDE_KEY` warnings, matching the
61/// MCP tool's behaviour.
62pub const OVERVIEW_INCLUDE_KEYS: &[&str] = &[
63 "community_members",
64 "community_bridges",
65 "mem_distribution",
66 "dangling_links",
67];
68
69// The unknown-filter warning prose lives in the `Display` impl of the
70// typed `WarningHint::UnknownFilterKey` / `WarningHint::UnknownRangeFilterField`
71// variants below. These helpers are shared with that Display impl. They
72// are pure string formatting with no search/tantivy dependency, so they
73// live here (not in the wasm-gated `search` module) and stay available
74// on `wasm32`.
75
76/// Render the type-list clause as quoted items only — `"'X'"` for one
77/// declarer, `"'X', 'Y'"` for many — without a leading "type" /
78/// "types" word. Caller composes the leading word via
79/// [`type_word_for`] so prose contexts like `"of types ..."` don't
80/// produce the duplicate-word output `"of types types '...'"`.
81pub(crate) fn format_types_clause(types: &[String]) -> String {
82 types
83 .iter()
84 .map(|t| format!("'{t}'"))
85 .collect::<Vec<_>>()
86 .join(", ")
87}
88
89/// Leading word to pair with [`format_types_clause`]: `"type"` for a
90/// single declarer, `"types"` for many. Empty slice maps to `"types"`
91/// (callers should not invoke this for an empty list; the typed-
92/// warning sites guard the `is_empty` case already).
93pub(crate) fn type_word_for(types: &[String]) -> &'static str {
94 if types.len() == 1 { "type" } else { "types" }
95}
96
97// ---------------------------------------------------------------------------
98// CRUD types
99// ---------------------------------------------------------------------------
100
101/// Arguments for creating an entity.
102#[derive(Debug, Clone)]
103pub struct CreateArgs {
104 pub title: String,
105 pub mem: String,
106 pub entity_type: String,
107 /// Section contents keyed by section key: `{ "<section-key>": "..." }`.
108 /// Valid keys depend on the schema (see `TypeDefinition::sections`).
109 pub sections: IndexMap<String, String>,
110 /// Metadata overrides: `{ "<field-key>": "value" }`.
111 pub metadata: IndexMap<String, String>,
112 /// Relationships to create: `[{ target: EntityId, rel_type: "USES" }]`.
113 pub relations: Vec<RelateArg>,
114 /// When true, validate and compute the result but do not write to
115 /// disk, mutate the store, create edges, or commit. Response carries
116 /// the prospective `id`, `file_path`, `content_hash`, and any
117 /// `warnings` — `write_id` is empty.
118 pub dry_run: bool,
119}
120
121/// Arguments for updating an entity.
122#[derive(Debug, Clone)]
123pub struct UpdateArgs {
124 pub id: EntityId,
125 /// Expected content hash (optimistic locking). Required.
126 pub expected_hash: String,
127 /// Section fields to set: `{ "<section-key>": "new content" }`.
128 pub sections: IndexMap<String, String>,
129 /// Section fields to append to: `{ "<section-key>": "extra content" }`.
130 pub append_sections: IndexMap<String, String>,
131 /// Section fields to patch: `{ "<section-key>": PatchArg { old, new } }`.
132 pub patch_sections: IndexMap<String, PatchArg>,
133 /// Metadata fields to set: `{ "<field-key>": "value" }`.
134 pub metadata: IndexMap<String, String>,
135 /// Metadata keys to remove from the entity. Silent no-op on absent
136 /// keys. Errors on read-only fields (mem, id, type) and on
137 /// schema-required fields for the entity's type.
138 pub metadata_unset: Vec<String>,
139 /// Dry-run mode — return proposed changes without persisting.
140 pub dry_run: bool,
141}
142
143/// Arguments for a patch (substring replacement).
144#[derive(Debug, Clone)]
145pub struct PatchArg {
146 pub old: String,
147 pub new: String,
148 /// When `true`, replace every occurrence of `old` in the target
149 /// section. Default `false` replaces only the first occurrence.
150 pub all: bool,
151}
152
153/// Section-level mutations applied by a single `memstead_update` call.
154/// Each vec lists the section keys that landed in that mutation mode.
155/// Empty inner vecs are serde-omitted so the wire stays quiet; the
156/// struct itself always serialises so the outer `modified_sections` key
157/// is a stable shape regardless of what the call actually touched.
158#[derive(Debug, Clone, Default, Serialize)]
159pub struct ModifiedSections {
160 /// Section keys whose body was replaced wholesale (`sections` input).
161 #[serde(default, skip_serializing_if = "Vec::is_empty")]
162 pub replaced: Vec<String>,
163 /// Section keys whose body received an append (`append_sections`).
164 #[serde(default, skip_serializing_if = "Vec::is_empty")]
165 pub appended: Vec<String>,
166 /// Section keys whose body was patched via find-and-replace
167 /// (`patch_sections`).
168 #[serde(default, skip_serializing_if = "Vec::is_empty")]
169 pub patched: Vec<String>,
170 /// Section keys removed outright — heading and body (`sections_unset`).
171 #[serde(default, skip_serializing_if = "Vec::is_empty")]
172 pub unset: Vec<String>,
173}
174
175/// Metadata-level mutations applied by a single `memstead_update` call.
176/// Same empty-vec-omit convention as `ModifiedSections`; auto-timestamp
177/// metadata fields written by the engine are NOT surfaced here (they are
178/// engine-driven, not user-driven — the caller has nothing to react to).
179#[derive(Debug, Clone, Default, Serialize)]
180pub struct ModifiedMetadata {
181 /// Metadata keys whose value was set or replaced.
182 #[serde(default, skip_serializing_if = "Vec::is_empty")]
183 pub set: Vec<String>,
184 /// Metadata keys that were removed from the frontmatter.
185 #[serde(default, skip_serializing_if = "Vec::is_empty")]
186 pub unset: Vec<String>,
187}
188
189/// Result of an update operation.
190#[derive(Debug, Clone, Serialize)]
191pub struct UpdateResult {
192 pub id: EntityId,
193 pub title: String,
194 /// Section-level mutations grouped by mode. Replaces the former flat
195 /// `modified_fields: Vec<String>` (which leaked mode as a string
196 /// prefix and collided on bare keys with `modified_metadata`).
197 pub modified_sections: ModifiedSections,
198 /// Metadata-level mutations grouped by direction (set vs unset).
199 pub modified_metadata: ModifiedMetadata,
200 pub modified_date: String,
201 /// On a real (non-dry-run) update: the new on-disk content hash after
202 /// the write. On a dry-run: the **current** on-disk hash (unchanged) —
203 /// the value an agent passes back as `expected_hash` on the follow-up
204 /// real call. Pair with `prospective_hash` to predict the post-write
205 /// hash without a second read. Wire key `_hash`.
206 #[serde(rename = "_hash")]
207 pub content_hash: String,
208 /// Dry-run only: the hash the entity *would* have after the proposed
209 /// write. `None` on real (non-dry-run) updates. Lets agents preview a
210 /// change and then call the real update with `expected_hash =
211 /// content_hash` (pinning the disk state) while still knowing what the
212 /// post-write hash will look like. Additive optional field — stable
213 /// shape for callers that ignore it.
214 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub prospective_hash: Option<String>,
216 /// The identity the mem's backend minted for this write: a commit
217 /// SHA on a git-branch mem, an opaque synthetic token on a folder
218 /// or in-memory mem. It is an identity and NOT a change cursor —
219 /// `memstead_changes_since` takes a commit SHA on a git-branch mem
220 /// and an RFC3339 ledger timestamp on a folder mem, and feeding it
221 /// this token refuses with `INVALID_CURSOR` (before that guard it
222 /// silently replayed a folder mem's whole history).
223 /// Empty for dry runs (no write happens).
224 #[serde(default)]
225 pub write_id: String,
226 /// Typed non-fatal issues — same shape as `CreateResult::warnings`.
227 /// Pre-Bug-4 this was `Vec<String>` and unused; now carries
228 /// `WarningHint` so e.g. `INLINE_WIKI_LINK_AUTO_STUBBED` from update
229 /// flows out via the same `{code, message, details}` envelope agents
230 /// already branch on for create-time warnings.
231 #[serde(default, skip_serializing_if = "Vec::is_empty")]
232 pub warnings: Vec<WarningHint>,
233}
234
235/// Typed non-fatal issue surfaced from engine operations. Serialises as the
236/// uniform `{ code, message, details }` envelope so a generic warning handler
237/// (log sink, UI, alerting) can read `code` + `message` without branching on
238/// variant. `Display` renders the agent-facing text, reachable via
239/// [`WarningHint::message`]; per-variant structured fields land under
240/// `details`, their shape keyed by `code`.
241///
242/// Shared across `CreateResult`, `RelateResult`, and `HealthSummary`. New
243/// variants are additive; they widen the enum rather than fork a per-site
244/// type so wire-level warning consumers keep a single discriminated union
245/// to branch on. The wire shape matches what [`envelope`] produces for the
246/// MCP error channel, so one decoder handles both surfaces.
247#[derive(Debug, Clone)]
248pub enum WarningHint {
249 /// A required section was empty or missing at create time. Carries
250 /// the type and section keys plus the section's own `write_rules`
251 /// so the agent can self-correct with a follow-up `memstead_update`.
252 /// Type-level `write_rules` no longer ride per warning — they
253 /// ship once at the mutation-response top level on
254 /// `type_guidance` keyed by `entity_type` (F9). Decoders look up
255 /// the guidance via `entity_type` against the top-level map.
256 MissingRequiredSection {
257 entity_type: String,
258 key: String,
259 heading: String,
260 write_rules: Vec<String>,
261 },
262 /// A required metadata field was not supplied at create time and the
263 /// schema does not auto-fill the value (no `default_value`, no
264 /// `init_timestamp`, no `auto_timestamp`). The entity still lands —
265 /// the generator may write an empty / today's-date placeholder into
266 /// the frontmatter — but the warning surfaces the gap so the agent
267 /// follows up via `memstead_update` rather than leaving the entity in a
268 /// stuck state. Payload mirrors [`Self::MissingRequiredSection`] in
269 /// shape so a single decoder handles both. Wire-equivalent shape
270 /// with `EngineError::RequiredFieldUnset`'s `details` payload, since
271 /// the recovery path is the same (read the description / allowed
272 /// enum values from the envelope rather than re-fetching the
273 /// schema).
274 MissingRequiredField {
275 entity_type: String,
276 key: String,
277 description: String,
278 enum_values: Vec<String>,
279 },
280 /// An undeclared relationship was admitted because the mem's schema
281 /// is in open mode. The caller can still suggest the name be added to
282 /// the schema vocabulary.
283 UndeclaredRelationshipOpen { rel_type: String, message: String },
284 /// `memstead_relate` was asked to add an edge that already exists. The
285 /// op is a successful no-op — the warning surfaces what would otherwise
286 /// be silent so an agent relying on `renames` / side-effects can notice
287 /// the call didn't change the graph.
288 DuplicateRelationship {
289 rel_type: String,
290 from: EntityId,
291 to: EntityId,
292 },
293 /// `memstead_relate` with `remove: true` was asked to drop an edge that
294 /// wasn't present. Successful no-op, surfaced so an agent operating on
295 /// a stale mental model sees the mismatch.
296 NoSuchRelationship {
297 rel_type: String,
298 from: EntityId,
299 to: EntityId,
300 },
301 /// An `include` key passed to `memstead_health` was outside the accepted
302 /// set. The key is ignored; the allowed list is echoed back verbatim so
303 /// an agent with a typo can correct on the next call without opening a
304 /// schema doc.
305 UnknownIncludeKey { key: String, allowed: Vec<String> },
306 /// A paged/bounded parameter exceeded its cap. The cap is authoritative
307 /// so the op still ran, but the warning surfaces what the caller
308 /// requested vs. what was served.
309 LimitClamped { requested: usize, actual: usize },
310 /// `memstead_rename` was asked to change the title but normalisation
311 /// (lowercase, diacritic-folding, punctuation-strip, hyphen-collapse)
312 /// mapped the requested title to the existing slug — so the id is
313 /// unchanged and nothing is written to disk. Surfaced so autonomous
314 /// skills don't mistake the silent short-circuit for a successful
315 /// cosmetic rewrite.
316 TitleNormalizedToSlugNoop {
317 requested_title: String,
318 current_slug: String,
319 },
320 /// The title grammar admits any single-line text, but the slug
321 /// alphabet stays narrow — this create/rename derived an id that
322 /// dropped one or more title characters (`&`, `.`, `§`, …). The
323 /// entity lands with the verbatim title; the warning keeps the
324 /// title↔id divergence visible without being fatal, naming each
325 /// distinct dropped character and the derived slug.
326 TitleCharsDroppedFromSlug {
327 title: String,
328 dropped_chars: Vec<char>,
329 slug: String,
330 },
331 /// `memstead_update` produced a post-mutation entity whose regenerated
332 /// markdown is bytes-identical to the on-disk content — no field,
333 /// section, metadata value, relation, or auto-timestamp actually
334 /// changed. The op is a successful no-op: no disk write, no
335 /// commit, `content_hash` unchanged. Surfaced so autonomous skills
336 /// branching on `write_id != ""` see an explicit signal, and
337 /// `expected_hash`-based polling stays stable across the no-op.
338 /// Mirrors `TitleNormalizedToSlugNoop` for the rename surface.
339 UpdateNoop { id: EntityId },
340 /// `memstead_search` was called with both `stub=true` and `entity_type`
341 /// set. Stubs carry no `entity_type` (they are ID-only placeholders),
342 /// so the combined filter excludes every stub — the call is an empty
343 /// set by construction. Surfaced so an agent doesn't interpret the
344 /// empty result as "no stubs of this type exist" when in fact no
345 /// stub can ever satisfy the filter. Drop `entity_type` to list stubs.
346 StubFilterExcludesAll { entity_type: String },
347 /// `memstead_search(filters: {<key>: ...})` named a filter key that the
348 /// queried type does not declare. The wire `code()` discriminates
349 /// the two outcomes, so a consumer branches on `code` alone:
350 /// - `declared_on_other_types` **empty** → no reachable schema
351 /// declares the key → `UNKNOWN_FILTER_KEY`; the filter is truly
352 /// ignored and the result set equals the same search without it.
353 /// - `declared_on_other_types` **non-empty** → the key is declared
354 /// on other type(s) and the filter was applied with strict
355 /// type-narrowing (result restricted to the declaring type(s), or
356 /// emptied when the call scoped to a non-declaring type) →
357 /// `FILTER_TYPE_SCOPED`.
358 ///
359 /// `declared_on_other_types` stays on the wire as enrichment, not as
360 /// the disambiguator.
361 UnknownFilterKey {
362 key: String,
363 /// `entity_type` the search call scoped to (`None` for an
364 /// unscoped call).
365 scoped_type: Option<String>,
366 /// Types where the filter IS declared, sorted alphabetically.
367 /// Empty when no reachable schema declares the key at all.
368 declared_on_other_types: Vec<String>,
369 },
370 /// `memstead_search(filters: {<field>: ...})` named a field that the
371 /// schema declares but with `filterable: none` — the filter is
372 /// ignored, the hit set is unconstrained by it.
373 FieldNotFilterable { field: String },
374 /// `memstead_search(filters: {<csv-field>: "a,b"})` passed a comma-bearing
375 /// value to a csv-array field. csv fields match a *single* member, so
376 /// the whole rendered value (e.g. the `tags: dedup,retry` an entity
377 /// displays) can never equal any one member — the filter matches
378 /// nothing. Surfaced so an agent that copied the rendered value gets a
379 /// recoverable signal (split into repeated single-member filters)
380 /// rather than an empty result indistinguishable from a true
381 /// no-match. The filter still applies as written (matches nothing);
382 /// this only adds the advisory.
383 FilterValueMultiMember { key: String, value: String },
384 /// `memstead_search(filters: {<field>: <value>})` passed a value the
385 /// schema field constrains with an `enum_values` allow-list, but the
386 /// value (or, for a csv-array field, one of its comma members) is not a
387 /// member. The filter still applies as written and matches nothing for
388 /// that value, so an empty result is otherwise indistinguishable from a
389 /// true no-match — this surfaces the typo plus the allowed values so an
390 /// agent corrects without opening the schema. Reuses the
391 /// `INVALID_ENUM_VALUE` code from the mutation surface.
392 FilterValueNotInEnum {
393 key: String,
394 value: String,
395 allowed: Vec<String>,
396 },
397 /// `memstead_search(related_to: <id>)` reached a neighbourhood larger
398 /// than the cap. The results were ranked by proximity (nearer first)
399 /// and bounded to the nearest `kept` of `total` reachable entities so a
400 /// hub can't flood the caller. Surfaced so the agent knows the
401 /// neighbourhood was truncated — narrow with `depth`/filters for more.
402 NeighbourhoodCapped { kept: usize, total: usize },
403 /// `memstead_search` trimmed the returned page to fit the token budget.
404 /// The highest-ranked `kept` hits that fit under `budget` are returned;
405 /// the rest of the page is dropped so the response stays under the MCP
406 /// transport cap. `_total` still reflects the full match count — page the
407 /// remainder with `offset`, narrow the query, or raise `token_budget`.
408 SearchResultsTruncated { kept: usize, budget: usize },
409 /// `memstead_search(range_filters: {<key>: ...})` named a key that
410 /// doesn't follow the `min_<field>` / `max_<field>` / `<field>_before`
411 /// / `<field>_after` grammar. The key is ignored.
412 RangeFilterKeyMalformed { key: String },
413 /// `memstead_search(range_filters: {<key>: ...})` named a range-filter
414 /// key whose underlying field the queried type does not declare.
415 /// Same shape and same one-code-per-outcome split as
416 /// [`Self::UnknownFilterKey`]: `code()` is `UNKNOWN_RANGE_FILTER_FIELD`
417 /// when `declared_on_other_types` is empty (truly ignored, result =
418 /// unfiltered) and `RANGE_FILTER_TYPE_SCOPED` when non-empty (applied
419 /// with strict type-narrowing). Includes the literal `key` (the
420 /// prefixed/suffixed form the caller sent) alongside the bare `field`.
421 UnknownRangeFilterField {
422 field: String,
423 /// The literal filter key the caller sent, e.g. `min_count`.
424 key: String,
425 scoped_type: Option<String>,
426 declared_on_other_types: Vec<String>,
427 },
428 /// `memstead_search(range_filters: {<field>: ...})` named a field that
429 /// the schema declares but with a filterability other than `range`.
430 /// The range filter is ignored.
431 FieldNotRangeFilterable { field: String },
432 /// `memstead_search` could not query a target mem's search index —
433 /// either the mem has no index yet (`reason: "missing_index"`)
434 /// or a tantivy execution failure surfaced (`reason:
435 /// "query_failed"` plus the error string).
436 SearchMemIndexUnavailable {
437 mem: String,
438 /// Discriminator: `"missing_index"` or `"query_failed"`.
439 reason: &'static str,
440 /// The underlying error string when `reason == "query_failed"`;
441 /// `None` for `"missing_index"`.
442 error: Option<String>,
443 },
444 // There is deliberately no `RenameSimilarityClamped` variant:
445 // out-of-range `rename_similarity` hard-refuses
446 // (`EngineError::RenameSimilarityOutOfRange` → typed
447 // `INVALID_INPUT`) rather than clamping, so the warning channel has
448 // no story to tell and the typed-warning vocabulary tracks the live
449 // wire shape.
450 /// `memstead_create` (or `memstead_rename`) received a `title` with leading
451 /// or trailing whitespace. The engine silently strips the surround
452 /// before slug derivation and storage; the warning records what the
453 /// caller sent vs. what landed so the audit trail can spot the
454 /// drift. Internal whitespace (between words) is preserved
455 /// untouched. Fully-whitespace titles are still refused at the
456 /// validator boundary (those collapse to empty).
457 TitleTrimmed { original: String, trimmed: String },
458 /// An inline wiki-link resolved to an ID of the form
459 /// `<current-mem>--<other-known-mem-suffix>--<slug>`. This is
460 /// almost always drift from a mem-rename — the author wrote
461 /// `[[plugin--slug]]` expecting `plugin` to be the mem prefix, but
462 /// the current mem is `test-mem-plugin`, so the literal
463 /// resolution nests the prefix. Detection only — the load path still
464 /// creates the stub (no silent rewrite). Fix via `memstead_update
465 /// patch_sections` to either the bare slug or the fully-qualified ID.
466 /// Emitted at load / reload / attach time and carried through
467 /// `HealthSummary.warnings`; mutation paths never emit this warning
468 /// to avoid noise on every edit.
469 SuspiciousNestedPrefix {
470 from: EntityId,
471 resolved_id: EntityId,
472 /// Stripped-and-resolved candidate via the two-pass resolver
473 /// (cross-mem lookup first, bare-slug fallback second). `None`
474 /// when no real entity was found — the author must disambiguate.
475 candidate_target: Option<EntityId>,
476 section: String,
477 /// Whether the link's prefix (`resolved_id.mem()`) is itself a
478 /// mounted mem. `true` means the link is a well-formed cross-mem
479 /// reference whose target is missing in that mem (no rename
480 /// happened); `false` means the prefix only resembles a mem
481 /// (it matches a roster member's last name segment), the
482 /// classic mem-rename drift. The message says which, instead
483 /// of calling every case rename drift: on this project's own graph all
484 /// eight recorded hits were missing targets in mounted mems.
485 prefix_mounted: bool,
486 },
487 /// Inline `[[wiki-link]]` syntax in entity section bodies parsed to
488 /// targets that did not yet resolve, so the engine auto-created stub
489 /// entities for them. A common authoring hazard: an agent illustrating
490 /// link syntax in prose (`[[example:slug]]`) inadvertently creates
491 /// ghost stubs and a REFERENCES edge from the prose entity to each.
492 /// Surfaced so the agent reviews the list and either replaces the
493 /// inline literal with a fenced/quoted form or removes the entity if
494 /// the stub was not intended. Carries the source entity id (`from`)
495 /// and every newly-stubbed `target` id created by THIS call.
496 InlineWikiLinkAutoStubbed {
497 from: EntityId,
498 stubs: Vec<EntityId>,
499 },
500 /// A body wiki-link resolved to the entity's own id, so the
501 /// alias-synthesis pass dropped the would-be self-referential edge
502 /// (F11) — a self-edge carries no navigational value and would render
503 /// as both an Outgoing and an Incoming neighbour of itself. The
504 /// create/update still succeeds (the author may have written their
505 /// own slug); this warns so the dropped link is observable, matching
506 /// the alias pass's other side-effect warnings (`AUTO_STUB_CREATED` /
507 /// `INLINE_WIKI_LINK_AUTO_STUBBED`).
508 SelfLinkIgnored { id: EntityId },
509 /// A body wiki-link crossed into a destination whose SCHEMA the
510 /// source schema declares no cross-mem entry for (and no wildcard),
511 /// so the alias-synthesis pass emitted no edge — the schema
512 /// legitimately declines it, and the write still succeeds. Before
513 /// this warning the link became inert prose SILENTLY (found by the
514 /// graph-plans 02 grading: a default-schema scratch mem citing a
515 /// planning mem, 2026-08-28); the write knows it dropped the edge,
516 /// so it says so, naming the target and the declaration gap. The
517 /// remedy is schema-side: declare the destination schema (or a
518 /// wildcard) under `cross_mem_relationships`.
519 CrossSchemaLinkUndeclared {
520 /// The entity carrying the link.
521 from: EntityId,
522 /// The link's resolved target.
523 target: EntityId,
524 /// The source mem's schema (`name@version` display form).
525 source_schema: String,
526 /// The target mem's schema name — the missing `to_schema` entry.
527 target_schema: String,
528 },
529 /// `memstead_relate` to a cross-mem target whose mem is not (yet)
530 /// mounted in the workspace. The cross-mem link policy permits
531 /// the edge, so the engine auto-stubs the target as a forward
532 /// reference — but with the target mem entirely absent from
533 /// `writable_mems()`, the stub has no `_mem_schema` resolution
534 /// and any later read sees an indeterminate-schema entity. The
535 /// warning makes the missing-mem state visible so an operator
536 /// can distinguish a typo (intended `B` but typed `b`) from a
537 /// deliberate forward reference that expects the mem to be
538 /// created later. (F4)
539 CrossMemTargetMemUncreated {
540 from_mem: String,
541 to_mem: String,
542 target_id: EntityId,
543 },
544 /// A mutation landed without a `note` field while the workspace
545 /// config's `[mutations].require_notes = true` — provenance is
546 /// best-effort, so the engine completes the commit but flags the
547 /// absence so autonomous skills can audit their coverage. The
548 /// mutation still writes to disk and produces a commit; this warning
549 /// exists purely to surface the missed opportunity for a human- /
550 /// agent-readable body line. `tool` carries the MCP tool name
551 /// (`memstead_create`, `memstead_update`, …) so consumers can attribute the
552 /// gap without re-deriving it from the response context.
553 NoteMissing { tool: String },
554 /// A create supplied a value for an auto-managed metadata field
555 /// (`init_timestamp` like `created_date`, or `auto_timestamp` like
556 /// `last_modified`); the engine owns those values, so the supplied
557 /// one was discarded and the engine value stamped instead. The
558 /// entity still lands — this warning closes the silent-drop gap so
559 /// the agent learns its input had no effect without a follow-up
560 /// read. `field` names the discarded key; `supplied` echoes the
561 /// rejected value. (The `memstead_update` path refuses the same keys
562 /// outright with `READ_ONLY_FIELD`; create's posture is
563 /// stamp-and-proceed, so it warns rather than refusing.)
564 IgnoredReadonlyField { field: String, supplied: String },
565 /// The workspace is embedded inside another git repository
566 /// (`outer_repo_root`) whose `.gitignore` does not list
567 /// `mem-repo/`. Without that ignore line, the outer repo would
568 /// either swallow `mem-repo-git` as a nested untracked tree or
569 /// (worse) record it as a submodule via gitlink — both shapes
570 /// silently corrupt the mem-repo identity.
571 ///
572 /// Surfaced from `memstead_health` so the agent / operator can fix
573 /// the outer repo's `.gitignore` (or pass `--no-gitignore` at
574 /// `memstead mem-repo init`/`migrate-from-disk` time and accept the
575 /// risk explicitly).
576 OuterRepoNotIgnoringMemRepo {
577 outer_repo_root: String,
578 workspace_root: String,
579 },
580 /// One or more `required_outgoing` blocks on the entity's type are
581 /// not yet satisfied by its post-application outgoing edges. Tier-2
582 /// — the create/update lands; the warning surfaces every unsatisfied
583 /// block in a single payload so the agent can emit one batched
584 /// `memstead_relate` follow-up.
585 MissingRequiredOutgoing {
586 entity_type: String,
587 entity_id: EntityId,
588 /// Each entry mirrors one unsatisfied `RequiredOutgoing` block:
589 /// the alternative relationship names plus the rendered
590 /// cardinality literal (`"at_least_one"`).
591 missing: Vec<MissingRequiredOutgoingBlock>,
592 },
593 /// A successful write moved a declared aggregate signal across a
594 /// threshold, in either direction. Out-of-band diagnostics beside
595 /// the success payload — never error-shaped, never changing the
596 /// mutation's success semantics (a signal crossing on a
597 /// successful write must not read as a failed write). Levels are
598 /// the wire literals `none` / `notice` / `warn`.
599 SignalThresholdCrossed {
600 entity_id: EntityId,
601 signal: String,
602 value: u64,
603 old_level: String,
604 new_level: String,
605 },
606 /// The written entity violates warn-tier declared `constraints`
607 /// of its type (e.g. `requires_when`: a field required under the
608 /// current value of another field is unset). Block-tier violations
609 /// refuse instead ([`EngineError::ConstraintUnsatisfied`]) — the
610 /// warning only ever carries `severity: warn` entries.
611 ConstraintUnsatisfied {
612 entity_type: String,
613 entity_id: EntityId,
614 violations: Vec<crate::ops::health::UnsatisfiedConstraint>,
615 },
616 /// A markdown file declared the same `## <Heading>` twice or more for a
617 /// schema-declared section key. The parser keeps the first occurrence's
618 /// body and drops the rest — the duplicate headers and their bodies are
619 /// removed from the storage value, so the next read-modify-write cycle
620 /// emits a single heading. Surfaced so the operator (or the next ingest
621 /// cycle) sees that content was discarded; common cause is an agent
622 /// appending a section instead of replacing it.
623 ///
624 /// Emitted at load / reload / attach time only; mutation paths do not
625 /// re-parse the just-written file.
626 DuplicateSectionHeading {
627 entity_id: EntityId,
628 section_key: String,
629 heading: String,
630 occurrences: usize,
631 },
632 /// The engine detected that a sibling writer (another `Engine`
633 /// instance, an out-of-band `git pull`, etc.) advanced the on-disk
634 /// HEAD of `mem` past the engine's cached `last_known_head`, so
635 /// the engine reloaded that mem's slice of the in-memory store
636 /// before serving the current call. The response carries fresh
637 /// content; the warning explains why state shifted under the
638 /// caller. Agents that need the per-entity diff call
639 /// `memstead_changes_since` with the supplied `old_head`.
640 MemReloaded {
641 mem: String,
642 old_head: String,
643 new_head: String,
644 entities_loaded: usize,
645 },
646 /// `MEM_ROSTER_CHANGED`: the mount roster changed since the engine last
647 /// reconciled it (a mem registered or unregistered by another process),
648 /// and the engine applied the change before serving this call: `added`
649 /// mems mounted cold, `removed` mems unmounted (their cached hashes are
650 /// void, an operation naming one refuses `MEM_UNMOUNTED`),
651 /// `quarantined` mems failed to mount under the boot rules and are on
652 /// the quarantine roster with their reason, `failures` names anything
653 /// that could not be applied (that part is retried next operation).
654 MemRosterChanged {
655 added: Vec<String>,
656 removed: Vec<String>,
657 quarantined: Vec<String>,
658 failures: Vec<String>,
659 },
660 /// `OUT_OF_BAND_EDITS_UNDETECTED`: this folder mem's drift cursor is its
661 /// own change ledger, which only the engine writes, so an edit made to the
662 /// files by anything else advances nothing.
663 ///
664 /// The engine keeps serving pre-edit content and `changes_since` reports
665 /// the edit as never having happened. It is not fixable cheaply: the
666 /// staleness probe runs before every operation, and turning it into a
667 /// directory walk would change the cost profile of the whole folder
668 /// backend. So the engine says it cannot detect them rather than staying
669 /// quiet, and `memstead health --include ledger` reconciles on demand.
670 ///
671 /// Never fires for a git-branch mem: its change set is a real two-tree
672 /// diff, so the condition cannot arise.
673 OutOfBandEditsUndetected { mem: String },
674 /// A destination entity of a projection binding names an in-scope source
675 /// artifact in its prose and carries no anchor on it — a claim no verify
676 /// watches on the entity's behalf. Read off the binding's findings store
677 /// (the `unanchored-mention` class the verify pass records); warn-level,
678 /// never a refusal. Remedy: anchor the artifact on the entity
679 /// (`memstead_update` with `anchors`), or exclude the artifact with a
680 /// rationale (`memstead projection exclude`).
681 UnanchoredMention {
682 mem: String,
683 binding: String,
684 entity: EntityId,
685 artifact: String,
686 section: String,
687 },
688 /// A config write found the stored config had moved on from what this
689 /// engine last observed: another writer changed it in between.
690 ///
691 /// The write still lands. It is applied to the CONFIG THAT IS THERE, not
692 /// to the engine's cached copy, so the intervening writer's fields
693 /// survive; `fields` names what they had changed. The warning exists
694 /// because a caller who set one field and finds three different is owed
695 /// the explanation on the response that did it, not in a log.
696 ///
697 /// Never fires in a single-writer workspace: the cached copy equals the
698 /// file there, so there is nothing to report.
699 ConfigWriteIntervened { mem: String, fields: Vec<String> },
700 /// A mutation verb was given an entity id without its mem prefix
701 /// and exactly one mounted mem carried an entity of that slug, so
702 /// the verb acted on that entity. Announced, never silent: the
703 /// caller learns the full id the write landed on, and a second
704 /// mem gaining the slug later turns the same call into an
705 /// `ENTITY_ID_MISSING_MEM` refusal rather than a silent retarget.
706 ShortIdResolved { given: String, resolved: EntityId },
707 /// `memstead_relate` add path landed on a not-yet-real target id and
708 /// the engine materialised a stub at that id (in-memory upsert; the
709 /// file lands when a follow-up `memstead_create` promotes the stub).
710 /// Pre-fix surfaced through a top-level `stub_warning: Option<String>`
711 /// field on the relate response — agents iterating `warnings[]` to
712 /// surface non-fatal findings silently skipped the auto-stub case.
713 /// Carries the materialised stub id so the agent can pin a
714 /// follow-up `memstead_create` (or `memstead_relate remove=true` to drop
715 /// the edge before authoring). `pending` marks the dry-run path:
716 /// the rehearsal validated the add and REPORTS the would-be stub
717 /// without writing it — the code stays `AUTO_STUB_CREATED`
718 /// (response-shape stability), only the message branches, so a
719 /// rehearsed response never claims a performed effect.
720 AutoStubCreated { stub_id: EntityId, pending: bool },
721 /// A duplicate-add `memstead_relate` on a derivation-declared
722 /// rel-type refreshed the edge's baseline —
723 /// the agent's explicit "I have reviewed the target's change; the
724 /// derivation still holds". Sidecar-only: `_hash` unchanged, the
725 /// edge unchanged; the response carries this warning so the
726 /// refresh is stated rather than a bare no-op.
727 DerivationBaselineRefreshed {
728 from: EntityId,
729 rel_type: String,
730 to: EntityId,
731 },
732 /// A relation parsed from an entity's `## Relationships` section
733 /// at load time failed validation against the source mem's
734 /// schema (or wiki-link grammar). The entity itself loads
735 /// normally; the offending relation is dropped from the
736 /// in-memory store. `reason` discriminates:
737 /// - `unknown_rel_type` — the rel-type is not declared in the
738 /// source mem's schema and the schema is in `strict` mode.
739 /// - `shape` — the `(source_type, target_type)` pair is not
740 /// allowed by the rel-type's `source_types` / `target_types`.
741 /// - `cycle` — adding this relation would close a cycle in an
742 /// acyclic-declared subgraph (emitted by the post-load
743 /// second-pass cycle check; not yet implemented).
744 ///
745 /// Hand-edits, external tooling, and embedder editor
746 /// surfaces can inject relations that bypass `memstead_relate`; the
747 /// parse-path validation catches those. Mutation-path writes
748 /// pre-validated by the engine never trip this warning.
749 ///
750 /// `origin` discriminates the source mount's capability:
751 /// `"writable"` (the operator can fix the source markdown via
752 /// `memstead_update` / `memstead_relate` and re-run) or `"readonly"`
753 /// (the source mem is mounted read-only — purely diagnostic,
754 /// the operator either uninstalls the archive or accepts the
755 /// dropped relation).
756 ///
757 /// `recovery` carries an abstract-action payload sufficient to
758 /// reverse the drop without consulting another response. `Some`
759 /// when `origin == "writable"` — the engine can rewrite the
760 /// source markdown via the mutation surface, so a consumer (an
761 /// agent walking `memstead_health`, a bulk-fix orchestrator, a
762 /// UI drift panel) maps `kind` to the concrete call on
763 /// whichever MCP / CLI surface it uses. `None` when
764 /// `origin == "readonly"` — the source markdown is not reachable
765 /// via the engine, so no abstract action exists; the warning's
766 /// message names the operator-level path (uninstall the archive
767 /// or accept the drop).
768 ParsedRelationInvalid {
769 entity_id: EntityId,
770 rel_type: String,
771 target: EntityId,
772 reason: String,
773 origin: String,
774 recovery: Option<ParsedRelationRecovery>,
775 },
776 /// `memstead_delete` (or `memstead_rename`, when implemented) on a
777 /// Write-Mem entity that had **no** Write-Mem referrers but
778 /// **does** have ReadOnly-mount referrers. The on-disk file is
779 /// removed and committed; the in-memory entity is demoted to a
780 /// stub at the same id so the surviving incoming edges from the
781 /// ReadOnly mount(s) keep a valid target. The agent sees
782 /// `memstead_entity <id>` returning a stub immediately and not
783 /// stale data after a server reload — fresh boot from disk
784 /// reconstructs the same stub via the parser's auto-stub-on-
785 /// unresolved-link path. `referrers` carries the surviving
786 /// ReadOnly source ids so the agent can either accept the stub
787 /// or uninstall the archive.
788 ResidualStubForReadOnlyReferrers {
789 id: EntityId,
790 referrers: Vec<EntityId>,
791 },
792 /// `memstead_mem_delete` was called with `delete_files: true` but
793 /// at least one part of the symmetric cleanup did not complete.
794 /// The mem is already unregistered from the router; this
795 /// warning surfaces what survived so an agent reading
796 /// `files_deleted: false` doesn't trigger redundant cleanup or
797 /// blame the wrong layer. `reason` discriminates:
798 /// - `rmdir_failed` — folder-backed mem directory survived
799 /// `remove_dir_all` (filesystem permission, busy handle, …).
800 /// `path` names the directory; `error` carries the OS-level
801 /// diagnostic.
802 /// - `backend_prune_failed` — git-branch backend rejected the
803 /// ref-edit transaction that prunes
804 /// `refs/heads/<branch_leaf>` + `__MEMSTEAD:mems/.../config.json`
805 /// (gitdir IO, concurrent writer racing the ref). `path` is
806 /// `None`; `error` carries the wrapped backend message.
807 ///
808 /// One emission per failed step — both can land in the same
809 /// response when a folder mount somehow has both an rmdir
810 /// failure and a backend cleanup failure (rare; the folder
811 /// backend's `delete_artifacts` is a no-op default).
812 MemFilesNotDeleted {
813 mem: String,
814 reason: String,
815 path: Option<String>,
816 error: Option<String>,
817 },
818 /// `memstead mem init` detected a pre-existing branch + config
819 /// blob carrying the `unregistered_at` tombstone marker that
820 /// `memstead mem unregister` writes — the operator's deliberate
821 /// "preserve for re-attach" signal. The create path adopted the
822 /// residual entities, cleared the tombstone, and registered the
823 /// branch as a writable mount. Audit visibility for the
824 /// reattach so an agent reading the warnings sees what shape
825 /// the new mount took. `unregistered_at` carries the ISO-8601
826 /// timestamp the tombstone recorded so the operator can correlate
827 /// the reattach with a prior unregister event.
828 MemReattachedAfterUnregister {
829 mem: String,
830 unregistered_at: String,
831 },
832 /// One-time boot migration: legacy `readMems` entries found in a
833 /// writable mem's config were converted into workspace-level
834 /// read-only mounts and the legacy key was removed from the
835 /// config. `mems` lists the migrated read-mem names,
836 /// `from_host_mems` the writable mems whose configs carried them.
837 /// A second boot is silent — the source key is gone.
838 ReadMemsMigratedToMounts {
839 mems: Vec<String>,
840 from_host_mems: Vec<String>,
841 },
842 /// Boot-honesty skew: the mem's engine-owned mutation stamp
843 /// (`MemConfig.mutation_stamp`, written after mutations) records a
844 /// different engine version than the running binary. Informative,
845 /// never fatal — the next mutation under this binary re-stamps.
846 /// Absence of a stamp (a pre-stamp mem) never fires this; only a
847 /// present, disagreeing stamp does. Surfaces on boot output and
848 /// `memstead health` without an include gate.
849 EngineVersionSkew {
850 mem: String,
851 /// Engine version the last mutation was performed under.
852 stamped_engine: String,
853 /// Engine version of the running binary.
854 running_engine: String,
855 /// Resolved schema the last mutation validated against.
856 stamped_schema: String,
857 /// Which way the versions differ. Present because "they differ" left
858 /// the reader to work out whether their binary was ahead of the mem
859 /// or behind it, which is the only part that changes what they should
860 /// do.
861 direction: crate::build_info::SkewDirection,
862 },
863 /// Generation-behind hint: the mem's pinned schema resolved from
864 /// the BUILT-IN catalogue and the catalogue registers at least
865 /// one strictly-higher version of the same name (real semver
866 /// ordering). Warn-tier, ungated, never blocking — retention
867 /// seals every shipped version, so the pin keeps working; the
868 /// hint names the newest available generation and the migration
869 /// verb. Locally-installed (workspace-storage) pins are silent:
870 /// the engine only knows generations for built-ins. Surfaces on
871 /// boot output and `memstead health` without an include gate,
872 /// like the skew hint above.
873 SchemaGenerationsBehind {
874 mem: String,
875 /// The pinned ref (`name@version`).
876 pinned: String,
877 /// The newest built-in version registered under the same name.
878 newest: String,
879 },
880 /// The mem was created on storage with no version control (a
881 /// folder mount). Provenance means something WEAKER there than the
882 /// headline "every mutation a reasoned commit": mutations ARE
883 /// recorded — each lands in the folder backend's changelog ledger
884 /// (`.memstead/changes.jsonl`) with its provenance note — but
885 /// there are no commits, the `write_id` every mutation returns
886 /// is a synthetic token rather than a commit and is not a change
887 /// cursor (poll with the last ledger entry's `ts`), and the
888 /// content is not durable until the surrounding repository
889 /// commits it. Emitted once, at
890 /// creation, to whoever is actually acting; never a refusal —
891 /// folder mems are a supported storage class.
892 FolderMemProvenance { mem: String },
893 /// Authoring-drift health axis: a pinned schema's sealed copy
894 /// carries an install-provenance stamp, and the authoring path it
895 /// names is GONE from the working tree. Distinct from
896 /// [`WarningHint::SchemaAuthoringSourceDiverged`] — a missing
897 /// package and a diverged one need different actions. Only
898 /// stamped schemas are checked: on git-branch workspaces the
899 /// authoring folder is typically absent for unstamped seals, so a
900 /// naive existence check would warn on healthy workspaces.
901 SchemaAuthoringSourceMissing {
902 schema_ref: String,
903 stamped_path: String,
904 mems: Vec<String>,
905 },
906 /// Authoring-drift health axis: the stamped authoring path exists
907 /// but its package no longer parses EQUIVALENT to the sealed copy
908 /// the engine runs on (parsed-schema comparison, never raw bytes —
909 /// editor-header comment lines and serialisation reordering do not
910 /// trip it). `detail` says how: a load failure's message, or the
911 /// parsed-difference marker.
912 SchemaAuthoringSourceDiverged {
913 schema_ref: String,
914 stamped_path: String,
915 mems: Vec<String>,
916 detail: String,
917 },
918 /// Low-tier rot axis for UNSTAMPED pins — distinct from the two
919 /// stamped variants above, whose no-false-positive contract stays
920 /// untouched. The pinned schema's sealed package still loads
921 /// tolerantly (the mem runs fine), but its content no longer passes
922 /// current-language AUTHORING validation — so the package is, as of
923 /// the seal, no longer installable, and the (unstamped, therefore
924 /// unlocatable) authoring source it was sealed from has rotted the
925 /// same way unless someone has since fixed it. `detail` carries the
926 /// authoring-tier load error. Remedy: re-author the package under
927 /// the current language and `memstead schema install` it — which
928 /// re-seals AND stamps, handing the check over to the divergence
929 /// axis. An unstamped package that still parses under the authoring
930 /// tier produces no hint.
931 SchemaUnstampedSourceRot {
932 schema_ref: String,
933 mems: Vec<String>,
934 detail: String,
935 },
936 /// A `## Relationships` row was followed by trailing content that
937 /// did not match the canonical em-dash delimiter (` — `, U+2014
938 /// framed by spaces) — ASCII `--`, ASCII `-`, en-dash U+2013, or
939 /// minus U+2212. The relation parses with `description: None`;
940 /// the trailing content is NOT preserved on the in-memory
941 /// `Relationship`, so the next render of this entity normalises
942 /// the row to the simple form `- **TYPE**: [[X]]`. The warning is
943 /// the operator's signal that content was dropped — restore the
944 /// description with an explicit em-dash if it should round-trip.
945 /// Emitted at parse time (load / reload / attach); mutation paths
946 /// never trip it because they go through the typed `description`
947 /// parameter rather than markdown text.
948 AmbiguousDescriptionDelimiter {
949 from: EntityId,
950 rel_type: String,
951 target: EntityId,
952 /// Literal trailing content captured between `]]` and end of
953 /// line — surfaced verbatim so the operator can paste the
954 /// intended text back in with a canonical delimiter.
955 trailing: String,
956 },
957 /// Parse-time variant of [`crate::EngineError::MissingRequiredDescription`].
958 /// A hand-edited `## Relationships` row used a rel-type whose
959 /// schema declares `per_edge_description: required` without a
960 /// trailing description. The relation still loads (the engine
961 /// does not block the file from booting), but the warning
962 /// surfaces the gap so the operator follows up with `memstead_update`
963 /// / `memstead_relate` to author the missing description.
964 ParseMissingRequiredDescription {
965 from: EntityId,
966 rel_type: String,
967 target: EntityId,
968 },
969 /// Parse-time variant of [`crate::EngineError::DescriptionNotPermitted`].
970 /// A hand-edited `## Relationships` row used a rel-type whose
971 /// schema declares `per_edge_description: forbidden` together
972 /// with a trailing em-dash description. The relation still loads
973 /// (the engine does not block the file from booting); the
974 /// description is dropped from the in-memory `Relationship` and
975 /// the next render normalises the row to the simple form. The
976 /// warning surfaces the violation so the operator either removes
977 /// the text from disk or asks the schema author to widen the
978 /// rel-type's posture.
979 ParseDescriptionNotPermitted {
980 from: EntityId,
981 rel_type: String,
982 target: EntityId,
983 },
984 /// A mem's `Mount.schema` expectation (the pin recorded in the
985 /// workspace `mounts.json`) disagreed with the authoritative pin in
986 /// the mem's own per-mem config. Boot resolves the effective
987 /// schema from the mem config (authoritative — a copied/cloned
988 /// mem is self-resolvable); this warning surfaces the discrepancy
989 /// so neither value is silently dropped. Recovery: align the
990 /// `mounts.json` entry to the mem's config, or correct the config.
991 SchemaPinMismatch {
992 /// Mem whose mount expectation and config pin disagree.
993 mem: String,
994 /// Authoritative pin from the mem's per-mem config.
995 config_pin: String,
996 /// Expectation pin recorded on the workspace mount.
997 mount_pin: String,
998 },
999 /// A mount resolved to nothing: the storage it names does not
1000 /// exist (`missing_ref` for a git-branch mount whose branch was
1001 /// never created or was deleted, `missing_path` for a folder or
1002 /// archive mount whose path is gone) or exists and holds no
1003 /// entity (`empty`). Before this warning a mount pointing at a
1004 /// nonexistent branch sat in the writable roster with zero
1005 /// entities and nothing said so (this project's own workspace carried two
1006 /// such mounts for weeks). Emitted at boot and on reload; a mount
1007 /// that resolves to at least one entity is silent. Lazy mounts are
1008 /// probed for storage presence only (the entity walk is deferred),
1009 /// so `empty` is reported for eager mounts.
1010 MountUnbacked {
1011 /// The mount's mem name.
1012 mem: String,
1013 /// Why it is unbacked.
1014 reason: MountUnbackedReason,
1015 /// What the mount names: the branch ref, the folder path or
1016 /// the archive path, for the operator's repair.
1017 location: String,
1018 },
1019 /// A mutation wrote a section whose emitted heading differs from a
1020 /// heading already present in the file that derives to the same
1021 /// section key. The write still commits — refusing would strand
1022 /// entities written before the round-trip gate existed — but the
1023 /// divergence is surfaced so the caller sees the file's heading
1024 /// text shifting under it (the regenerated file carries the
1025 /// schema's declared heading; the previous text is replaced).
1026 SectionHeadingDivergence {
1027 entity_id: EntityId,
1028 section_key: String,
1029 /// Heading the mutation is writing (the schema's declared one).
1030 writing_heading: String,
1031 /// Different heading the file carried for the same key.
1032 existing_heading: String,
1033 },
1034 /// A mem's resolved (already-installed) schema declares one or
1035 /// more sections whose heading does not derive back to its key —
1036 /// the condition new installs are refused for
1037 /// (`check_section_heading_roundtrip`). Sealed schemas keep
1038 /// loading by contract (refusing at boot would brick the
1039 /// workspace), so the violation surfaces here instead: every write
1040 /// against such a section forks its content into a second heading
1041 /// or the catch-all. Recovery: fix the schema's heading/key pairs
1042 /// and reinstall.
1043 SchemaHeadingRoundtripViolation {
1044 /// Mem whose pinned schema violates the rule.
1045 mem: String,
1046 /// The pinned `<name>@<version>`.
1047 schema_ref: String,
1048 /// Every offending `(type, key, heading, derived_key)` tuple.
1049 violations: Vec<SchemaHeadingViolation>,
1050 },
1051}
1052
1053/// Wire-shape entry inside `SchemaHeadingRoundtripViolation.violations`
1054/// — one section whose declared heading does not derive back to its
1055/// declared key. Mirrors `memstead_schema::HeadingKeyViolation`, kept
1056/// as a local struct so the warning's JSON shape is owned here.
1057#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1058pub struct SchemaHeadingViolation {
1059 pub type_name: String,
1060 pub key: String,
1061 pub heading: String,
1062 pub derived_key: String,
1063}
1064
1065impl From<&memstead_schema::HeadingKeyViolation> for SchemaHeadingViolation {
1066 fn from(v: &memstead_schema::HeadingKeyViolation) -> Self {
1067 Self {
1068 type_name: v.type_name.clone(),
1069 key: v.key.clone(),
1070 heading: v.heading.clone(),
1071 derived_key: v.derived_key.clone(),
1072 }
1073 }
1074}
1075
1076/// Wire-shape entry inside `MissingRequiredOutgoing.missing`. Lists the
1077/// relationship-name alternatives and the rendered cardinality literal
1078/// for one unsatisfied `RequiredOutgoing` block. Custom struct so the
1079/// JSON output is `{ "relationships": [...], "cardinality": "at_least_one" }`
1080/// — identical to the schema YAML shape, so an agent can copy the
1081/// envelope's `details.missing` entry directly into a `memstead_relate`
1082/// plan without renaming fields.
1083#[derive(Debug, Clone, Serialize)]
1084pub struct MissingRequiredOutgoingBlock {
1085 pub relationships: Vec<String>,
1086 pub cardinality: String,
1087 /// The block's declared severity. Serialized only for `block` —
1088 /// warn is the default the vocabulary has always had, and existing
1089 /// consumers keep their byte-identical `{ relationships,
1090 /// cardinality }` shape.
1091 #[serde(skip_serializing_if = "severity_is_warn")]
1092 pub severity: memstead_schema::ConstraintSeverity,
1093 /// The condition that armed a conditional block (`when_field` /
1094 /// `when_value` on the declaration). Serialized only when present,
1095 /// so unconditional blocks keep their byte-identical shape — and
1096 /// the reader of a refusal, warning, or health finding sees which
1097 /// trigger armed the obligation.
1098 #[serde(skip_serializing_if = "Option::is_none")]
1099 pub when_field: Option<String>,
1100 #[serde(skip_serializing_if = "Option::is_none")]
1101 pub when_value: Option<String>,
1102}
1103
1104fn severity_is_warn(s: &memstead_schema::ConstraintSeverity) -> bool {
1105 *s == memstead_schema::ConstraintSeverity::Warn
1106}
1107
1108/// Abstract recovery action attached to a `PARSED_RELATION_INVALID`
1109/// warning when the source mem is writable. The shape is tool-
1110/// agnostic: it names *what* to do, not *which tool* to call. A
1111/// consumer (agent, bulk-fix orchestrator, app surface) maps `kind`
1112/// to the concrete call on whichever MCP / CLI path it
1113/// uses; the warning's payload itself does not drift when the
1114/// mutation surface evolves.
1115///
1116/// `kind` is the discriminator. Additive — new variants may land as
1117/// the recovery taxonomy grows. Current values:
1118///
1119/// - `"remove_explicit_relation"` — drop the relation from the
1120/// source entity's `## Relationships` section. Agents map this to
1121/// `memstead_relate { from: source_id, to: target_id, type: rel_type,
1122/// remove: true }`. The CLI maps it to the equivalent
1123/// `memstead relate --remove` invocation. The bulk-fix consumer reads
1124/// `source_id`, `target_id`, `rel_type` straight from the payload.
1125///
1126/// The mirrored `source_id` / `target_id` / `rel_type` fields are
1127/// redundant with the warning's `entity_id` / `target` / `rel_type`
1128/// — duplication is intentional. A consumer that branches on
1129/// `recovery` and forwards the payload downstream does not need to
1130/// stitch the warning's top-level fields back in.
1131#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1132pub struct ParsedRelationRecovery {
1133 pub kind: String,
1134 pub source_id: EntityId,
1135 pub target_id: EntityId,
1136 pub rel_type: String,
1137}
1138
1139impl ParsedRelationRecovery {
1140 /// Stable discriminator for the "drop the relation from the
1141 /// source markdown" recovery — the only abstract action this
1142 /// warning emits today.
1143 pub const KIND_REMOVE_EXPLICIT_RELATION: &'static str = "remove_explicit_relation";
1144
1145 /// Constructor for the standard `remove_explicit_relation`
1146 /// recovery — the only shape produced by the parser today.
1147 /// Emission sites use this so the discriminator string lives in
1148 /// one place.
1149 pub fn remove_explicit_relation(
1150 source_id: EntityId,
1151 target_id: EntityId,
1152 rel_type: String,
1153 ) -> Self {
1154 Self {
1155 kind: Self::KIND_REMOVE_EXPLICIT_RELATION.to_string(),
1156 source_id,
1157 target_id,
1158 rel_type,
1159 }
1160 }
1161}
1162
1163/// Per-entry result of an `apply_parse_recovery` call. One entry per
1164/// `PARSED_RELATION_INVALID` warning the engine observed at the call
1165/// site: the bulk-fix dispatches the writable-origin recoveries and
1166/// reports the read-only-origin warnings as skipped. Wire-equivalent
1167/// across the MCP and CLI surfaces; the renderer chooses the
1168/// shape it prefers.
1169///
1170/// `outcome` is the stable discriminator. Current values:
1171/// - `"removed"` — the source entity was re-rendered; the parse-time-
1172/// dropped row no longer appears in the on-disk markdown. `reason`
1173/// is `None`.
1174/// - `"skipped"` — the engine intentionally did not attempt the
1175/// recovery. `reason` carries a stable code: `"readonly_mount"`
1176/// (source mem is read-only and not engine-writable).
1177/// - `"failed"` — the engine attempted the recovery and the underlying
1178/// mutation surfaced a typed error. `reason` carries the engine's
1179/// `UPPER_SNAKE_CASE` error code (`HASH_MISMATCH`,
1180/// `WIKILINK_WITHOUT_RELATION`, etc.). The original entity-side
1181/// drift survives and will surface again on the next reload.
1182#[derive(Debug, Clone, Serialize)]
1183pub struct ParseRecoveryEntry {
1184 pub entity_id: EntityId,
1185 pub rel_type: String,
1186 pub target: EntityId,
1187 pub outcome: String,
1188 #[serde(default, skip_serializing_if = "Option::is_none")]
1189 pub reason: Option<String>,
1190}
1191
1192impl ParseRecoveryEntry {
1193 pub const OUTCOME_REMOVED: &'static str = "removed";
1194 pub const OUTCOME_SKIPPED: &'static str = "skipped";
1195 pub const OUTCOME_FAILED: &'static str = "failed";
1196
1197 /// Stable reason value for read-only-origin warnings the bulk-fix
1198 /// cannot act on — the source markdown is not engine-writable.
1199 pub const REASON_READONLY_MOUNT: &'static str = "readonly_mount";
1200}
1201
1202/// Outcome of `Engine::apply_parse_recovery`. Carries one
1203/// `ParseRecoveryEntry` per parse-time-dropped relation observed at
1204/// the call site plus the last successful commit sha for callers that
1205/// want to poll `memstead_changes_since` for the per-entity diff. An empty
1206/// `entries` list means the workspace was already clean.
1207///
1208/// Idempotency: re-running on a workspace where the writable drops
1209/// were already cleaned produces an empty `entries` list (no work,
1210/// no commits, no errors).
1211#[derive(Debug, Clone, Default, Serialize)]
1212pub struct ParseRecoveryReport {
1213 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1214 pub entries: Vec<ParseRecoveryEntry>,
1215 /// The backend's identity for the last successful per-source
1216 /// re-render the bulk-fix performed — a commit SHA on a git-branch
1217 /// mem, a synthetic token on a folder mem, and never a change
1218 /// cursor. Empty when no recovery wrote to disk
1219 /// (workspace already clean, only read-only warnings, or every
1220 /// writable attempt failed).
1221 #[serde(default, skip_serializing_if = "String::is_empty")]
1222 pub write_id: String,
1223}
1224
1225impl fmt::Display for WarningHint {
1226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 match self {
1228 WarningHint::SchemaPinMismatch {
1229 mem,
1230 config_pin,
1231 mount_pin,
1232 } => write!(
1233 f,
1234 "mem '{mem}': the workspace mount expects schema '{mount_pin}' but the \
1235 mem's own config pins '{config_pin}' — the config pin is authoritative and \
1236 was used; align the mounts.json entry or the mem config to clear this"
1237 ),
1238 WarningHint::MountUnbacked {
1239 mem,
1240 reason,
1241 location,
1242 } => match reason {
1243 MountUnbackedReason::MissingRef => write!(
1244 f,
1245 "mount '{mem}' is unbacked: its branch {location} does not exist \
1246 (the mem was never created there, or the branch was deleted); create \
1247 it, point the mount at the right branch, or remove the mount"
1248 ),
1249 MountUnbackedReason::MissingPath => write!(
1250 f,
1251 "mount '{mem}' is unbacked: its path {location} does not exist; \
1252 restore the folder or remove the mount"
1253 ),
1254 MountUnbackedReason::Empty => write!(
1255 f,
1256 "mount '{mem}' is unbacked: {location} exists but holds no entity \
1257 (an empty mem serves nothing); author into it or remove the mount"
1258 ),
1259 },
1260 WarningHint::SectionHeadingDivergence {
1261 entity_id,
1262 section_key,
1263 writing_heading,
1264 existing_heading,
1265 } => write!(
1266 f,
1267 "entity '{entity_id}': section '{section_key}' is being written under \
1268 heading '{writing_heading}' but the file carried '{existing_heading}' for \
1269 the same section — the write commits and the regenerated file uses \
1270 '{writing_heading}'; the previous heading text is replaced"
1271 ),
1272 WarningHint::SchemaHeadingRoundtripViolation {
1273 mem,
1274 schema_ref,
1275 violations,
1276 } => {
1277 let list = violations
1278 .iter()
1279 .map(|v| {
1280 format!(
1281 "type '{}' section '{}' heading '{}' (derives to '{}')",
1282 v.type_name, v.key, v.heading, v.derived_key
1283 )
1284 })
1285 .collect::<Vec<_>>()
1286 .join("; ");
1287 write!(
1288 f,
1289 "mem '{mem}': pinned schema '{schema_ref}' declares section heading(s) \
1290 that cannot round-trip to their key(s): {list}. The mem keeps loading, \
1291 but writes to these sections fork content into a second heading or the \
1292 catch-all. Fix the schema's heading/key pairs and reinstall — new \
1293 installs of such a schema are refused"
1294 )
1295 }
1296 WarningHint::MissingRequiredSection {
1297 key,
1298 heading,
1299 write_rules,
1300 ..
1301 } => {
1302 write!(
1303 f,
1304 "required section '{key}' (heading \"{heading}\") is empty — \
1305 entity will show as unhealthy"
1306 )?;
1307 if !write_rules.is_empty() {
1308 write!(f, ". Writing guidance:")?;
1309 for rule in write_rules {
1310 write!(f, "\n - {rule}")?;
1311 }
1312 }
1313 Ok(())
1314 }
1315 WarningHint::MissingRequiredField {
1316 key,
1317 entity_type,
1318 description,
1319 enum_values,
1320 } => {
1321 write!(
1322 f,
1323 "required metadata field '{key}' on type '{entity_type}' was not \
1324 supplied — entity landed with a placeholder. {description}"
1325 )?;
1326 if !enum_values.is_empty() {
1327 write!(f, " Allowed values: [{}].", enum_values.join(", "))?;
1328 }
1329 Ok(())
1330 }
1331 WarningHint::UndeclaredRelationshipOpen { message, .. } => f.write_str(message),
1332 WarningHint::DuplicateRelationship { rel_type, from, to } => write!(
1333 f,
1334 "relationship {rel_type} from {from} to {to} already exists — no-op"
1335 ),
1336 WarningHint::NoSuchRelationship { rel_type, from, to } => write!(
1337 f,
1338 "relationship {rel_type} from {from} to {to} does not exist — no-op"
1339 ),
1340 WarningHint::UnknownIncludeKey { key, allowed } => write!(
1341 f,
1342 "unknown include key '{key}' ignored. Allowed: [{}]",
1343 allowed.join(", ")
1344 ),
1345 WarningHint::LimitClamped { requested, actual } => write!(
1346 f,
1347 "limit clamped from {requested} to {actual} (max for memstead_health)"
1348 ),
1349 WarningHint::TitleNormalizedToSlugNoop {
1350 requested_title,
1351 current_slug,
1352 } => write!(
1353 f,
1354 "requested title '{requested_title}' normalises to the existing slug \
1355 '{current_slug}' — no change written to disk"
1356 ),
1357 WarningHint::TitleCharsDroppedFromSlug {
1358 title,
1359 dropped_chars,
1360 slug,
1361 } => write!(
1362 f,
1363 "title '{title}' keeps its characters as display text, but the derived \
1364 slug '{slug}' drops {dropped_chars:?} — link this entity by its slug"
1365 ),
1366 WarningHint::UpdateNoop { id } => write!(
1367 f,
1368 "update on {id} produced bytes-identical content — no \
1369 disk write, no commit, content_hash unchanged"
1370 ),
1371 WarningHint::StubFilterExcludesAll { entity_type } => write!(
1372 f,
1373 "stub=true combined with entity_type='{entity_type}' excludes every \
1374 stub — stubs carry no entity_type. Drop entity_type to list stubs."
1375 ),
1376 WarningHint::UnknownFilterKey {
1377 key,
1378 scoped_type,
1379 declared_on_other_types,
1380 } => {
1381 let on_other = !declared_on_other_types.is_empty();
1382 let scoped_matches_other = matches!(
1383 scoped_type.as_deref(),
1384 Some(t) if declared_on_other_types.iter().any(|o| o == t)
1385 );
1386 if let Some(t) = scoped_type.as_deref() {
1387 if on_other && !scoped_matches_other {
1388 let word = type_word_for(declared_on_other_types);
1389 let items = format_types_clause(declared_on_other_types);
1390 return write!(
1391 f,
1392 "filter '{key}' applied with strict type-exclusion semantics — exists on {word} {items} but the query scoped to type '{t}', where it is not declared. All entities of type '{t}' will be excluded; scope to a declaring type to apply the filter."
1393 );
1394 }
1395 return write!(
1396 f,
1397 "unknown filter key '{key}' for type '{t}' — filter ignored"
1398 );
1399 }
1400 if on_other {
1401 let word = type_word_for(declared_on_other_types);
1402 let items = format_types_clause(declared_on_other_types);
1403 return write!(
1404 f,
1405 "filter '{key}' applied with strict type-exclusion semantics — only entities of {word} {items} will match. Scope explicitly via entity_type=… to suppress this warning."
1406 );
1407 }
1408 write!(
1409 f,
1410 "unknown filter key '{key}' — no reachable schema declares it — filter ignored"
1411 )
1412 }
1413 WarningHint::FieldNotFilterable { field } => {
1414 write!(f, "field '{field}' is not filterable — filter ignored")
1415 }
1416 WarningHint::FilterValueMultiMember { key, value } => write!(
1417 f,
1418 "filter '{key}={value}' targets a csv-array field but the value contains a comma — \
1419 csv fields match a single member, so the full value matches nothing. Filter on one \
1420 member at a time (e.g. `{key}={first}`)",
1421 first = value.split(',').next().map(str::trim).unwrap_or("").trim(),
1422 ),
1423 WarningHint::FilterValueNotInEnum {
1424 key,
1425 value,
1426 allowed,
1427 } => write!(
1428 f,
1429 "filter '{key}={value}' is not an allowed value for '{key}' — allowed: [{}]. \
1430 The filter applies as written and matches nothing.",
1431 allowed.join(", ")
1432 ),
1433 WarningHint::NeighbourhoodCapped { kept, total } => write!(
1434 f,
1435 "related_to neighbourhood has {total} entities; ranked by proximity and bounded to \
1436 the nearest {kept}. Narrow with `depth` or filters to see fewer, more specific hits."
1437 ),
1438 WarningHint::SearchResultsTruncated { kept, budget } => write!(
1439 f,
1440 "results trimmed to the highest-ranked {kept} hits to fit the {budget}-token budget. \
1441 `_total` is the full match count — page the rest with `offset`, narrow the query, \
1442 or raise `token_budget`."
1443 ),
1444 WarningHint::RangeFilterKeyMalformed { key } => write!(
1445 f,
1446 "range filter key '{key}' must start with 'min_'/'max_' or end with '_before'/'_after' — filter ignored"
1447 ),
1448 WarningHint::UnknownRangeFilterField {
1449 field,
1450 key,
1451 scoped_type,
1452 declared_on_other_types,
1453 } => {
1454 let on_other = !declared_on_other_types.is_empty();
1455 let scoped_matches_other = matches!(
1456 scoped_type.as_deref(),
1457 Some(t) if declared_on_other_types.iter().any(|o| o == t)
1458 );
1459 if let Some(t) = scoped_type.as_deref() {
1460 if on_other && !scoped_matches_other {
1461 let word = type_word_for(declared_on_other_types);
1462 let items = format_types_clause(declared_on_other_types);
1463 return write!(
1464 f,
1465 "range filter field '{field}' (from key '{key}') applied with strict type-exclusion semantics — exists on {word} {items} but the query scoped to type '{t}', where it is not declared. All entities of type '{t}' will be excluded; scope to a declaring type to apply the filter."
1466 );
1467 }
1468 return write!(
1469 f,
1470 "unknown range filter field '{field}' (from key '{key}') for type '{t}' — filter ignored"
1471 );
1472 }
1473 if on_other {
1474 let word = type_word_for(declared_on_other_types);
1475 let items = format_types_clause(declared_on_other_types);
1476 return write!(
1477 f,
1478 "range filter field '{field}' (from key '{key}') applied with strict type-exclusion semantics — only entities of {word} {items} will match. Scope explicitly via entity_type=… to suppress this warning."
1479 );
1480 }
1481 write!(
1482 f,
1483 "unknown range filter field '{field}' (from key '{key}') — no reachable schema declares it — filter ignored"
1484 )
1485 }
1486 WarningHint::FieldNotRangeFilterable { field } => write!(
1487 f,
1488 "field '{field}' is not range-filterable — filter ignored"
1489 ),
1490 WarningHint::SearchMemIndexUnavailable { mem, reason, error } => {
1491 match (*reason, error.as_deref()) {
1492 ("missing_index", _) => {
1493 write!(f, "mem '{mem}' has no search index — query returns no hits")
1494 }
1495 ("query_failed", Some(e)) => {
1496 write!(f, "search index for mem '{mem}' errored: {e}")
1497 }
1498 _ => write!(f, "search index for mem '{mem}' is unavailable ({reason})"),
1499 }
1500 }
1501 WarningHint::TitleTrimmed { original, trimmed } => write!(
1502 f,
1503 "title trimmed of surrounding whitespace: {original:?} → {trimmed:?}"
1504 ),
1505 WarningHint::SuspiciousNestedPrefix {
1506 from,
1507 resolved_id,
1508 candidate_target,
1509 section,
1510 prefix_mounted,
1511 } => {
1512 if *prefix_mounted {
1513 write!(
1514 f,
1515 "wiki-link in {from}#{section} resolves to {resolved_id}: \
1516 target missing in mem {}",
1517 resolved_id.mem()
1518 )?;
1519 } else {
1520 write!(
1521 f,
1522 "wiki-link in {from}#{section} resolves to {resolved_id}: \
1523 prefix '{}' is not a mounted mem (it only matches a mem \
1524 name's last segment, the mem-rename drift pattern)",
1525 resolved_id.mem()
1526 )?;
1527 }
1528 if let Some(cand) = candidate_target {
1529 write!(f, "; did you mean {cand}?")?;
1530 }
1531 Ok(())
1532 }
1533 WarningHint::InlineWikiLinkAutoStubbed { from, stubs } => {
1534 write!(
1535 f,
1536 "{from} contained {n} inline wiki-link(s) that auto-created stub \
1537 entities — review whether the stubs were intended; if not, \
1538 remove the inline syntax or wrap the example in a fenced/quoted \
1539 form. Auto-stubbed targets:",
1540 n = stubs.len(),
1541 )?;
1542 for s in stubs {
1543 write!(f, "\n - {s}")?;
1544 }
1545 Ok(())
1546 }
1547 WarningHint::SelfLinkIgnored { id } => write!(
1548 f,
1549 "{id} contains a body wiki-link to its own id — the self-referential edge \
1550 was dropped (a self-link carries no navigational value). The entity was \
1551 created/updated normally; remove the `[[{slug}]]` link if it was a mistake",
1552 slug = id.name(),
1553 ),
1554 WarningHint::CrossSchemaLinkUndeclared {
1555 from,
1556 target,
1557 source_schema,
1558 target_schema,
1559 } => write!(
1560 f,
1561 "{from} body-links {target}, but schema {source_schema} declares no \
1562 cross_mem_relationships entry for schema '{target_schema}' (and no \
1563 wildcard), so NO edge was emitted — the link is prose only. The write \
1564 succeeded. To make such citations real edges, declare '{target_schema}' \
1565 (or a `to_schema: \"*\"` wildcard) under the source schema's \
1566 cross_mem_relationships",
1567 ),
1568 WarningHint::CrossMemTargetMemUncreated {
1569 from_mem,
1570 to_mem,
1571 target_id,
1572 } => write!(
1573 f,
1574 "cross-mem relate from '{from_mem}' to '{target_id}': \
1575 target mem '{to_mem}' is not mounted in the workspace — \
1576 the auto-stub has no schema resolution until the mem is created. \
1577 If '{to_mem}' is a typo, fix the relate; if forward-reference \
1578 is intended, create the mem to promote the stub."
1579 ),
1580 WarningHint::NoteMissing { tool } => write!(
1581 f,
1582 "{tool} called without a `note` while \
1583 `[mutations].require_notes = true`; the write carries no \
1584 provenance line"
1585 ),
1586 WarningHint::IgnoredReadonlyField { field, supplied } => write!(
1587 f,
1588 "'{field}' is auto-managed by the engine — the supplied \
1589 value '{supplied}' was discarded and the engine value \
1590 stamped instead"
1591 ),
1592 WarningHint::OuterRepoNotIgnoringMemRepo {
1593 outer_repo_root,
1594 workspace_root,
1595 } => write!(
1596 f,
1597 "workspace at '{workspace_root}' is embedded inside the git \
1598 repository at '{outer_repo_root}' but the outer .gitignore \
1599 does not list 'mem-repo/'. Add 'mem-repo/' (or the \
1600 workspace-relative equivalent) to the outer repo's \
1601 .gitignore to keep mem-repo-git out of the outer index."
1602 ),
1603 WarningHint::SignalThresholdCrossed {
1604 entity_id,
1605 signal,
1606 value,
1607 old_level,
1608 new_level,
1609 } => write!(
1610 f,
1611 "signal '{signal}' on {entity_id} crossed a declared threshold: \
1612 {old_level} → {new_level} (value {value})"
1613 ),
1614 WarningHint::MissingRequiredOutgoing {
1615 entity_type,
1616 entity_id,
1617 missing,
1618 } => {
1619 write!(
1620 f,
1621 "{entity_id} ({entity_type}) is missing required outgoing edges — \
1622 schema declares {n} `required_outgoing` block(s) still unsatisfied:",
1623 n = missing.len(),
1624 )?;
1625 for block in missing {
1626 write!(
1627 f,
1628 "\n - [{}] cardinality={}",
1629 block.relationships.join(", "),
1630 block.cardinality,
1631 )?;
1632 }
1633 Ok(())
1634 }
1635 WarningHint::ConstraintUnsatisfied {
1636 entity_type,
1637 entity_id,
1638 violations,
1639 } => {
1640 write!(
1641 f,
1642 "{entity_id} ({entity_type}) violates {n} declared constraint(s):",
1643 n = violations.len(),
1644 )?;
1645 for v in violations {
1646 write!(f, "\n - {}", v.describe())?;
1647 }
1648 Ok(())
1649 }
1650 WarningHint::DuplicateSectionHeading {
1651 entity_id,
1652 section_key,
1653 heading,
1654 occurrences,
1655 } => write!(
1656 f,
1657 "{entity_id} declared `## {heading}` {occurrences} times — \
1658 section '{section_key}' kept the first occurrence's body \
1659 and dropped the rest. The next read-modify-write will \
1660 collapse the markdown to one heading."
1661 ),
1662 WarningHint::UnanchoredMention {
1663 binding,
1664 entity,
1665 artifact,
1666 section,
1667 ..
1668 } => write!(
1669 f,
1670 "`{entity}` names `{artifact}` in section `{section}` and carries no anchor on \
1671 it, so no verify under `{binding}` watches that claim. Add the anchor \
1672 (`memstead_update` with `anchors`), or exclude the artifact with a rationale \
1673 (`memstead projection exclude {binding}`).",
1674 ),
1675 WarningHint::OutOfBandEditsUndetected { mem } => write!(
1676 f,
1677 "mem '{mem}' is folder-backed, so its drift cursor is its own change ledger and \
1678 only the engine writes it: an edit made to its files by anything else is not \
1679 detected, and reads keep serving the pre-edit content. Reconcile on demand with \
1680 `memstead health --include ledger`.",
1681 ),
1682 WarningHint::ShortIdResolved { given, resolved } => write!(
1683 f,
1684 "entity id `{given}` carried no mem prefix; exactly one mounted mem holds that \
1685 slug, so this call acted on `{resolved}`. Write the full id to keep the target \
1686 fixed if another mem gains the slug.",
1687 ),
1688 WarningHint::ConfigWriteIntervened { mem, fields } => write!(
1689 f,
1690 "mem '{mem}' config had changed since this engine last read it: another writer \
1691 set {}. This write was applied on top of theirs, so nothing of theirs was \
1692 lost.",
1693 fields.join(", "),
1694 ),
1695 WarningHint::MemReloaded {
1696 mem,
1697 old_head,
1698 new_head,
1699 entities_loaded,
1700 } if old_head.is_empty() => write!(
1701 f,
1702 "mem '{mem}' was reloaded — its branch appeared at {new_head} \
1703 (born, fetched or pushed into place since the engine last \
1704 read the mem, which had loaded it empty). {entities_loaded} \
1705 entities loaded; response carries fresh content. Re-derive \
1706 any conclusions that depended on the prior content of this \
1707 mem before continuing."
1708 ),
1709 WarningHint::MemReloaded {
1710 mem,
1711 old_head,
1712 new_head,
1713 entities_loaded,
1714 } => write!(
1715 f,
1716 "mem '{mem}' was reloaded — on-disk HEAD advanced from \
1717 {old_head} to {new_head} (a sibling writer or out-of-band \
1718 commit landed since the engine last read the mem). \
1719 {entities_loaded} entities reloaded; response carries \
1720 fresh content. Re-derive any conclusions that depended on \
1721 the prior content of this mem before continuing. Call \
1722 `memstead_changes_since since={old_head}` for the per-entity \
1723 diff."
1724 ),
1725 WarningHint::MemRosterChanged {
1726 added,
1727 removed,
1728 quarantined,
1729 failures,
1730 } => write!(
1731 f,
1732 "the mount roster changed and the engine reconciled it before serving this \
1733 call — added: [{}], removed: [{}], quarantined: [{}]{}. Cached hashes for a \
1734 removed mem are void; an operation naming it refuses MEM_UNMOUNTED.",
1735 added.join(", "),
1736 removed.join(", "),
1737 quarantined.join(", "),
1738 if failures.is_empty() {
1739 String::new()
1740 } else {
1741 format!("; not applied: {}", failures.join("; "))
1742 }
1743 ),
1744 WarningHint::AutoStubCreated { stub_id, pending } => {
1745 if *pending {
1746 write!(
1747 f,
1748 "target '{stub_id}' does not exist — a stub would be \
1749 auto-created by the real call. Promote it via \
1750 memstead_create first, or let the real call create \
1751 the stub (adoption preserves the incoming edge)."
1752 )
1753 } else {
1754 write!(
1755 f,
1756 "target '{stub_id}' did not exist — stub auto-created. \
1757 Promote it via memstead_create when authoring the real \
1758 entity (stub adoption preserves the incoming edge)."
1759 )
1760 }
1761 }
1762 WarningHint::DerivationBaselineRefreshed { from, rel_type, to } => write!(
1763 f,
1764 "derivation baseline refreshed: '{from}' -[{rel_type}]-> '{to}' — the edge \
1765 already existed; its baseline now records the target's current content \
1766 hash (reviewed, still holds). Nothing else changed."
1767 ),
1768 WarningHint::ParsedRelationInvalid {
1769 entity_id,
1770 rel_type,
1771 target,
1772 reason,
1773 origin,
1774 recovery: _,
1775 } => {
1776 let recovery_msg = if origin == "readonly" {
1777 "Source mem is mounted read-only; the engine cannot \
1778 rewrite the markdown. Either remove the mount \
1779 (`memstead uninstall <mem>`) or accept the dropped \
1780 relation."
1781 } else {
1782 "Fix the source markdown (via memstead_update / \
1783 memstead_relate — `details.recovery` carries the abstract \
1784 action) or adjust the schema."
1785 };
1786 write!(
1787 f,
1788 "parsed relation {rel_type} from {entity_id} to \
1789 {target} was dropped — reason: {reason}, origin: \
1790 {origin}. The entity loaded but the relation does \
1791 not appear in the in-memory graph. {recovery_msg}"
1792 )
1793 }
1794 WarningHint::ResidualStubForReadOnlyReferrers { id, referrers } => write!(
1795 f,
1796 "{id} was deleted from disk but {n} read-only-mount \
1797 referrer(s) still target it; the in-memory entity is \
1798 demoted to a stub at the same id so the surviving \
1799 incoming edges keep a valid target. Surviving referrers: \
1800 [{}]. Either accept the stub or remove the source mount \
1801 (`memstead uninstall <mem>`) — read-only content cannot \
1802 be rewritten by the engine.",
1803 referrers
1804 .iter()
1805 .map(|r| r.to_string())
1806 .collect::<Vec<_>>()
1807 .join(", "),
1808 n = referrers.len(),
1809 ),
1810 WarningHint::AmbiguousDescriptionDelimiter {
1811 from,
1812 rel_type,
1813 target,
1814 trailing,
1815 } => write!(
1816 f,
1817 "{from} → {target} ({rel_type}): trailing content {trailing:?} \
1818 after `]]` did not match the canonical em-dash delimiter ` — ` \
1819 (U+2014); content dropped, the relation parses with no \
1820 description. Restore with `memstead_relate {from} {rel_type} \
1821 {target} --description \"<text>\"` (or hand-edit using \
1822 ` — `) if the text was intentional."
1823 ),
1824 WarningHint::ParseMissingRequiredDescription {
1825 from,
1826 rel_type,
1827 target,
1828 } => write!(
1829 f,
1830 "{from} → {target} ({rel_type}): rel-type declares \
1831 `per_edge_description: required` but the row has no \
1832 trailing em-dash description. Add one via `memstead_relate \
1833 {from} {rel_type} {target} --description \"<text>\"` (or \
1834 hand-edit the markdown using ` — `)."
1835 ),
1836 WarningHint::ParseDescriptionNotPermitted {
1837 from,
1838 rel_type,
1839 target,
1840 } => write!(
1841 f,
1842 "{from} → {target} ({rel_type}): rel-type declares \
1843 `per_edge_description: forbidden` but the markdown row \
1844 carries a trailing description. The description is \
1845 dropped from the in-memory graph and the next render \
1846 normalises the row to the simple form. Drop the trailing \
1847 text from the source markdown if it should not round-trip."
1848 ),
1849 WarningHint::MemReattachedAfterUnregister {
1850 mem,
1851 unregistered_at,
1852 } => write!(
1853 f,
1854 "mem '{mem}' was reattached to pre-existing storage \
1855 that carried an `unregistered_at: {unregistered_at}` \
1856 tombstone marker. The entities from the prior session \
1857 were adopted; the tombstone has been cleared. If this \
1858 reattach was unexpected, run `memstead mem delete \
1859 {mem}` to destroy the storage and start fresh."
1860 ),
1861 WarningHint::ReadMemsMigratedToMounts {
1862 mems,
1863 from_host_mems,
1864 } => write!(
1865 f,
1866 "legacy `readMems` registrations were migrated to \
1867 workspace-level read-only mounts: [{}] (previously \
1868 attached to writable mem(s) [{}]). The legacy key was \
1869 removed from the config; this migration runs once. \
1870 Remove a migrated read-mem with `memstead uninstall \
1871 <name>`.",
1872 mems.join(", "),
1873 from_host_mems.join(", "),
1874 ),
1875 WarningHint::EngineVersionSkew {
1876 mem,
1877 stamped_engine,
1878 running_engine,
1879 stamped_schema,
1880 direction,
1881 } => write!(
1882 f,
1883 "mem '{mem}': the last mutation was performed by engine \
1884 v{stamped_engine} (against schema {stamped_schema}); \
1885 this binary is engine v{running_engine} ({}). Informative \
1886 only — the next mutation re-stamps. If behaviour \
1887 differs from the last session, the binary changed \
1888 between them.",
1889 match direction {
1890 crate::build_info::SkewDirection::StampedNewer =>
1891 "the mem was last written by a NEWER binary than this one",
1892 crate::build_info::SkewDirection::StampedOlder =>
1893 "the mem was last written by an OLDER binary than this one",
1894 },
1895 ),
1896 WarningHint::SchemaGenerationsBehind {
1897 mem,
1898 pinned,
1899 newest,
1900 } => write!(
1901 f,
1902 "mem '{mem}' pins built-in schema {pinned}, but the \
1903 catalogue registers newer generations up to {newest}. \
1904 The pin keeps working (retained versions stay sealed); \
1905 migrate via `memstead mem set-schema` when ready.",
1906 ),
1907 WarningHint::FolderMemProvenance { mem } => write!(
1908 f,
1909 "mem '{mem}' was created on folder storage with no \
1910 version control. Provenance here is the changelog \
1911 ledger (`.memstead/changes.jsonl`), which records \
1912 every mutation with its note — but there are no \
1913 commits: the `write_id` mutations return is a \
1914 synthetic token rather than a commit, and it is not a \
1915 change cursor — poll this mem with the `ts` of the last \
1916 ledger entry you read. The content is not durable until \
1917 the surrounding repository commits it."
1918 ),
1919 WarningHint::SchemaAuthoringSourceMissing {
1920 schema_ref,
1921 stamped_path,
1922 mems,
1923 } => write!(
1924 f,
1925 "schema '{schema_ref}' (pinned by {}) was installed from \
1926 '{stamped_path}', and that authoring package is no longer \
1927 there. The engine keeps running on its sealed copy — \
1928 nothing is broken — but the source the seal came from is \
1929 gone: restore or move back the package, or re-install \
1930 from its new location to re-stamp.",
1931 mems.join(", ")
1932 ),
1933 WarningHint::SchemaAuthoringSourceDiverged {
1934 schema_ref,
1935 stamped_path,
1936 mems,
1937 detail,
1938 } => write!(
1939 f,
1940 "schema '{schema_ref}' (pinned by {}) no longer matches \
1941 its authoring package at '{stamped_path}': {detail}. The \
1942 engine keeps running on its sealed copy; if the authoring \
1943 change is intended, bump the version and `memstead schema \
1944 install` it.",
1945 mems.join(", ")
1946 ),
1947 WarningHint::SchemaUnstampedSourceRot {
1948 schema_ref,
1949 mems,
1950 detail,
1951 } => write!(
1952 f,
1953 "schema '{schema_ref}' (pinned by {}) has no install-provenance \
1954 stamp, and its sealed package no longer passes current-language \
1955 authoring validation: {detail}. The mem keeps running on the \
1956 tolerantly-loaded seal — nothing is broken — but the package is \
1957 no longer installable as authored. Re-author it under the \
1958 current language and `memstead schema install` it (which also \
1959 stamps it, so future drift is checked).",
1960 mems.join(", ")
1961 ),
1962 WarningHint::MemFilesNotDeleted {
1963 mem,
1964 reason,
1965 path,
1966 error,
1967 } => match (reason.as_str(), path.as_deref(), error.as_deref()) {
1968 ("rmdir_failed", Some(p), Some(e)) => write!(
1969 f,
1970 "mem '{mem}' was unregistered but rmdir of \
1971 {p:?} failed: {e}. Files remain on disk; agent \
1972 may follow up with manual cleanup."
1973 ),
1974 ("rmdir_failed", Some(p), None) => write!(
1975 f,
1976 "mem '{mem}' was unregistered but rmdir of \
1977 {p:?} failed. Files remain on disk."
1978 ),
1979 ("backend_prune_failed", _, Some(e)) => write!(
1980 f,
1981 "mem '{mem}' was unregistered but backend \
1982 artifact cleanup failed: {e}. The mem-repo \
1983 branch and/or `__MEMSTEAD:mems/.../config.json` \
1984 entry may survive; rerun delete with the same \
1985 arguments or have an operator inspect."
1986 ),
1987 ("backend_prune_failed", _, None) => write!(
1988 f,
1989 "mem '{mem}' was unregistered but backend \
1990 artifact cleanup failed. The mem-repo branch \
1991 and/or `__MEMSTEAD` config entry may survive."
1992 ),
1993 _ => write!(
1994 f,
1995 "mem '{mem}' was unregistered but \
1996 `delete_files: true` did not run to completion \
1997 (reason: {reason})."
1998 ),
1999 },
2000 }
2001 }
2002}
2003
2004/// Closed vocabulary of [`WarningHint::MountUnbacked`] reasons, serialised
2005/// as the lowercase `details.reason` value.
2006#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2007pub enum MountUnbackedReason {
2008 /// Git-branch mount: the branch ref does not exist.
2009 MissingRef,
2010 /// Folder or archive mount: the path does not exist.
2011 MissingPath,
2012 /// The storage exists and holds no entity.
2013 Empty,
2014}
2015
2016impl MountUnbackedReason {
2017 /// The wire value (`missing_ref` / `missing_path` / `empty`).
2018 pub fn as_str(self) -> &'static str {
2019 match self {
2020 Self::MissingRef => "missing_ref",
2021 Self::MissingPath => "missing_path",
2022 Self::Empty => "empty",
2023 }
2024 }
2025}
2026
2027impl WarningHint {
2028 /// Stable UPPER_SNAKE_CASE identifier. Wire-level contract — never rename
2029 /// an existing value; new variants add new codes. Agents branch on this,
2030 /// not on [`WarningHint::message`].
2031 pub fn code(&self) -> &'static str {
2032 match self {
2033 Self::InlineWikiLinkAutoStubbed { .. } => "INLINE_WIKI_LINK_AUTO_STUBBED",
2034 Self::CrossMemTargetMemUncreated { .. } => "CROSS_MEM_TARGET_MEM_UNCREATED",
2035 Self::MissingRequiredSection { .. } => "MISSING_REQUIRED_SECTION",
2036 Self::MissingRequiredField { .. } => "MISSING_REQUIRED_FIELD",
2037 Self::UndeclaredRelationshipOpen { .. } => "UNDECLARED_RELATIONSHIP_OPEN",
2038 Self::DuplicateRelationship { .. } => "DUPLICATE_RELATIONSHIP",
2039 Self::NoSuchRelationship { .. } => "NO_SUCH_RELATIONSHIP",
2040 Self::UnknownIncludeKey { .. } => "UNKNOWN_INCLUDE_KEY",
2041 Self::LimitClamped { .. } => "LIMIT_CLAMPED",
2042 Self::TitleNormalizedToSlugNoop { .. } => "TITLE_NORMALIZED_TO_SLUG_NOOP",
2043 Self::TitleCharsDroppedFromSlug { .. } => "TITLE_CHARS_DROPPED_FROM_SLUG",
2044 Self::UpdateNoop { .. } => "UPDATE_NOOP",
2045 Self::StubFilterExcludesAll { .. } => "STUB_FILTER_EXCLUDES_ALL",
2046 // One code per outcome:
2047 // a key declared on some OTHER reachable type was applied
2048 // with strict type-narrowing (the filter took effect — it
2049 // restricts the result to the declaring type(s)), so it
2050 // carries a distinct code from a key no schema declares
2051 // (which is truly ignored). A consumer branches on `code`
2052 // alone to learn whether its filter took effect, without
2053 // inspecting `declared_on_other_types`.
2054 Self::UnknownFilterKey {
2055 declared_on_other_types,
2056 ..
2057 } => {
2058 if declared_on_other_types.is_empty() {
2059 "UNKNOWN_FILTER_KEY"
2060 } else {
2061 "FILTER_TYPE_SCOPED"
2062 }
2063 }
2064 Self::FieldNotFilterable { .. } => "FIELD_NOT_FILTERABLE",
2065 Self::FilterValueMultiMember { .. } => "FILTER_VALUE_MULTI_MEMBER",
2066 Self::FilterValueNotInEnum { .. } => "INVALID_ENUM_VALUE",
2067 Self::NeighbourhoodCapped { .. } => "NEIGHBOURHOOD_CAPPED",
2068 Self::SearchResultsTruncated { .. } => "SEARCH_RESULTS_TRUNCATED",
2069 Self::RangeFilterKeyMalformed { .. } => "RANGE_FILTER_KEY_MALFORMED",
2070 Self::UnknownRangeFilterField {
2071 declared_on_other_types,
2072 ..
2073 } => {
2074 if declared_on_other_types.is_empty() {
2075 "UNKNOWN_RANGE_FILTER_FIELD"
2076 } else {
2077 "RANGE_FILTER_TYPE_SCOPED"
2078 }
2079 }
2080 Self::FieldNotRangeFilterable { .. } => "FIELD_NOT_RANGE_FILTERABLE",
2081 Self::SearchMemIndexUnavailable { .. } => "SEARCH_MEM_INDEX_UNAVAILABLE",
2082 Self::TitleTrimmed { .. } => "TITLE_TRIMMED",
2083 Self::SuspiciousNestedPrefix { .. } => "SUSPICIOUS_NESTED_PREFIX",
2084 Self::NoteMissing { .. } => "NOTE_MISSING",
2085 Self::IgnoredReadonlyField { .. } => "IGNORED_READONLY_FIELD",
2086 Self::OuterRepoNotIgnoringMemRepo { .. } => "OUTER_REPO_NOT_IGNORING_MEM_REPO",
2087 Self::MissingRequiredOutgoing { .. } => "MISSING_REQUIRED_OUTGOING",
2088 Self::SignalThresholdCrossed { .. } => "SIGNAL_THRESHOLD_CROSSED",
2089 Self::ConstraintUnsatisfied { .. } => "CONSTRAINT_UNSATISFIED",
2090 Self::DuplicateSectionHeading { .. } => "DUPLICATE_SECTION_HEADING",
2091 Self::MemReloaded { .. } => "MEM_RELOADED",
2092 Self::MemRosterChanged { .. } => "MEM_ROSTER_CHANGED",
2093 Self::ConfigWriteIntervened { .. } => "CONFIG_WRITE_INTERVENED",
2094 Self::ShortIdResolved { .. } => "SHORT_ID_RESOLVED",
2095 Self::OutOfBandEditsUndetected { .. } => "OUT_OF_BAND_EDITS_UNDETECTED",
2096 Self::UnanchoredMention { .. } => "UNANCHORED_MENTION",
2097 Self::SchemaPinMismatch { .. } => "SCHEMA_PIN_MISMATCH",
2098 Self::MountUnbacked { .. } => "MOUNT_UNBACKED",
2099 Self::EngineVersionSkew { .. } => "ENGINE_VERSION_SKEW",
2100 Self::SchemaGenerationsBehind { .. } => "SCHEMA_GENERATIONS_BEHIND",
2101 Self::SchemaHeadingRoundtripViolation { .. } => "SCHEMA_HEADING_ROUNDTRIP_VIOLATION",
2102 Self::SectionHeadingDivergence { .. } => "SECTION_HEADING_DIVERGENCE",
2103 Self::AutoStubCreated { .. } => "AUTO_STUB_CREATED",
2104 Self::DerivationBaselineRefreshed { .. } => "DERIVATION_BASELINE_REFRESHED",
2105 Self::SelfLinkIgnored { .. } => "SELF_LINK_IGNORED",
2106 Self::CrossSchemaLinkUndeclared { .. } => "CROSS_SCHEMA_LINK_UNDECLARED",
2107 Self::ParsedRelationInvalid { .. } => "PARSED_RELATION_INVALID",
2108 Self::ResidualStubForReadOnlyReferrers { .. } => "RESIDUAL_STUB_FOR_READONLY_REFERRERS",
2109 Self::MemFilesNotDeleted { .. } => "MEM_FILES_NOT_DELETED",
2110 Self::MemReattachedAfterUnregister { .. } => "MEM_REATTACHED_AFTER_UNREGISTER",
2111 Self::ReadMemsMigratedToMounts { .. } => "READ_MEMS_MIGRATED_TO_MOUNTS",
2112 Self::FolderMemProvenance { .. } => "FOLDER_MEM_PROVENANCE",
2113 Self::SchemaAuthoringSourceMissing { .. } => "SCHEMA_AUTHORING_SOURCE_MISSING",
2114 Self::SchemaAuthoringSourceDiverged { .. } => "SCHEMA_AUTHORING_SOURCE_DIVERGED",
2115 Self::SchemaUnstampedSourceRot { .. } => "SCHEMA_UNSTAMPED_SOURCE_ROT",
2116 Self::AmbiguousDescriptionDelimiter { .. } => "AMBIGUOUS_DESCRIPTION_DELIMITER",
2117 Self::ParseMissingRequiredDescription { .. } => "MISSING_REQUIRED_DESCRIPTION",
2118 Self::ParseDescriptionNotPermitted { .. } => "DESCRIPTION_NOT_PERMITTED",
2119 }
2120 }
2121
2122 /// Human-readable message — delegates to `Display`. May change across
2123 /// releases; use [`WarningHint::code`] for branching.
2124 pub fn message(&self) -> String {
2125 self.to_string()
2126 }
2127
2128 /// Mem that "owns" the warning when one can be attributed.
2129 /// Workspace-/request-scoped variants return `None` — `memstead_health`'s
2130 /// mem filter keeps those visible regardless of scope, while
2131 /// mem-attributable variants drop out when the filter doesn't
2132 /// match. The contract mirrors the data fields the same filter
2133 /// gates (counts, distributions, detail lists are source-mem
2134 /// scoped; rosters stay global).
2135 pub fn source_mem(&self) -> Option<&str> {
2136 match self {
2137 Self::SuspiciousNestedPrefix { from, .. } => Some(from.mem()),
2138 Self::DuplicateSectionHeading { entity_id, .. } => Some(entity_id.mem()),
2139 Self::SchemaPinMismatch { mem, .. } => Some(mem.as_str()),
2140 Self::MountUnbacked { mem, .. } => Some(mem.as_str()),
2141 Self::SchemaHeadingRoundtripViolation { mem, .. } => Some(mem.as_str()),
2142 Self::SectionHeadingDivergence { entity_id, .. } => Some(entity_id.mem()),
2143 Self::MemReloaded { mem, .. } => Some(mem.as_str()),
2144 Self::MemRosterChanged { .. } => None,
2145 Self::MemFilesNotDeleted { mem, .. } => Some(mem.as_str()),
2146 Self::MemReattachedAfterUnregister { mem, .. } => Some(mem.as_str()),
2147 Self::ReadMemsMigratedToMounts { .. } => None,
2148 Self::EngineVersionSkew { mem, .. } => Some(mem.as_str()),
2149 Self::SchemaGenerationsBehind { mem, .. } => Some(mem.as_str()),
2150 Self::FolderMemProvenance { mem } => Some(mem.as_str()),
2151 Self::MissingRequiredOutgoing { entity_id, .. } => Some(entity_id.mem()),
2152 Self::SignalThresholdCrossed { entity_id, .. } => Some(entity_id.mem()),
2153 Self::ConstraintUnsatisfied { entity_id, .. } => Some(entity_id.mem()),
2154 Self::DuplicateRelationship { from, .. } => Some(from.mem()),
2155 Self::NoSuchRelationship { from, .. } => Some(from.mem()),
2156 Self::InlineWikiLinkAutoStubbed { from, .. } => Some(from.mem()),
2157 Self::SelfLinkIgnored { id } => Some(id.mem()),
2158 Self::CrossMemTargetMemUncreated { from_mem, .. } => Some(from_mem.as_str()),
2159 Self::AutoStubCreated { stub_id, .. } => Some(stub_id.mem()),
2160 Self::DerivationBaselineRefreshed { from, .. } => Some(from.mem()),
2161 Self::UpdateNoop { id } => Some(id.mem()),
2162 Self::ParsedRelationInvalid { entity_id, .. } => Some(entity_id.mem()),
2163 Self::ResidualStubForReadOnlyReferrers { id, .. } => Some(id.mem()),
2164 Self::AmbiguousDescriptionDelimiter { from, .. } => Some(from.mem()),
2165 Self::ParseMissingRequiredDescription { from, .. } => Some(from.mem()),
2166 Self::ParseDescriptionNotPermitted { from, .. } => Some(from.mem()),
2167 // Search-mem-index unavailability is attributable to the
2168 // failing mem; the filter-key warnings are request-
2169 // derived (the agent's filter payload) and fall through
2170 // to `None` below to stay visible to the caller.
2171 Self::SearchMemIndexUnavailable { mem, .. } => Some(mem.as_str()),
2172 Self::OutOfBandEditsUndetected { mem } => Some(mem.as_str()),
2173 Self::UnanchoredMention { mem, .. } => Some(mem.as_str()),
2174 Self::ConfigWriteIntervened { mem, .. } => Some(mem.as_str()),
2175 Self::ShortIdResolved { resolved, .. } => Some(resolved.mem()),
2176 Self::CrossSchemaLinkUndeclared { from, .. } => Some(from.mem()),
2177 // Workspace- or request-scoped — no mem to attribute.
2178 // OuterRepoNotIgnoringMemRepo concerns the embedding repo,
2179 // not a specific mem; an agent should see it under any
2180 // filter. UnknownIncludeKey / LimitClamped / NoteMissing /
2181 // TitleNormalizedToSlugNoop / StubFilterExcludesAll /
2182 // UndeclaredRelationshipOpen / MissingRequiredSection /
2183 // MissingRequiredField are request-derived (mutation
2184 // payload or schema-level), so the mem is the
2185 // request's mem — `None` here keeps them visible to
2186 // the caller that triggered them.
2187 _ => None,
2188 }
2189 }
2190
2191 /// Whether this warning belongs in a report scoped to `mem`: the one
2192 /// rule the health composer applies to every warning under a mem
2193 /// filter. A warning attributed to one mem (`source_mem`) concerns
2194 /// that mem only; a warning naming several mems (the schema-source
2195 /// trio) concerns each of them; a warning attributed to no mem at all
2196 /// (a request notice, a workspace-level roster or config condition)
2197 /// concerns every mem, this one included, and stays.
2198 pub fn concerns_mem(&self, mem: &str) -> bool {
2199 if let Some(source) = self.source_mem() {
2200 return source == mem;
2201 }
2202 match self {
2203 Self::SchemaAuthoringSourceMissing { mems, .. }
2204 | Self::SchemaAuthoringSourceDiverged { mems, .. }
2205 | Self::SchemaUnstampedSourceRot { mems, .. } => mems.iter().any(|m| m == mem),
2206 _ => true,
2207 }
2208 }
2209
2210 /// One representative of every `WarningHint` variant — the single
2211 /// source of truth consumed by stability tests (`envelope_*`,
2212 /// `code_values_are_upper_snake_case`) and by the MCP description
2213 /// drift-guard (`every_warning_code_appears_in_a_description`).
2214 /// Adding a new variant without extending this list fails those tests;
2215 /// that's the forcing function.
2216 pub fn all_samples() -> Vec<WarningHint> {
2217 vec![
2218 WarningHint::EngineVersionSkew {
2219 mem: "m".into(),
2220 stamped_engine: "0.3.0".into(),
2221 running_engine: "0.4.0".into(),
2222 stamped_schema: "default@1.0.0".into(),
2223 direction: crate::build_info::SkewDirection::StampedOlder,
2224 },
2225 WarningHint::SchemaGenerationsBehind {
2226 mem: "m".into(),
2227 pinned: "default@1.0.0".into(),
2228 newest: "1.2.0".into(),
2229 },
2230 WarningHint::MissingRequiredSection {
2231 entity_type: "t".into(),
2232 key: "k".into(),
2233 heading: "H".into(),
2234 write_rules: vec![],
2235 },
2236 WarningHint::MissingRequiredField {
2237 entity_type: "decision".into(),
2238 key: "decided_on".into(),
2239 description: "Date the decision was accepted.".into(),
2240 enum_values: vec![],
2241 },
2242 WarningHint::UndeclaredRelationshipOpen {
2243 rel_type: "X".into(),
2244 message: "m".into(),
2245 },
2246 WarningHint::DuplicateRelationship {
2247 rel_type: "X".into(),
2248 from: EntityId("a".into()),
2249 to: EntityId("b".into()),
2250 },
2251 WarningHint::NoSuchRelationship {
2252 rel_type: "X".into(),
2253 from: EntityId("a".into()),
2254 to: EntityId("b".into()),
2255 },
2256 WarningHint::UnknownIncludeKey {
2257 key: "x".into(),
2258 allowed: vec![],
2259 },
2260 WarningHint::LimitClamped {
2261 requested: 1,
2262 actual: 1,
2263 },
2264 WarningHint::SearchResultsTruncated {
2265 kept: 12,
2266 budget: 12_000,
2267 },
2268 WarningHint::TitleNormalizedToSlugNoop {
2269 requested_title: "Hello World!".into(),
2270 current_slug: "hello-world".into(),
2271 },
2272 WarningHint::TitleCharsDroppedFromSlug {
2273 title: "Acme Inc. & Co".into(),
2274 dropped_chars: vec!['.', '&'],
2275 slug: "acme-inc-co".into(),
2276 },
2277 WarningHint::UpdateNoop {
2278 id: EntityId("specs--example".into()),
2279 },
2280 WarningHint::StubFilterExcludesAll {
2281 entity_type: "spec".into(),
2282 },
2283 // Non-empty `declared_on_other_types` → code FILTER_TYPE_SCOPED.
2284 WarningHint::UnknownFilterKey {
2285 key: "nonexistent_field".into(),
2286 scoped_type: Some("spec".into()),
2287 declared_on_other_types: vec!["decision".into()],
2288 },
2289 // Empty `declared_on_other_types` → code UNKNOWN_FILTER_KEY.
2290 WarningHint::UnknownFilterKey {
2291 key: "stauts".into(),
2292 scoped_type: None,
2293 declared_on_other_types: vec![],
2294 },
2295 WarningHint::FieldNotFilterable {
2296 field: "title".into(),
2297 },
2298 WarningHint::RangeFilterKeyMalformed {
2299 key: "weird_key".into(),
2300 },
2301 // Empty `declared_on_other_types` → code UNKNOWN_RANGE_FILTER_FIELD.
2302 WarningHint::UnknownRangeFilterField {
2303 field: "count".into(),
2304 key: "min_count".into(),
2305 scoped_type: None,
2306 declared_on_other_types: vec![],
2307 },
2308 // Non-empty → code RANGE_FILTER_TYPE_SCOPED.
2309 WarningHint::UnknownRangeFilterField {
2310 field: "priority".into(),
2311 key: "min_priority".into(),
2312 scoped_type: Some("spec".into()),
2313 declared_on_other_types: vec!["decision".into()],
2314 },
2315 WarningHint::FieldNotRangeFilterable {
2316 field: "tags".into(),
2317 },
2318 WarningHint::SearchMemIndexUnavailable {
2319 mem: "specs".into(),
2320 reason: "missing_index",
2321 error: None,
2322 },
2323 WarningHint::SuspiciousNestedPrefix {
2324 from: EntityId("test-mem-plugin--audit-skill".into()),
2325 resolved_id: EntityId("test-mem-plugin--plugin--memstead-mcp-tool-surface".into()),
2326 candidate_target: Some(EntityId(
2327 "test-mem-plugin--memstead-mcp-tool-surface".into(),
2328 )),
2329 section: "constraints".into(),
2330 prefix_mounted: false,
2331 },
2332 WarningHint::MountUnbacked {
2333 mem: "institute".into(),
2334 reason: MountUnbackedReason::MissingRef,
2335 location: "refs/heads/institute".into(),
2336 },
2337 WarningHint::InlineWikiLinkAutoStubbed {
2338 from: EntityId("specs--demo".into()),
2339 stubs: vec![EntityId("specs--example-target".into())],
2340 },
2341 WarningHint::CrossMemTargetMemUncreated {
2342 from_mem: "specs".into(),
2343 to_mem: "memos".into(),
2344 target_id: EntityId("memos--example".into()),
2345 },
2346 WarningHint::NoteMissing {
2347 tool: "memstead_update".into(),
2348 },
2349 WarningHint::OuterRepoNotIgnoringMemRepo {
2350 outer_repo_root: "/repos/demo".into(),
2351 workspace_root: "/repos/demo/memstead".into(),
2352 },
2353 WarningHint::MissingRequiredOutgoing {
2354 entity_type: "decision".into(),
2355 entity_id: EntityId("planning--decision-x".into()),
2356 missing: vec![
2357 MissingRequiredOutgoingBlock {
2358 relationships: vec!["CHOSEN".into()],
2359 cardinality: "at_least_one".into(),
2360 severity: memstead_schema::ConstraintSeverity::Warn,
2361 when_field: None,
2362 when_value: None,
2363 },
2364 MissingRequiredOutgoingBlock {
2365 relationships: vec!["REJECTED".into()],
2366 cardinality: "at_least_one".into(),
2367 severity: memstead_schema::ConstraintSeverity::Warn,
2368 when_field: None,
2369 when_value: None,
2370 },
2371 ],
2372 },
2373 WarningHint::DuplicateSectionHeading {
2374 entity_id: EntityId("plugin--hooks-subsystem".into()),
2375 section_key: "realization".into(),
2376 heading: "Realization".into(),
2377 occurrences: 3,
2378 },
2379 WarningHint::ConfigWriteIntervened {
2380 mem: "test-mem-plugin".into(),
2381 fields: vec!["description".into()],
2382 },
2383 WarningHint::OutOfBandEditsUndetected {
2384 mem: "test-mem-plugin".into(),
2385 },
2386 WarningHint::UnanchoredMention {
2387 mem: "engine".into(),
2388 binding: "engine/graph".into(),
2389 entity: EntityId("engine--reload".into()),
2390 artifact: "../public/crates/memstead-base/src/storage/filesystem.rs".into(),
2391 section: "constraints".into(),
2392 },
2393 WarningHint::MemReloaded {
2394 mem: "test-mem-plugin".into(),
2395 old_head: "abc123".into(),
2396 new_head: "def456".into(),
2397 entities_loaded: 42,
2398 },
2399 WarningHint::MemRosterChanged {
2400 added: vec!["arrived".into()],
2401 removed: vec!["departed".into()],
2402 quarantined: vec![],
2403 failures: vec![],
2404 },
2405 WarningHint::AutoStubCreated {
2406 stub_id: EntityId("specs--future-target".into()),
2407 pending: false,
2408 },
2409 WarningHint::ParsedRelationInvalid {
2410 entity_id: EntityId("specs--example-source".into()),
2411 rel_type: "EXECUTES".into(),
2412 target: EntityId("specs--example-target".into()),
2413 reason: "shape".into(),
2414 origin: "writable".into(),
2415 recovery: Some(ParsedRelationRecovery::remove_explicit_relation(
2416 EntityId("specs--example-source".into()),
2417 EntityId("specs--example-target".into()),
2418 "EXECUTES".into(),
2419 )),
2420 },
2421 WarningHint::ResidualStubForReadOnlyReferrers {
2422 id: EntityId("specs--archived-target".into()),
2423 referrers: vec![EntityId("archive--archived-source".into())],
2424 },
2425 WarningHint::MemFilesNotDeleted {
2426 mem: "plan-example".into(),
2427 reason: "backend_prune_failed".into(),
2428 path: None,
2429 error: Some("ref-edit transaction rejected".into()),
2430 },
2431 WarningHint::MemReattachedAfterUnregister {
2432 mem: "plan-example".into(),
2433 unregistered_at: "2026-05-17T08:43:29Z".into(),
2434 },
2435 WarningHint::FolderMemProvenance {
2436 mem: "plan-example".into(),
2437 },
2438 WarningHint::SchemaAuthoringSourceMissing {
2439 schema_ref: "authored@0.1.0".into(),
2440 stamped_path: "/workspace/authored".into(),
2441 mems: vec!["specs".into()],
2442 },
2443 WarningHint::SchemaAuthoringSourceDiverged {
2444 schema_ref: "authored@0.1.0".into(),
2445 stamped_path: "/workspace/authored".into(),
2446 mems: vec!["specs".into()],
2447 detail: "the parsed authoring package differs from the sealed copy".into(),
2448 },
2449 WarningHint::SchemaUnstampedSourceRot {
2450 schema_ref: "authored@0.1.0".into(),
2451 mems: vec!["specs".into()],
2452 detail: "type 'decision': `propagating_relationships` was renamed".into(),
2453 },
2454 WarningHint::AmbiguousDescriptionDelimiter {
2455 from: EntityId("specs--example-source".into()),
2456 rel_type: "OTHER".into(),
2457 target: EntityId("specs--example-target".into()),
2458 trailing: " -- legacy delimiter".into(),
2459 },
2460 WarningHint::ParseMissingRequiredDescription {
2461 from: EntityId("specs--example-source".into()),
2462 rel_type: "OTHER".into(),
2463 target: EntityId("specs--example-target".into()),
2464 },
2465 WarningHint::ParseDescriptionNotPermitted {
2466 from: EntityId("specs--example-source".into()),
2467 rel_type: "IMPLEMENTS".into(),
2468 target: EntityId("specs--example-target".into()),
2469 },
2470 ]
2471 }
2472
2473 fn details_payload(&self) -> serde_json::Value {
2474 match self {
2475 Self::OutOfBandEditsUndetected { mem } => serde_json::json!({ "mem": mem }),
2476 Self::UnanchoredMention {
2477 mem,
2478 binding,
2479 entity,
2480 artifact,
2481 section,
2482 } => serde_json::json!({
2483 "mem": mem,
2484 "binding": binding,
2485 "entity": entity,
2486 "artifact": artifact,
2487 "section": section,
2488 }),
2489 Self::ConfigWriteIntervened { mem, fields } => serde_json::json!({
2490 "mem": mem,
2491 "fields": fields,
2492 }),
2493 Self::ShortIdResolved { given, resolved } => serde_json::json!({
2494 "given": given,
2495 "resolved": resolved,
2496 }),
2497 Self::MissingRequiredSection {
2498 entity_type,
2499 key,
2500 heading,
2501 write_rules,
2502 } => serde_json::json!({
2503 "entity_type": entity_type,
2504 "key": key,
2505 "heading": heading,
2506 "write_rules": write_rules,
2507 }),
2508 Self::MissingRequiredField {
2509 entity_type,
2510 key,
2511 description,
2512 enum_values,
2513 } => serde_json::json!({
2514 "entity_type": entity_type,
2515 "key": key,
2516 "field_description": description,
2517 "enum_values": enum_values,
2518 }),
2519 Self::UndeclaredRelationshipOpen { rel_type, .. } => {
2520 serde_json::json!({ "rel_type": rel_type })
2521 }
2522 Self::DuplicateRelationship { rel_type, from, to } => {
2523 serde_json::json!({ "rel_type": rel_type, "from": from, "to": to })
2524 }
2525 Self::NoSuchRelationship { rel_type, from, to } => {
2526 serde_json::json!({ "rel_type": rel_type, "from": from, "to": to })
2527 }
2528 Self::UnknownIncludeKey { key, allowed } => {
2529 serde_json::json!({ "key": key, "allowed": allowed })
2530 }
2531 Self::LimitClamped { requested, actual } => {
2532 serde_json::json!({ "requested": requested, "actual": actual })
2533 }
2534 Self::TitleNormalizedToSlugNoop {
2535 requested_title,
2536 current_slug,
2537 } => serde_json::json!({
2538 "requested_title": requested_title,
2539 "current_slug": current_slug,
2540 }),
2541 Self::TitleCharsDroppedFromSlug {
2542 title,
2543 dropped_chars,
2544 slug,
2545 } => serde_json::json!({
2546 "title": title,
2547 "dropped_chars": dropped_chars,
2548 "slug": slug,
2549 }),
2550 Self::UpdateNoop { id } => serde_json::json!({ "id": id }),
2551 Self::StubFilterExcludesAll { entity_type } => {
2552 serde_json::json!({ "entity_type": entity_type })
2553 }
2554 Self::UnknownFilterKey {
2555 key,
2556 scoped_type,
2557 declared_on_other_types,
2558 } => serde_json::json!({
2559 "key": key,
2560 "scoped_type": scoped_type,
2561 "declared_on_other_types": declared_on_other_types,
2562 }),
2563 Self::FieldNotFilterable { field } => serde_json::json!({ "field": field }),
2564 Self::FilterValueMultiMember { key, value } => {
2565 serde_json::json!({ "key": key, "value": value })
2566 }
2567 Self::FilterValueNotInEnum {
2568 key,
2569 value,
2570 allowed,
2571 } => {
2572 serde_json::json!({ "key": key, "value": value, "allowed": allowed })
2573 }
2574 Self::NeighbourhoodCapped { kept, total } => {
2575 serde_json::json!({ "kept": kept, "total": total })
2576 }
2577 Self::SearchResultsTruncated { kept, budget } => {
2578 serde_json::json!({ "kept": kept, "budget": budget })
2579 }
2580 Self::RangeFilterKeyMalformed { key } => serde_json::json!({ "key": key }),
2581 Self::UnknownRangeFilterField {
2582 field,
2583 key,
2584 scoped_type,
2585 declared_on_other_types,
2586 } => serde_json::json!({
2587 "field": field,
2588 "key": key,
2589 "scoped_type": scoped_type,
2590 "declared_on_other_types": declared_on_other_types,
2591 }),
2592 Self::FieldNotRangeFilterable { field } => serde_json::json!({ "field": field }),
2593 Self::SearchMemIndexUnavailable { mem, reason, error } => serde_json::json!({
2594 "mem": mem,
2595 "reason": reason,
2596 "error": error,
2597 }),
2598 Self::TitleTrimmed { original, trimmed } => serde_json::json!({
2599 "original": original,
2600 "trimmed": trimmed,
2601 }),
2602 Self::SuspiciousNestedPrefix {
2603 from,
2604 resolved_id,
2605 candidate_target,
2606 section,
2607 prefix_mounted,
2608 } => serde_json::json!({
2609 "from": from,
2610 "resolved_id": resolved_id,
2611 "candidate_target": candidate_target,
2612 "section": section,
2613 "target_mem": resolved_id.mem(),
2614 "prefix_mounted": prefix_mounted,
2615 }),
2616 Self::InlineWikiLinkAutoStubbed { from, stubs } => serde_json::json!({
2617 "from": from,
2618 "stubs": stubs,
2619 }),
2620 Self::SelfLinkIgnored { id } => serde_json::json!({ "id": id }),
2621 Self::CrossSchemaLinkUndeclared {
2622 from,
2623 target,
2624 source_schema,
2625 target_schema,
2626 } => serde_json::json!({
2627 "from": from,
2628 "target": target,
2629 "source_schema": source_schema,
2630 "target_schema": target_schema,
2631 }),
2632 Self::CrossMemTargetMemUncreated {
2633 from_mem,
2634 to_mem,
2635 target_id,
2636 } => serde_json::json!({
2637 "from_mem": from_mem,
2638 "to_mem": to_mem,
2639 "target_id": target_id,
2640 }),
2641 Self::NoteMissing { tool } => serde_json::json!({ "tool": tool }),
2642 Self::IgnoredReadonlyField { field, supplied } => {
2643 serde_json::json!({ "field": field, "supplied": supplied })
2644 }
2645 Self::OuterRepoNotIgnoringMemRepo {
2646 outer_repo_root,
2647 workspace_root,
2648 } => serde_json::json!({
2649 "outer_repo_root": outer_repo_root,
2650 "workspace_root": workspace_root,
2651 }),
2652 Self::MissingRequiredOutgoing {
2653 entity_type,
2654 entity_id,
2655 missing,
2656 } => serde_json::json!({
2657 "entity_type": entity_type,
2658 "entity_id": entity_id,
2659 "missing": missing,
2660 }),
2661 Self::SignalThresholdCrossed {
2662 entity_id,
2663 signal,
2664 value,
2665 old_level,
2666 new_level,
2667 } => serde_json::json!({
2668 "entity": entity_id,
2669 "signal": signal,
2670 "value": value,
2671 "old_level": old_level,
2672 "new_level": new_level,
2673 }),
2674 Self::ConstraintUnsatisfied {
2675 entity_type,
2676 entity_id,
2677 violations,
2678 } => serde_json::json!({
2679 "entity_type": entity_type,
2680 "entity_id": entity_id,
2681 "violations": violations,
2682 }),
2683 Self::DuplicateSectionHeading {
2684 entity_id,
2685 section_key,
2686 heading,
2687 occurrences,
2688 } => serde_json::json!({
2689 "entity_id": entity_id,
2690 "section_key": section_key,
2691 "heading": heading,
2692 "occurrences": occurrences,
2693 }),
2694 Self::MemReloaded {
2695 mem,
2696 old_head,
2697 new_head,
2698 entities_loaded,
2699 } => serde_json::json!({
2700 "mem": mem,
2701 "old_head": old_head,
2702 "new_head": new_head,
2703 "entities_loaded": entities_loaded,
2704 }),
2705 Self::MemRosterChanged {
2706 added,
2707 removed,
2708 quarantined,
2709 failures,
2710 } => serde_json::json!({
2711 "added": added,
2712 "removed": removed,
2713 "quarantined": quarantined,
2714 "failures": failures,
2715 }),
2716 Self::AutoStubCreated { stub_id, .. } => serde_json::json!({ "stub_id": stub_id }),
2717 Self::DerivationBaselineRefreshed { from, rel_type, to } => serde_json::json!({
2718 "from": from,
2719 "rel_type": rel_type,
2720 "to": to,
2721 }),
2722 Self::ParsedRelationInvalid {
2723 entity_id,
2724 rel_type,
2725 target,
2726 reason,
2727 origin,
2728 recovery,
2729 } => {
2730 serde_json::json!({
2731 "entity_id": entity_id,
2732 "rel_type": rel_type,
2733 "target": target,
2734 "reason": reason,
2735 "origin": origin,
2736 "recovery": recovery,
2737 })
2738 }
2739 Self::ResidualStubForReadOnlyReferrers { id, referrers } => serde_json::json!({
2740 "id": id,
2741 "referrers": referrers,
2742 }),
2743 Self::MemFilesNotDeleted {
2744 mem,
2745 reason,
2746 path,
2747 error,
2748 } => serde_json::json!({
2749 "mem": mem,
2750 "reason": reason,
2751 "path": path,
2752 "error": error,
2753 }),
2754 Self::MemReattachedAfterUnregister {
2755 mem,
2756 unregistered_at,
2757 } => serde_json::json!({
2758 "mem": mem,
2759 "unregistered_at": unregistered_at,
2760 }),
2761 Self::EngineVersionSkew {
2762 mem,
2763 stamped_engine,
2764 running_engine,
2765 stamped_schema,
2766 direction,
2767 } => {
2768 serde_json::json!({
2769 "mem": mem,
2770 "stamped_engine": stamped_engine,
2771 "running_engine": running_engine,
2772 "stamped_schema": stamped_schema,
2773 "direction": direction,
2774 })
2775 }
2776 Self::SchemaGenerationsBehind {
2777 mem,
2778 pinned,
2779 newest,
2780 } => serde_json::json!({
2781 "mem": mem,
2782 "pinned": pinned,
2783 "newest": newest,
2784 }),
2785 Self::ReadMemsMigratedToMounts {
2786 mems,
2787 from_host_mems,
2788 } => serde_json::json!({
2789 "mems": mems,
2790 "from_host_mems": from_host_mems,
2791 }),
2792 Self::FolderMemProvenance { mem } => serde_json::json!({
2793 "mem": mem,
2794 "ledger": ".memstead/changes.jsonl",
2795 "write_id": "synthetic token, not a commit and not a change cursor (no version control)",
2796 "change_cursor": "an RFC3339 timestamp — the `ts` of the last ledger entry",
2797 "durability": "content persists only when the surrounding repository commits it",
2798 }),
2799 Self::SchemaAuthoringSourceMissing {
2800 schema_ref,
2801 stamped_path,
2802 mems,
2803 } => serde_json::json!({
2804 "schema_ref": schema_ref,
2805 "stamped_path": stamped_path,
2806 "mems": mems,
2807 }),
2808 Self::SchemaAuthoringSourceDiverged {
2809 schema_ref,
2810 stamped_path,
2811 mems,
2812 detail,
2813 } => serde_json::json!({
2814 "schema_ref": schema_ref,
2815 "stamped_path": stamped_path,
2816 "mems": mems,
2817 "detail": detail,
2818 }),
2819 Self::SchemaUnstampedSourceRot {
2820 schema_ref,
2821 mems,
2822 detail,
2823 } => serde_json::json!({
2824 "schema_ref": schema_ref,
2825 "mems": mems,
2826 "detail": detail,
2827 }),
2828 Self::AmbiguousDescriptionDelimiter {
2829 from,
2830 rel_type,
2831 target,
2832 trailing,
2833 } => serde_json::json!({
2834 "from": from,
2835 "rel_type": rel_type,
2836 "target": target,
2837 "trailing": trailing,
2838 }),
2839 Self::ParseMissingRequiredDescription {
2840 from,
2841 rel_type,
2842 target,
2843 } => {
2844 serde_json::json!({ "from": from, "rel_type": rel_type, "target": target })
2845 }
2846 Self::ParseDescriptionNotPermitted {
2847 from,
2848 rel_type,
2849 target,
2850 } => {
2851 serde_json::json!({ "from": from, "rel_type": rel_type, "target": target })
2852 }
2853 Self::SchemaPinMismatch {
2854 mem,
2855 config_pin,
2856 mount_pin,
2857 } => {
2858 serde_json::json!({
2859 "mem": mem,
2860 "config_pin": config_pin,
2861 "mount_pin": mount_pin,
2862 })
2863 }
2864 Self::MountUnbacked {
2865 mem,
2866 reason,
2867 location,
2868 } => serde_json::json!({
2869 "mem": mem,
2870 "reason": reason.as_str(),
2871 "location": location,
2872 }),
2873 Self::SchemaHeadingRoundtripViolation {
2874 mem,
2875 schema_ref,
2876 violations,
2877 } => {
2878 serde_json::json!({
2879 "mem": mem,
2880 "schema_ref": schema_ref,
2881 "violations": violations,
2882 })
2883 }
2884 Self::SectionHeadingDivergence {
2885 entity_id,
2886 section_key,
2887 writing_heading,
2888 existing_heading,
2889 } => {
2890 serde_json::json!({
2891 "entity_id": entity_id,
2892 "section_key": section_key,
2893 "writing_heading": writing_heading,
2894 "existing_heading": existing_heading,
2895 })
2896 }
2897 }
2898 }
2899}
2900
2901impl Serialize for WarningHint {
2902 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2903 // Direct struct emission — avoids the intermediate `Value` allocation
2904 // `envelope(...).serialize(serializer)` would incur. Wire shape is
2905 // bit-identical to `envelope(...)`'s output; DRY lives at the
2906 // constructor level via the shared `envelope` helper used by the MCP
2907 // error path (`engine_err_with_suggestions`).
2908 let details = self.details_payload();
2909 let mut state = serializer.serialize_struct("WarningHint", 3)?;
2910 state.serialize_field("code", self.code())?;
2911 state.serialize_field("message", &self.message())?;
2912 state.serialize_field("details", &details)?;
2913 state.end()
2914 }
2915}
2916
2917/// Build the uniform `{ code, message, details }` envelope used on both the
2918/// warning wire (`WarningHint`'s custom `Serialize`) and the MCP error wire
2919/// (`tool_error_with_payload` payloads in `engine_err_with_suggestions`).
2920/// Agents and other decoders branch on `code` (UPPER_SNAKE_CASE, stable)
2921/// and parse `details` by `code` when they need structured fields.
2922pub fn envelope(
2923 code: &str,
2924 message: impl Into<String>,
2925 details: serde_json::Value,
2926) -> serde_json::Value {
2927 serde_json::json!({
2928 "code": code,
2929 "message": message.into(),
2930 "details": details,
2931 })
2932}
2933
2934/// Result of a create operation.
2935#[derive(Debug, Clone, Serialize)]
2936pub struct CreateResult {
2937 pub id: EntityId,
2938 pub title: String,
2939 pub mem: String,
2940 pub file_path: String,
2941 pub created_date: String,
2942 /// Post-write content hash under the real path; the **prospective**
2943 /// hash under `dry_run` — bit-identical to what a real call with the
2944 /// same inputs would produce. Wire key `_hash`.
2945 #[serde(rename = "_hash")]
2946 pub content_hash: String,
2947 /// The backend's identity for this write, never a cursor — see
2948 /// `UpdateResult::write_id`. Empty under
2949 /// `dry_run`.
2950 #[serde(default)]
2951 pub write_id: String,
2952 /// Typed non-fatal issues — missing required sections (with writing
2953 /// guidance) and open-mode relationship admissions.
2954 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2955 pub warnings: Vec<WarningHint>,
2956 /// Type-level `write_rules` keyed by `entity_type` — the
2957 /// MISSING_REQUIRED_SECTION / MISSING_REQUIRED_FIELD warnings on
2958 /// `warnings[]` reference this top-level map via their
2959 /// `entity_type` field rather than each carrying the (identical,
2960 /// type-axis) array (F9). Stable empty shape (`{}`) ships when no
2961 /// such warnings fire — consumers don't branch on field presence.
2962 #[serde(default)]
2963 pub type_guidance: std::collections::BTreeMap<String, Vec<String>>,
2964 /// Number of incoming edges adopted from a pre-existing stub at this
2965 /// id (real path) or that would be adopted (dry_run). `None` means
2966 /// no pre-existing stub / no incoming refs — field is serde-omitted.
2967 #[serde(skip_serializing_if = "Option::is_none")]
2968 pub incoming_count: Option<usize>,
2969 /// Incoming edges present at this id at create time. Real path:
2970 /// edges preserved during stub adoption. Dry_run: edges that would
2971 /// be adopted if committed. Sorted by (rel_type, from) for
2972 /// determinism. Empty vec is serde-omitted.
2973 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2974 pub incoming: Vec<IncomingRef>,
2975}
2976
2977/// Serialisable projection of `store::InEdge` for `CreateResult.incoming`.
2978/// `source` is the lowercase `EdgeSource` variant:
2979/// `"explicit" | "hierarchy" | "body_link"`.
2980#[derive(Debug, Clone, Serialize)]
2981pub struct IncomingRef {
2982 pub from: EntityId,
2983 pub rel_type: String,
2984 pub source: String,
2985}
2986
2987/// Project `&[store::InEdge]` into a sorted `Vec<IncomingRef>`. Ordering
2988/// by (rel_type, from) ascending — deterministic output despite the
2989/// underlying HashMap iteration order.
2990pub fn project_incoming(edges: &[crate::store::InEdge]) -> Vec<IncomingRef> {
2991 let mut out: Vec<IncomingRef> = edges
2992 .iter()
2993 .map(|e| IncomingRef {
2994 from: e.from.clone(),
2995 rel_type: e.rel_type.clone(),
2996 source: match e.source {
2997 crate::store::EdgeSource::Explicit => "explicit",
2998 crate::store::EdgeSource::Hierarchy => "hierarchy",
2999 crate::store::EdgeSource::BodyLink => "body_link",
3000 }
3001 .to_string(),
3002 })
3003 .collect();
3004 out.sort_by(|a, b| a.rel_type.cmp(&b.rel_type).then(a.from.0.cmp(&b.from.0)));
3005 out
3006}
3007
3008/// Result of a delete operation.
3009#[derive(Debug, Clone, Serialize)]
3010pub struct DeleteResult {
3011 pub id: EntityId,
3012 pub relations_removed: usize,
3013 /// The backend's identity for this write, never a cursor — see
3014 /// `UpdateResult::write_id`.
3015 #[serde(default)]
3016 pub write_id: String,
3017 /// Stub entities that became orphaned by this delete (their last
3018 /// incoming edge disappeared with this entity) and were garbage-
3019 /// collected. Empty vec is serde-omitted.
3020 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3021 pub orphan_stubs_removed: Vec<EntityId>,
3022}
3023
3024/// Result of a rename operation.
3025#[derive(Debug, Clone, Serialize)]
3026pub struct RenameResult {
3027 pub old_id: EntityId,
3028 pub new_id: EntityId,
3029 pub old_path: String,
3030 pub new_path: String,
3031 /// Content hash of the renamed entity after the write. Sources by branch:
3032 /// - Real rename (slug change): post-write hash from the re-parsed
3033 /// entity, including the `modified_date` bump applied by
3034 /// `rename_entity` and any wiki-link rewrites in referrers.
3035 /// - Slug-noop short-circuit: the unchanged on-disk hash (no write
3036 /// happened).
3037 ///
3038 /// Pass this as `expected_hash` on the next hash-protected op
3039 /// (`memstead_update`, `memstead_rename`, `memstead_delete`) on the entity — no
3040 /// `memstead_entity` re-read required. Mirrors `RelateResult._hash`.
3041 /// Wire key `_hash`.
3042 #[serde(default, rename = "_hash", skip_serializing_if = "String::is_empty")]
3043 pub content_hash: String,
3044 /// The backend's identity for this write, never a cursor — see
3045 /// `UpdateResult::write_id`. Empty on the
3046 /// no-op same-title rename (no file change, no commit).
3047 #[serde(default)]
3048 pub write_id: String,
3049 /// Typed non-fatal issues. The slug-noop short-circuit
3050 /// (`TitleNormalizedToSlugNoop`) surfaces here when a requested title
3051 /// normalises to the existing slug — the op stays a silent no-op on
3052 /// disk, but the warning tells autonomous skills not to trust
3053 /// `old_id == new_id` as "cosmetic rewrite landed".
3054 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3055 pub warnings: Vec<WarningHint>,
3056}
3057
3058/// Arguments for a relate/unrelate operation.
3059#[derive(Debug, Clone)]
3060pub struct RelateArg {
3061 /// The far end of the edge. Named `target` rather than `to`
3062 /// because the near end is implied by the call (the entity being
3063 /// created or updated) — the rule the response shapes already
3064 /// follow: a pair is `from`/`to`, an implied near end leaves
3065 /// `target`.
3066 pub target: EntityId,
3067 pub rel_type: String,
3068 /// Optional per-edge description text. Validated against the
3069 /// rel-type's `per_edge_description` posture at call time —
3070 /// `forbidden` rejects `Some`; `required` rejects `None`.
3071 /// Empty / whitespace-only strings normalise to `None` before
3072 /// validation.
3073 pub description: Option<String>,
3074}
3075
3076/// One repair-shaped relation removal on `memstead_update` —
3077/// `relations_unset: [{ rel_type, target }]`. Symmetric with
3078/// `metadata_unset`: an absent `(rel_type, target)` pair is a silent
3079/// no-op. Only accepted when the target entity currently fails the
3080/// conformance check (`REPAIR_NOT_NEEDED` otherwise) — the everyday
3081/// detach path stays `memstead_relate(remove)`.
3082#[derive(Debug, Clone, serde::Deserialize)]
3083pub struct RelationUnsetArg {
3084 pub rel_type: String,
3085 pub target: EntityId,
3086}
3087
3088/// Result of a relate operation.
3089#[derive(Debug, Clone, Serialize)]
3090pub struct RelateResult {
3091 pub from: EntityId,
3092 pub to: EntityId,
3093 pub rel_type: String,
3094 pub source: String,
3095 /// Content hash of the source entity after the relate. On successful
3096 /// add/remove, reflects the re-rendered file (Relationships section
3097 /// updated); on duplicate-add and remove-nonexistent no-ops, reflects
3098 /// the unchanged file. Pass this as `expected_hash` on the next
3099 /// hash-protected op (`memstead_update`, `memstead_rename`, `memstead_delete`) on
3100 /// the source — no `memstead_entity` re-read required. Wire key `_hash`.
3101 #[serde(default, rename = "_hash", skip_serializing_if = "String::is_empty")]
3102 pub content_hash: String,
3103 /// The backend's identity for this write, never a cursor — see
3104 /// `UpdateResult::write_id`.
3105 #[serde(default)]
3106 pub write_id: String,
3107 /// Typed non-fatal issues — open-mode schema admissions, duplicate-add
3108 /// no-ops (`DuplicateRelationship`), remove-nonexistent no-ops
3109 /// (`NoSuchRelationship`). Previously silent edge cases now surface here.
3110 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3111 pub warnings: Vec<WarningHint>,
3112 /// True if the op wrote to disk (real add or real remove). False on
3113 /// duplicate-add and remove-nonexistent-edge. Internal signal — the
3114 /// wrapper gates reindex + vcs_commit on this; the MCP wire relies on
3115 /// `write_id.is_empty()` as the external no-op indicator.
3116 #[serde(skip)]
3117 pub disk_changed: bool,
3118 /// Stub entities that became orphaned by an edge removal (their last
3119 /// incoming edge was this one) and were garbage-collected. Only
3120 /// populated on `remove: true` calls where the edge actually existed;
3121 /// empty on add paths and no-op removes. Empty vec is serde-omitted.
3122 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3123 pub orphan_stubs_removed: Vec<EntityId>,
3124}
3125
3126fn is_zero(n: &usize) -> bool {
3127 *n == 0
3128}
3129
3130/// Result of an **atomic** batch update — all-or-nothing.
3131///
3132/// A batch either applies in full as a single commit (`applied: true`)
3133/// or, if any item fails (validation, hash mismatch, missing entity),
3134/// applies *nothing* and refuses (`applied: false`) with the offending
3135/// item named. There is no partial-application middle state: a refused
3136/// batch leaves the on-disk mem and the in-memory store byte-identical
3137/// to the pre-call state.
3138#[derive(Debug, Clone, Serialize)]
3139pub struct BatchResult {
3140 /// Batch-level warnings. Today this carries `CONFIG_WRITE_INTERVENED`
3141 /// when the mutation version stamp merged over another writer's config
3142 /// change: the batch is the operation, so the batch
3143 /// result is where its report belongs. Empty on the ordinary path.
3144 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3145 pub warnings: Vec<WarningHint>,
3146 /// `true` when every item applied (one commit); `false` when the
3147 /// batch was refused (a single item failed → nothing committed).
3148 pub applied: bool,
3149 /// One entry per submitted item, in submission order. On an applied
3150 /// batch every entry's `action` is `"updated"` (a real write) or
3151 /// `"noop"` (content unchanged). On a refused batch the failing
3152 /// item's `action` is `"error"` with a populated `error` envelope,
3153 /// and every other item's `action` is `"not_applied"`.
3154 pub results: Vec<BatchEntry>,
3155 /// Count of applied items when `applied`; `0` when refused.
3156 pub succeeded: usize,
3157 /// Number of FAILING entries whose error envelopes were suppressed
3158 /// beyond the reporting cap (bounded reporting for very large
3159 /// failing batches — the entries still carry `action: "error"`,
3160 /// only the detailed envelope is omitted). `0` when every failure
3161 /// is fully reported.
3162 #[serde(default, skip_serializing_if = "is_zero")]
3163 pub errors_suppressed: usize,
3164 /// Count of failed items when refused (≥1); `0` when applied.
3165 pub failed: usize,
3166 /// Ids of stub entities GC'd because a removed edge in this batch
3167 /// was their last incoming reference — the batch sibling of the
3168 /// single relate response's `orphan_stubs_removed`. Empty (and
3169 /// serde-omitted) for batch-create / batch-update and for batches
3170 /// that removed nothing.
3171 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3172 pub orphan_stubs_removed: Vec<EntityId>,
3173 /// The backend's identity for the batch's write — a commit SHA on
3174 /// a git-branch mem, a synthetic token on a folder mem, and never a
3175 /// change cursor. Present when the batch applied and produced at
3176 /// least one write. Empty when the batch was
3177 /// refused, when it was empty, or when every item was a no-op (no
3178 /// commit happens). For a batch spanning multiple mems this names
3179 /// the last mem committed; single-mem batches (the common case)
3180 /// name their one commit.
3181 #[serde(default)]
3182 pub write_id: String,
3183}
3184
3185#[derive(Debug, Clone, Serialize)]
3186pub struct BatchEntry {
3187 pub id: EntityId,
3188 pub action: String,
3189 /// Structured error envelope when this entry failed. Mirrors the
3190 /// `{code, message, details}` shape single-update errors carry on
3191 /// the wire so a mixed-success batch is structurally uniform —
3192 /// consumers branch on `code` rather than prose-parsing a string.
3193 /// Empty (`None`) for successful entries.
3194 pub error: Option<BatchError>,
3195}
3196
3197/// Per-item error envelope on a batch result. The shape matches the
3198/// MCP wire envelope for single-entry failures: `code` is the stable
3199/// `UPPER_SNAKE_CASE` token from [`crate::EngineError::code()`];
3200/// `details` carries the variant-specific recovery payload (e.g.
3201/// declared list, allowed enum values, hash-mismatch current) when
3202/// available, or an empty object for variants without a structured
3203/// payload.
3204#[derive(Debug, Clone, Serialize)]
3205pub struct BatchError {
3206 pub code: String,
3207 pub message: String,
3208 pub details: serde_json::Value,
3209}
3210
3211// ---------------------------------------------------------------------------
3212// Search types
3213// ---------------------------------------------------------------------------
3214
3215/// Flat query shape for full-text search. Four optional fields, all
3216/// combined with implicit AND across fields.
3217///
3218/// Within `any`: at least one term must match (OR semantics). Entities
3219/// matching more terms rank higher automatically — no explicit `and`.
3220/// Within `not`: none of the listed terms may appear. `phrase` requires
3221/// exact adjacency (case- and diacritic-folded). `field` narrows the match
3222/// region for all three to a single indexed field; `None` = match anywhere
3223/// indexed.
3224///
3225/// Empty/unset everywhere ⇒ no text predicate; `search` behaves as a
3226/// metadata-only filter (subsumes the former `list` semantics).
3227///
3228/// No stemming, wildcards, or regex — the caller expands morphology and
3229/// synonyms by enumerating variants in `any`.
3230#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
3231pub struct Query {
3232 /// Terms where at least one must match (OR semantics).
3233 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3234 pub any: Vec<String>,
3235 /// Terms that must not match (exclusion).
3236 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3237 pub not: Vec<String>,
3238 /// Exact phrase that must appear (case- and diacritic-folded).
3239 #[serde(default, skip_serializing_if = "Option::is_none")]
3240 pub phrase: Option<String>,
3241 /// Restrict `any` / `not` / `phrase` to a single field (title or section
3242 /// key). `None` = match anywhere indexed.
3243 #[serde(default, skip_serializing_if = "Option::is_none")]
3244 pub field: Option<String>,
3245}
3246
3247impl Query {
3248 /// True if no text predicate is set — caller falls back to the
3249 /// metadata-only filter path.
3250 pub fn is_empty(&self) -> bool {
3251 self.any.is_empty() && self.not.is_empty() && self.phrase.is_none()
3252 }
3253}
3254
3255/// Scope filters for search and list operations.
3256#[derive(Debug, Clone, Default)]
3257pub struct SearchScope {
3258 /// Structured flat query. All text matching flows through this field;
3259 /// see [`Query`] for semantics. `None` (or an empty query) makes
3260 /// `search` behave as a metadata-only filter.
3261 pub query: Option<Query>,
3262 pub mem: Option<String>,
3263 pub entity_type: Option<String>,
3264 pub limit: Option<usize>,
3265 pub offset: Option<usize>,
3266 /// Equality filters on metadata fields: `{ "level": "M0" }`.
3267 pub filters: HashMap<String, String>,
3268 /// Range filters: `{ "min_coverage": "0.5", "max_coverage": "1.0" }`.
3269 pub range_filters: HashMap<String, String>,
3270 /// Only entities with this edge type (incoming or outgoing).
3271 pub edge_type: Option<String>,
3272 /// Only entities reachable from this entity within `depth` hops.
3273 pub related_to: Option<EntityId>,
3274 pub depth: Option<usize>,
3275 /// Relationship types to follow from primary hits to pull in graph-proximal
3276 /// neighbours.
3277 pub expand_via: Option<Vec<String>>,
3278 /// Maximum hops to traverse via `expand_via` (default: 1 when `expand_via`
3279 /// is set).
3280 pub expand_depth: Option<usize>,
3281 /// Traversal direction for `related_to` AND `expand_via`, applied at
3282 /// EVERY hop (depth > 1 is a pure transitive closure in the chosen
3283 /// direction, never a mixed walk). Defaults to `both` — the
3284 /// historical undirected behaviour, so a query omitting the
3285 /// selector returns exactly what it always returned.
3286 pub direction: crate::graph::query::TraversalDirection,
3287 /// Filter by stub status. `None` = no filter (returns both stubs and real
3288 /// entities); `Some(true)` = only stubs; `Some(false)` = only real entities.
3289 pub stub: Option<bool>,
3290 /// Token budget bounding the returned hit payload (search path only).
3291 /// `None` uses the engine default. A page whose hits exceed the budget is
3292 /// greedily trimmed (at least one hit always returns) with a
3293 /// `SEARCH_RESULTS_TRUNCATED` warning; `total` still reflects the full
3294 /// match count so the agent can page with `offset`.
3295 pub token_budget: Option<usize>,
3296}
3297
3298/// Per-hit score components surfaced so agents can understand ranking.
3299///
3300/// Note: this is illustrative feedback, not a numerically authoritative
3301/// decomposition — tantivy's `Explanation` for `BoostQuery` over
3302/// `BooleanQuery` does not always sum cleanly. Agents should treat these
3303/// as proportions, not exact sums.
3304#[derive(Debug, Clone, Serialize, JsonSchema)]
3305pub struct ScoreBreakdown {
3306 pub bm25: f32,
3307 pub title_boost: f32,
3308 pub field_weights: HashMap<String, f32>,
3309 /// `Some(f32)` on expanded hits only, carrying the depth-based decay
3310 /// factor (`0.5.powi(depth)`). `None` on primary hits.
3311 #[serde(default, skip_serializing_if = "Option::is_none")]
3312 pub expansion_decay: Option<f32>,
3313}
3314
3315/// One snippet-level match recorded per (term, field). `heading_path` is
3316/// `Some` when the match falls under an H3–H6 sub-heading; elements are
3317/// ordered outermost → innermost.
3318#[derive(Debug, Clone, Serialize, JsonSchema)]
3319pub struct TermMatch {
3320 pub field: String,
3321 pub snippet: String,
3322 #[serde(default, skip_serializing_if = "Option::is_none")]
3323 pub heading_path: Option<Vec<String>>,
3324}
3325
3326/// Metadata attached to hits reached via graph expansion. The
3327/// primary hit that seeded the expansion is identified by `of`; `via_edge`
3328/// is the exact `rel_type` string; `depth` counts hops from the seed.
3329#[derive(Debug, Clone, Serialize, JsonSchema)]
3330pub struct ExpansionInfo {
3331 pub of: EntityId,
3332 pub via_edge: String,
3333 pub depth: usize,
3334 /// The direction the first-reaching edge was traversed in (`out` =
3335 /// away from the seed, `in` = at the seed) — keeps a `both` result
3336 /// interpretable. Additive: clients that ignore it decode unchanged.
3337 pub via_direction: crate::graph::query::TraversalDirection,
3338}
3339
3340/// One sub-section-level facet entry. `path` is ordered outermost →
3341/// innermost, prefixed with the H2 section key (e.g. `["specifies",
3342/// "Response Shapes", "Markdown Output"]`). Structured vector (not a
3343/// delimiter-joined string) so headings containing punctuation don't break
3344/// the key.
3345#[derive(Debug, Clone, Serialize, JsonSchema)]
3346pub struct SubsectionFacet {
3347 pub path: Vec<String>,
3348 pub count: usize,
3349}
3350
3351/// Fixed set of facet dimensions computed over the unpaginated hit set.
3352/// Tier 1 freezes the dimensions; extend later only if empirical use
3353/// demands it. Zero-count entries are excluded to keep the payload small.
3354#[derive(Debug, Clone, Default, Serialize, JsonSchema)]
3355pub struct Facets {
3356 pub by_type: HashMap<String, usize>,
3357 pub by_mem: HashMap<String, usize>,
3358 pub by_level: HashMap<String, usize>,
3359 pub by_status: HashMap<String, usize>,
3360 pub by_confidence: HashMap<String, usize>,
3361 pub by_subsection: Vec<SubsectionFacet>,
3362 /// `"primary"` / `"expanded"` — counts of primary vs. graph-expanded
3363 /// hits. Always present; `expanded` is `0` when no expansion ran.
3364 pub by_expansion: HashMap<String, usize>,
3365}
3366
3367/// A search result hit.
3368#[derive(Debug, Clone, Serialize)]
3369pub struct SearchHit {
3370 pub id: EntityId,
3371 pub title: String,
3372 pub mem: String,
3373 pub entity_type: String,
3374 pub stub: bool,
3375 pub score: f32,
3376 pub tokens: usize,
3377 /// The entity's `last_modified` stamp (RFC-3339 date) — list/roster
3378 /// consumers (the app's Liste, agents asking "what moved lately")
3379 /// sort on it without per-entity reads. `None` for stubs and hits
3380 /// built outside the engine ops.
3381 #[serde(default, skip_serializing_if = "Option::is_none")]
3382 pub last_modified: Option<String>,
3383 pub snippet: Option<String>,
3384 /// Lead/key section bodies for the hit. The `search` op leaves this
3385 /// **empty** — search finds entities, `memstead_entity` reads their
3386 /// bodies; carrying every required section per hit overflowed the MCP
3387 /// transport cap. The `list` op still populates it (its human-facing
3388 /// roster consumers read the lead section as a one-line summary).
3389 /// Empty maps are omitted from the serialized envelope.
3390 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
3391 pub sections: HashMap<String, String>,
3392 /// Score component breakdown — populated when the call supplied a
3393 /// text predicate; `None` on the metadata-only path. Always on the
3394 /// wire (as `null` when absent): the envelope the `memstead_search`
3395 /// description promises is one stable shape, so a consumer reads
3396 /// the key and branches on its value, never on its presence.
3397 #[serde(default)]
3398 pub score_breakdown: Option<ScoreBreakdown>,
3399 /// Per-term match details keyed by query term — populated when the
3400 /// call supplied a text predicate; `None` on the metadata-only path.
3401 /// Always on the wire, as `score_breakdown` is.
3402 #[serde(default)]
3403 pub matched_terms: Option<HashMap<String, Vec<TermMatch>>>,
3404 /// Expansion metadata — populated on hits reached via graph
3405 /// expansion; `None` on primary hits. Always on the wire, as
3406 /// `score_breakdown` is.
3407 #[serde(default)]
3408 pub expansion: Option<ExpansionInfo>,
3409 /// Lead-section summary resolved against the hit's *own* mem schema
3410 /// at search time (see [`SummaryPair`]). The renderer cannot resolve
3411 /// it correctly on its own — the global `type_by_name` only sees the
3412 /// `default` schema, so a `software`-schema hit (`requirement` →
3413 /// `Statement`, `actor` → `Role`) would miss its anchor section and
3414 /// render `—`. `#[serde(skip)]` keeps `SearchHit`'s wire shape
3415 /// unchanged; the value surfaces on the envelope's `summary_heading` /
3416 /// `summary_value`. `None` only on hits built outside the engine
3417 /// search op (FFI/bridge and test fixtures), where the renderer falls
3418 /// back to the default-schema lookup.
3419 #[serde(skip)]
3420 pub summary: Option<SummaryPair>,
3421}
3422
3423/// Lead-section `(heading, value)` for a search/list hit, resolved
3424/// against the hit's own mem schema at search time. Carried in-memory
3425/// from the search op to the renderers; see [`SearchHit::summary`].
3426#[derive(Debug, Clone)]
3427pub struct SummaryPair {
3428 pub heading: String,
3429 pub value: String,
3430}
3431
3432/// Search result with metadata.
3433#[derive(Debug, Clone, Serialize)]
3434pub struct SearchResult {
3435 pub total: usize,
3436 pub returned: usize,
3437 pub offset: usize,
3438 /// Sum of estimated tokens across all matching entities (pre-pagination).
3439 /// Lets agents judge read cost before paging.
3440 pub total_tokens: usize,
3441 pub hits: Vec<SearchHit>,
3442 /// Faceted counts over the unpaginated hit set. Stable closed
3443 /// struct; zero-count entries are excluded.
3444 #[serde(default, skip_serializing_if = "Option::is_none")]
3445 pub facets: Option<Facets>,
3446 /// Non-fatal issues surfaced to the caller. Structured
3447 /// `WarningHint` shape (`{code, details, message}`) — same wire
3448 /// envelope every other tool's warnings already use. Agents
3449 /// branch on `code`; the message field carries the existing
3450 /// remediation prose.
3451 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3452 pub warnings: Vec<WarningHint>,
3453}
3454
3455/// List result with token totals.
3456#[derive(Debug, Clone, Serialize)]
3457pub struct ListResult {
3458 pub total: usize,
3459 pub returned: usize,
3460 pub offset: usize,
3461 pub total_tokens: usize,
3462 pub hits: Vec<SearchHit>,
3463 /// Non-fatal issues surfaced to the caller — same structured
3464 /// shape as `SearchResult.warnings`.
3465 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3466 pub warnings: Vec<WarningHint>,
3467}
3468
3469// ---------------------------------------------------------------------------
3470// Health types
3471// ---------------------------------------------------------------------------
3472
3473/// Health check result for one entity.
3474#[derive(Debug, Clone, Serialize)]
3475pub struct HealthReport {
3476 pub id: EntityId,
3477 pub title: String,
3478 pub score: f32,
3479 pub issues: Vec<HealthIssue>,
3480}
3481
3482/// Machine-readable condition discriminator for a [`HealthIssue`] —
3483/// the enumeration lives here, with the issue type, and is never
3484/// re-derived per projection. A projection that lists issues carries
3485/// the code; the code is NEVER only a message-string prefix (a
3486/// projection that drops messages would silently collapse distinct
3487/// conditions — the exact misdirection `SECTION_HEADING_MISMATCH`
3488/// exists to prevent).
3489#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
3490#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
3491pub enum HealthIssueCode {
3492 /// The required section/field is genuinely absent or empty.
3493 Missing,
3494 /// The section's content is present in the file but sits under a
3495 /// heading that does not derive back to the section key — NOT
3496 /// missing; fix the schema's heading/key pair.
3497 SectionHeadingMismatch,
3498 /// The entity carries a relationship whose rel-type the mem's
3499 /// schema does not declare.
3500 UndeclaredRelationship,
3501 /// An existing edge violates the rel-type's declared
3502 /// `source_types` / `target_types` shape.
3503 InvalidRelShape,
3504}
3505
3506impl HealthIssueCode {
3507 /// Stable wire string — matches the serde `SCREAMING_SNAKE_CASE`
3508 /// serialization, exposed for text renderers.
3509 pub fn as_wire(&self) -> &'static str {
3510 match self {
3511 HealthIssueCode::Missing => "MISSING",
3512 HealthIssueCode::SectionHeadingMismatch => "SECTION_HEADING_MISMATCH",
3513 HealthIssueCode::UndeclaredRelationship => "UNDECLARED_RELATIONSHIP",
3514 HealthIssueCode::InvalidRelShape => "INVALID_REL_SHAPE",
3515 }
3516 }
3517}
3518
3519#[derive(Debug, Clone, Serialize)]
3520pub struct HealthIssue {
3521 pub field: String,
3522 /// Which condition this issue reports — see [`HealthIssueCode`].
3523 pub code: HealthIssueCode,
3524 pub message: String,
3525}
3526
3527/// One quarantine-roster entry on [`HealthSummary`]: the mem, the
3528/// typed reason code, and the full reason message (repair command
3529/// included — plan-01 material).
3530#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
3531pub struct QuarantinedMemReport {
3532 pub mem: String,
3533 pub reason_code: String,
3534 pub reason_message: String,
3535}
3536
3537/// One per-file load failure surfaced on the health report. `file` is
3538/// the path the loader reported (absolute for folder mounts after the
3539/// reload-normalization pass); `error` is the loader's message, which
3540/// names the remedy where one exists (the merge-conflict refusal names
3541/// `memstead conflicts resolve`).
3542#[derive(Debug, Clone, serde::Serialize)]
3543pub struct LoadErrorReport {
3544 pub file: String,
3545 pub error: String,
3546}
3547
3548/// Aggregated health report for the whole graph.
3549#[derive(Debug, Clone, Serialize)]
3550pub struct HealthSummary {
3551 pub stale_entities: Vec<StaleEntity>,
3552 /// Entities the day threshold would list as stale but whose anchors
3553 /// resolve: fresh by the anchor clock, absent from `stale_entities`,
3554 /// listed here so the reading names the clock that overruled the
3555 /// threshold. Empty whenever no anchor spoke.
3556 pub anchor_fresh: Vec<StaleEntity>,
3557 pub missing_fields: Vec<HealthReport>,
3558 pub orphan_count: usize,
3559 pub stub_count: usize,
3560 /// Typed non-fatal issues visible to every caller of `Engine::health()`.
3561 /// Populated in two layers: `Engine.load_warnings` contributes drift
3562 /// warnings surfaced during mem load / reload / attach
3563 /// (`SuspiciousNestedPrefix`, future load-time checks); the MCP
3564 /// handler additionally appends request-scoped warnings (unknown
3565 /// `include` keys, clamped `limit`) on top of whatever the engine
3566 /// merged. Empty on the happy path.
3567 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3568 pub warnings: Vec<WarningHint>,
3569 /// Quarantine roster: mems that failed their mem-level boot step
3570 /// and serve nothing until repaired + reloaded. Always present in
3571 /// `Engine::health()` output when non-empty — a boot-honesty fact,
3572 /// never behind an include gate. Empty (and omitted from the wire)
3573 /// on a healthy workspace, keeping default output byte-unchanged.
3574 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3575 pub quarantined: Vec<QuarantinedMemReport>,
3576 /// Per-file load failures: entity files the loader refused (git
3577 /// merge-conflict markers, unreadable bytes, parser failures). The
3578 /// same boot-honesty class as `quarantined` — always present when
3579 /// non-empty, never behind an include gate — because each entry's
3580 /// message names the remedy (e.g. the conflict refusal names
3581 /// `memstead conflicts resolve`), and a remedy no surface renders
3582 /// is a capability nobody finds at the moment it is needed. Empty
3583 /// (and omitted from the wire) on a clean workspace.
3584 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3585 pub load_errors: Vec<LoadErrorReport>,
3586 /// Workspace-level boot diagnosis from a diagnostic-shell engine
3587 /// (`{code, message}`): why the real workspace could not boot at
3588 /// all. Absent on every ordinarily booted engine.
3589 #[serde(default, skip_serializing_if = "Option::is_none")]
3590 pub boot_diagnosis: Option<serde_json::Value>,
3591 /// Real-entity count per leaf-declared type (`<schema_ref>:<type>`
3592 /// keys) — the population the orphan axis exempts because those
3593 /// types are terminal by construction.
3594 /// Visible, never vanished. Empty (and omitted from the wire) for
3595 /// schemas that declare nothing, keeping default output
3596 /// byte-unchanged.
3597 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
3598 pub leaf_entities_by_type: std::collections::BTreeMap<String, usize>,
3599 /// Dangling references: the three conditions [`DanglingLink`] carries,
3600 /// which are NOT all "a body wiki-link to a missing file" — that is one
3601 /// of them. See [`DanglingLinkKind`] for the other two (a body link to
3602 /// a written entity the referrer does not relate to, and a
3603 /// relationships row naming an absent entity) and their repairs.
3604 /// Populated only when the caller
3605 /// opts in via `include=["dangling_links"]`; `None` otherwise, so
3606 /// absence-of-key means "not requested" and presence-of-empty-array
3607 /// means "requested, zero findings". Scan is handler-driven (same
3608 /// pattern as `warnings` above), so non-MCP callers of
3609 /// `Engine::health()` always see `None` unless they invoke
3610 /// [`health::collect_dangling_links`] directly.
3611 #[serde(default, skip_serializing_if = "Option::is_none")]
3612 pub dangling_links: Option<Vec<DanglingLink>>,
3613 /// Integrity findings (`{ id, axis, code, detail }`) over the
3614 /// conformance axis — and, under `include=["integrity"]`, the
3615 /// consistency axis too. Populated only when the caller opts in
3616 /// via `include=["conformance"]` / `include=["integrity"]`;
3617 /// `None` otherwise (same handler-driven pattern as
3618 /// `dangling_links`: absence means "not requested", an empty
3619 /// array means "requested, fully integral").
3620 #[serde(default, skip_serializing_if = "Option::is_none")]
3621 pub findings: Option<Vec<integrity::IntegrityFinding>>,
3622 /// Tag distribution (count per distinct tag, case-sensitive) over non-stub
3623 /// entities. Populated only when the caller opts in via `include=["tags"]`.
3624 /// Case-variant drift is surfaced via the sibling field [`tag_distribution_folded`].
3625 #[serde(default, skip_serializing_if = "Option::is_none")]
3626 pub tag_distribution: Option<Vec<TagDistribution>>,
3627 /// Case-drift audit sidecar: entries where two or more casings of the same
3628 /// canonical tag (lowercase) both appear in authored tags. Only entries with
3629 /// `variants.len() > 1` are returned — the default read of `tag_distribution`
3630 /// stays untouched. Populated alongside `tag_distribution`.
3631 #[serde(default, skip_serializing_if = "Option::is_none")]
3632 pub tag_distribution_folded: Option<Vec<FoldedTag>>,
3633 /// Count of non-stub entities whose `tags` metadata is missing, empty,
3634 /// or resolves to zero effective tags after splitting on `,` and trimming.
3635 /// Populated alongside `tag_distribution` when `include=["tags"]`.
3636 #[serde(default, skip_serializing_if = "Option::is_none")]
3637 pub untagged_entities: Option<UntaggedStats>,
3638}
3639
3640#[derive(Debug, Clone, Serialize)]
3641pub struct StaleEntity {
3642 pub id: EntityId,
3643 pub title: String,
3644 pub days_since_modified: u64,
3645 /// The anchor state that produced this row when the anchor clock
3646 /// spoke (`drifted` or `recheck`, or `resolves` on a fresh-by-anchor
3647 /// row); `None` means the day threshold produced it. The two clocks
3648 /// never both speak for one entity: an entity with an adjudicated
3649 /// hash-bearing anchor reads by its anchors, the rest by the day
3650 /// threshold.
3651 pub anchor_state: Option<String>,
3652}
3653
3654/// One entry in the tag distribution surface: an authored tag string, the
3655/// number of non-stub entities carrying it, and the per-entity-type breakdown
3656/// of those hits. Comparison is case-sensitive — `decision` and `Decision`
3657/// count as distinct entries here (see `tag_distribution_folded` for the
3658/// drift-aware sidecar).
3659#[derive(Debug, Clone, Serialize)]
3660pub struct TagDistribution {
3661 pub tag: String,
3662 pub count: usize,
3663 pub by_entity_type: HashMap<String, usize>,
3664}
3665
3666/// Case-drift audit entry. Surfaces when two or more casings of the same
3667/// canonical (lowercased) tag appear in the authored graph — the agent-hostile
3668/// bug where `decision` and `Decision` look like two healthy low-count tags
3669/// in the case-sensitive primary surface.
3670#[derive(Debug, Clone, Serialize)]
3671pub struct FoldedTag {
3672 /// Lowercase form — the canonical key.
3673 pub canonical: String,
3674 /// Sum of counts across every casing variant.
3675 pub total: usize,
3676 /// Authored casings (as-written), each with its individual count.
3677 /// Sorted by `count` descending; ties broken by `tag` ascending.
3678 pub variants: Vec<TagVariant>,
3679}
3680
3681#[derive(Debug, Clone, Serialize)]
3682pub struct TagVariant {
3683 pub tag: String,
3684 pub count: usize,
3685}
3686
3687/// Aggregate count of non-stub entities with zero effective tags, broken
3688/// down by `entity_type`. "Untagged" collapses three states: missing `tags`
3689/// metadata, empty string value, and comma-only value (e.g. `","`).
3690#[derive(Debug, Clone, Serialize)]
3691pub struct UntaggedStats {
3692 pub total: usize,
3693 pub by_entity_type: HashMap<String, usize>,
3694}
3695
3696/// One dangling-reference finding surfaced by
3697/// `memstead_health include=["dangling_links"]` and projected onto the
3698/// consistency axis by `include=["integrity"]`.
3699///
3700/// Three conditions reach this type, and [`kind`](Self::kind) says which:
3701/// a body wiki-link whose target has no markdown file (the post-delete /
3702/// renamed-without-rewrite / typo signal), a body wiki-link to a fully
3703/// written entity that the referrer does not relate to, and a relationships
3704/// row naming an entity absent from the store. Their repairs differ, so the
3705/// codes differ; see [`DanglingLinkKind`].
3706///
3707/// The prose this replaces described only the first condition, which is how
3708/// the fusion survived: the type read as if it had one subject while
3709/// producing three.
3710#[derive(Debug, Clone, Serialize)]
3711pub struct DanglingLink {
3712 /// Which of the three conditions this is, and therefore which repair
3713 /// applies. Carried from the one producer, never re-derived: the split
3714 /// happens where the conditions are distinguished (04/06).
3715 pub kind: DanglingLinkKind,
3716 pub from: EntityId,
3717 /// Canonical ID the wiki-link resolves to.
3718 ///
3719 /// NOT necessarily a stub: it is a stub or absent for
3720 /// [`DanglingLinkKind::LinkTargetMissing`] and
3721 /// [`DanglingLinkKind::RelationTargetMissing`], and a real, non-stub
3722 /// entity for [`DanglingLinkKind::LinkNotRelated`], where the entity is
3723 /// fine and the relationship row is what is missing. The old wording said
3724 /// "stub-typed in the store", which was true of one of the three
3725 /// conditions this type carried.
3726 pub target_id: EntityId,
3727 /// Resolved mem-relative path segment of the target ID (e.g. `gone`
3728 /// for `specs--gone`). This is the normalised form the engine records —
3729 /// not the literal `[[…]]` characters as authored. Widening `WikiLink`
3730 /// to preserve the authored form is a future-work item if agents need
3731 /// grep-to-source precision.
3732 pub target_path: String,
3733 /// Section key the body wiki-link appears in (e.g. `"purpose"`).
3734 ///
3735 /// `None` for [`DanglingLinkKind::RelationTargetMissing`], whose source is
3736 /// the auto-managed relationships block rather than a body section. That
3737 /// absence used to be the ONLY way to tell that condition apart, which is
3738 /// why `kind` exists: a reader should not have to inspect a payload for
3739 /// nulls to learn which repair applies.
3740 #[serde(skip_serializing_if = "Option::is_none")]
3741 pub section: Option<String>,
3742}
3743
3744/// The three conditions the one dangling-link collector distinguishes.
3745///
3746/// They were emitted under a single `DANGLING_LINK` code through an identical
3747/// payload, so a reader could not tell which of three repairs applied, and
3748/// neither could the surfaces rendering it. Two of the three were not
3749/// discriminable at all. The project's error discipline is that a typed code
3750/// names one condition, so each gets its own (04/06).
3751///
3752/// The serialised value IS the code, so a payload's `kind`, a finding's
3753/// `code` and a rendered line all read the same string. A kebab-case serde
3754/// name would be a second spelling of one condition, which is the shape of
3755/// the defect this plan removes.
3756#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3757pub enum DanglingLinkKind {
3758 /// A body wiki-link whose target is absent from the store or present only
3759 /// as a stub. Repair: create the target entity.
3760 #[serde(rename = "DANGLING_LINK_TARGET_MISSING")]
3761 LinkTargetMissing,
3762 /// A body wiki-link to an existing, non-stub entity that the referrer's
3763 /// relationships list does not name. The entity is fine; the relationship
3764 /// row is missing. Repair: `memstead_relate` the two.
3765 #[serde(rename = "DANGLING_LINK_NOT_RELATED")]
3766 LinkNotRelated,
3767 /// A relationships row whose target is entirely absent, neither stub nor
3768 /// real. Repair: remove the row, or create the target.
3769 ///
3770 /// A stub target here is a legitimate forward reference (the alias
3771 /// machinery auto-stubs absent targets by design) and is deliberately not
3772 /// flagged.
3773 #[serde(rename = "DANGLING_RELATION_TARGET_MISSING")]
3774 RelationTargetMissing,
3775}
3776
3777impl DanglingLinkKind {
3778 /// The stable wire code. One code, one condition, one repair.
3779 pub fn code(&self) -> &'static str {
3780 match self {
3781 DanglingLinkKind::LinkTargetMissing => "DANGLING_LINK_TARGET_MISSING",
3782 DanglingLinkKind::LinkNotRelated => "DANGLING_LINK_NOT_RELATED",
3783 DanglingLinkKind::RelationTargetMissing => "DANGLING_RELATION_TARGET_MISSING",
3784 }
3785 }
3786
3787 /// Every code this family can emit. The strict counter and any other
3788 /// consumer filtering on the literal string reads THIS rather than
3789 /// keeping its own copy.
3790 ///
3791 /// Kept honest by `all_codes_covers_every_variant`, whose exhaustive
3792 /// match stops compiling when a variant is added — without it this is
3793 /// just another hand-written list, and a fourth condition would fall
3794 /// out of the strict gate silently, which is the failure the roster
3795 /// exists to prevent.
3796 pub const ALL_CODES: &'static [&'static str] = &[
3797 "DANGLING_LINK_TARGET_MISSING",
3798 "DANGLING_LINK_NOT_RELATED",
3799 "DANGLING_RELATION_TARGET_MISSING",
3800 ];
3801
3802 /// What to do about it, in one clause.
3803 pub fn repair(&self) -> &'static str {
3804 match self {
3805 DanglingLinkKind::LinkTargetMissing => {
3806 "create the target entity, or remove the wiki-link"
3807 }
3808 DanglingLinkKind::LinkNotRelated => {
3809 "relate the two entities, so the body link is backed by a relationship row"
3810 }
3811 DanglingLinkKind::RelationTargetMissing => {
3812 "remove the relationship row, or create the target entity"
3813 }
3814 }
3815 }
3816}
3817
3818// ---------------------------------------------------------------------------
3819// Export types
3820// ---------------------------------------------------------------------------
3821
3822/// Export result.
3823///
3824/// Workspace-wide `export_markdown` returns this struct with
3825/// `skipped_mounts` populated for every mount whose active backend
3826/// doesn't support
3827/// markdown regeneration in place (git-branch, archive). Per-mem
3828/// export against an incompatible backend short-circuits with
3829/// `EngineError::MarkdownExportUnsupportedBackend` instead.
3830#[derive(Debug, Clone, Serialize)]
3831pub struct ExportResult {
3832 pub written: usize,
3833 pub unchanged: usize,
3834 /// Mounts that the workspace-wide export declined to write
3835 /// because their backend doesn't support markdown regeneration.
3836 /// Empty on the happy path (every mount is folder-backed).
3837 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3838 pub skipped_mounts: Vec<SkippedMount>,
3839 /// Entities the export declined to regenerate because their stored body
3840 /// ends inside an unterminated code fence: writing them would seal the
3841 /// sections that fence absorbed. Skipping one entity
3842 /// is the non-stranding half of that refusal — the rest of the export
3843 /// still lands, and the entity is named rather than silently passed over.
3844 /// Empty on the happy path.
3845 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3846 pub refused_entities: Vec<RefusedEntity>,
3847}
3848
3849/// One entity `export_markdown` declined, with the condition that stopped it.
3850#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
3851pub struct RefusedEntity {
3852 pub id: String,
3853 pub reason: String,
3854 pub detail: String,
3855}
3856
3857/// One mount declined by `export_markdown` because the active
3858/// backend doesn't support in-place markdown regeneration.
3859///
3860/// `reason` is a stable token (today: `"backend_does_not_support_markdown_export"`);
3861/// `active_backend` matches [`crate::workspace::MountStorage::backend_id`].
3862#[derive(Debug, Clone, Serialize)]
3863pub struct SkippedMount {
3864 pub mem: String,
3865 pub active_backend: String,
3866 pub reason: String,
3867}
3868
3869/// Result of a `.mem` mem-archive export.
3870#[derive(Debug, Clone, Serialize)]
3871pub struct MemExportResult {
3872 pub archive_path: String,
3873 pub name: String,
3874 pub version: String,
3875 pub entity_count: usize,
3876 pub size_bytes: u64,
3877 /// Cross-mem edges in the exported slice whose target won't travel
3878 /// inside this single-mem archive — `install` will reject the
3879 /// archive for each one. Surfaced at export time
3880 /// (`DANGLING_CROSS_MEM_EDGE_IN_EXPORT`) so the operator sees the
3881 /// install-time failure before sharing. Empty for a self-contained
3882 /// export.
3883 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3884 pub dangling_cross_mem_edges: Vec<crate::validator::DanglingCrossMemEdge>,
3885 /// Private-pattern spans redacted in the archive's authoring
3886 /// provenance, counted per class (`ops::redaction`); empty when no
3887 /// rationale carried one.
3888 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3889 pub redactions: Vec<crate::ops::redaction::RedactionCount>,
3890 /// Ids in the exported slice whose stored body ends inside an
3891 /// unterminated code fence. `install` refuses the archive for each one
3892 /// (the repack would bury the sections that fence absorbed), so the
3893 /// condition is surfaced here for the same reason the dangling edges
3894 /// above are: the operator should see the install-time failure before
3895 /// sharing, not after. One predicate, two postures.
3896 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3897 pub unterminated_fence_entities: Vec<String>,
3898}
3899
3900/// Result of `Engine::set_mem_internal`. Carries `warnings` for the same
3901/// reason every other config setter does: without a channel the
3902/// `CONFIG_WRITE_INTERVENED` report has nowhere to go.
3903#[derive(Debug, Clone, Serialize)]
3904pub struct SetMemInternalOutcome {
3905 pub mem: String,
3906 pub internal: bool,
3907 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3908 pub warnings: Vec<WarningHint>,
3909}
3910
3911/// Result of `Engine::set_mem_version`. Carries the (mem,
3912/// old_version, new_version) triple so callers (CLI, MCP) can surface
3913/// the change without an extra read.
3914#[derive(Debug, Clone, Serialize)]
3915pub struct SetMemVersionOutcome {
3916 pub mem: String,
3917 /// Previous version. `None` when the mem config carried no
3918 /// version field before this call (pre-gate / externally-imported
3919 /// config, or the residual `MEM_CONFIG_INCOMPLETE` path).
3920 #[serde(default, skip_serializing_if = "Option::is_none")]
3921 pub old_version: Option<semver::Version>,
3922 pub new_version: semver::Version,
3923 /// Concurrent-drift warnings detected at the pre-write probe —
3924 /// e.g. `MemReloaded` when a sibling engine committed between
3925 /// this engine's last snapshot and the set-version write. Empty
3926 /// on the happy path. F1.
3927 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3928 pub warnings: Vec<WarningHint>,
3929}
3930
3931/// Result of `Engine::set_mem_title`. Same shape discipline as
3932/// [`SetMemDescriptionOutcome`].
3933#[derive(Debug, Clone, Serialize)]
3934pub struct SetMemTitleOutcome {
3935 pub mem: String,
3936 #[serde(default, skip_serializing_if = "Option::is_none")]
3937 pub old_title: Option<String>,
3938 #[serde(default, skip_serializing_if = "Option::is_none")]
3939 pub new_title: Option<String>,
3940 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3941 pub warnings: Vec<WarningHint>,
3942}
3943
3944/// Result of `Engine::set_mem_subject`. The block sets/clears as a
3945/// unit; old/new carry the whole block.
3946#[derive(Debug, Clone, Serialize)]
3947pub struct SetMemSubjectOutcome {
3948 pub mem: String,
3949 #[serde(default, skip_serializing_if = "Option::is_none")]
3950 pub old_subject: Option<memstead_schema::MemSubject>,
3951 #[serde(default, skip_serializing_if = "Option::is_none")]
3952 pub new_subject: Option<memstead_schema::MemSubject>,
3953 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3954 pub warnings: Vec<WarningHint>,
3955}
3956
3957/// Result of `Engine::set_mem_description`. Carries the (mem,
3958/// old_description, new_description) triple so callers can surface
3959/// the change without an extra read.
3960#[derive(Debug, Clone, Serialize)]
3961pub struct SetMemDescriptionOutcome {
3962 pub mem: String,
3963 /// Previous description. `None` when the mem config carried no
3964 /// description before this call (the common case — mem creation
3965 /// seeds none).
3966 #[serde(default, skip_serializing_if = "Option::is_none")]
3967 pub old_description: Option<String>,
3968 /// The description now persisted; `None` when the call cleared it.
3969 #[serde(default, skip_serializing_if = "Option::is_none")]
3970 pub new_description: Option<String>,
3971 /// Concurrent-drift warnings detected at the pre-write probe.
3972 /// Empty on the happy path.
3973 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3974 pub warnings: Vec<WarningHint>,
3975}
3976
3977/// Result of `Engine::set_mem_sync_state`. Carries the (mem, key,
3978/// previous-token) triple so callers (CLI, MCP) can surface the change
3979/// without an extra read. The token values are opaque to the engine —
3980/// see `MemConfig::sync_state`.
3981#[derive(Debug, Clone, Serialize)]
3982pub struct SetMemSyncStateOutcome {
3983 pub mem: String,
3984 /// The sync-state key that was set or cleared (opaque; the ingest
3985 /// layer keys per `(ingest, facet)`).
3986 pub key: String,
3987 /// Previous token under `key`, `None` when the key was unset before
3988 /// this call. Lets callers report set-vs-overwrite without a read.
3989 #[serde(default, skip_serializing_if = "Option::is_none")]
3990 pub previous: Option<String>,
3991 /// True when an empty token cleared an existing key. `false` for a
3992 /// set/overwrite and for a clear of an already-absent key (a no-op).
3993 pub removed: bool,
3994 /// Concurrent-drift warnings detected at the pre-write probe — e.g.
3995 /// `MemReloaded` when a sibling engine committed between this
3996 /// engine's last snapshot and the write. Empty on the happy path.
3997 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3998 pub warnings: Vec<WarningHint>,
3999}
4000
4001// ---------------------------------------------------------------------------
4002// Context types
4003// ---------------------------------------------------------------------------
4004
4005/// Context around an entity — neighbors, community, related entities.
4006#[derive(Debug, Clone, Serialize)]
4007pub struct ContextResult {
4008 pub entity_id: EntityId,
4009 pub community: Option<String>,
4010 pub neighbors: Vec<NeighborInfo>,
4011}
4012
4013#[derive(Debug, Clone, Serialize)]
4014pub struct NeighborInfo {
4015 pub id: EntityId,
4016 pub title: String,
4017 pub relationship: String,
4018 pub direction: Direction,
4019}
4020
4021#[derive(Debug, Clone, Serialize)]
4022pub enum Direction {
4023 Outgoing,
4024 Incoming,
4025}
4026
4027// ---------------------------------------------------------------------------
4028// Status
4029// ---------------------------------------------------------------------------
4030
4031/// Graph status — node / edge counts and schema distribution. Renamed from
4032/// the former `Stats` when the `stats` command became `status`; the fields are unchanged so every caller's
4033/// payload stays byte-compatible.
4034#[derive(Debug, Clone, Serialize)]
4035pub struct Status {
4036 pub entity_count: usize,
4037 pub edge_count: usize,
4038 /// Edge count per relationship type, in name order: a `BTreeMap` so
4039 /// every renderer (CLI, MCP, ui-api) emits the same bytes run after run.
4040 pub edge_types: std::collections::BTreeMap<String, usize>,
4041 pub community_count: usize,
4042 pub mem_count: usize,
4043 pub types_in_use: Vec<String>,
4044}
4045
4046// ---------------------------------------------------------------------------
4047// Reload result
4048// ---------------------------------------------------------------------------
4049
4050#[derive(Debug, Clone, Serialize)]
4051pub struct ReloadResult {
4052 pub added: Vec<EntityId>,
4053 pub changed: Vec<EntityId>,
4054 pub removed: Vec<EntityId>,
4055}
4056
4057/// Per-mem reload outcome — produced by [`Engine::reload_one_mem`]
4058/// and surfaced verbatim in the `memstead_reload` MCP tool's response when
4059/// an explicit operator-triggered reload runs against a single mem.
4060/// Auto-reloads on the read path consume this internally and emit a
4061/// [`WarningHint::MemReloaded`] (which carries `mem`, `old_head`,
4062/// `new_head`, `entities_loaded` — the diff list is intentionally
4063/// omitted from the lean warning payload; agents that need it call
4064/// `memstead_changes_since` themselves with the supplied `old_head`).
4065///
4066/// `head_before` / `head_after` are hex-rendered SHAs (or
4067/// `EMPTY_TREE_SHA` for the no-baseline case) so the wire shape
4068/// matches what `memstead_changes_since` already accepts as `since`.
4069/// `changed_entity_ids` is the list of non-stub IDs whose
4070/// `content_hash` differs between the pre- and post-reload store
4071/// snapshots, plus every newly-added or newly-removed id — same
4072/// semantic as `ReloadResult { added, changed, removed }` flattened
4073/// into a single set so callers don't have to merge three lists.
4074#[derive(Debug, Clone, Serialize)]
4075pub struct ReloadReport {
4076 pub mem: String,
4077 pub head_before: String,
4078 pub head_after: String,
4079 pub entities_loaded: usize,
4080 pub changed_entity_ids: Vec<EntityId>,
4081}
4082
4083/// What `Engine::full_refresh` changed — and, just as deliberately,
4084/// what it SKIPPED. The refresh is additive-only: removals never take
4085/// effect warm, and this report is how the caller learns whether its
4086/// next call will succeed instead of guessing.
4087#[derive(Debug, Clone, Default, Serialize)]
4088pub struct FullRefreshReport {
4089 /// Schema versions (`name@version`) newly resolvable.
4090 pub schemas_added: Vec<String>,
4091 /// In-memory schema versions absent from the re-scanned sources —
4092 /// the removal was skipped; they stay resolvable until restart.
4093 pub schema_removals_skipped: Vec<String>,
4094 /// Mems newly mounted (cold-loaded like any boot-time mount).
4095 pub mems_mounted: Vec<String>,
4096 /// Mounted writable mems absent from the re-scanned roster — unmounted
4097 /// atomically, no longer served (applied since 2026-09-02; the former
4098 /// `mem_removals_skipped` reported them as left live until restart).
4099 pub mems_unmounted: Vec<String>,
4100 /// Roster entries that failed to mount and sit on the quarantine
4101 /// roster with their reason.
4102 pub mems_quarantined: Vec<String>,
4103 /// Per-item failures: a source or mount that failed to refresh.
4104 /// Failed items never surface as newly available; the others
4105 /// proceed.
4106 pub failures: Vec<RefreshFailure>,
4107 /// Wall-clock cost of the refresh (the bounded-cost report).
4108 pub elapsed_ms: u64,
4109}
4110
4111/// One failed refresh item — `item` is `schema-source:<which>`,
4112/// `mount:<mem>`, `mount-manifest`, or `workspace`.
4113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4114pub struct RefreshFailure {
4115 pub item: String,
4116 pub error: String,
4117}
4118
4119#[cfg(test)]
4120mod tests {
4121 use super::*;
4122
4123 /// `ALL_CODES` is what the strict gate and the graph referee filter
4124 /// on, so a condition missing from it is a condition that stops
4125 /// failing a gate — silently, since nothing else would break. The
4126 /// exhaustive match below is the enforcement: add a variant and this
4127 /// stops COMPILING, which is the only moment anyone would otherwise
4128 /// have to remember.
4129 #[test]
4130 fn all_codes_covers_every_variant() {
4131 let every = [
4132 DanglingLinkKind::LinkTargetMissing,
4133 DanglingLinkKind::LinkNotRelated,
4134 DanglingLinkKind::RelationTargetMissing,
4135 ];
4136 for kind in every {
4137 // Exhaustive by construction: a new variant fails to compile
4138 // here before it can quietly miss the roster.
4139 match kind {
4140 DanglingLinkKind::LinkTargetMissing
4141 | DanglingLinkKind::LinkNotRelated
4142 | DanglingLinkKind::RelationTargetMissing => {}
4143 }
4144 assert!(
4145 DanglingLinkKind::ALL_CODES.contains(&kind.code()),
4146 "{} is emitted but absent from ALL_CODES, so every filter \
4147 reading the roster would skip it",
4148 kind.code()
4149 );
4150 assert!(
4151 !kind.repair().is_empty(),
4152 "{} has no repair clause",
4153 kind.code()
4154 );
4155 }
4156 assert_eq!(
4157 DanglingLinkKind::ALL_CODES.len(),
4158 every.len(),
4159 "ALL_CODES carries a code no variant emits"
4160 );
4161 // The serialised `kind` IS the code — one spelling per condition.
4162 for kind in every {
4163 assert_eq!(
4164 serde_json::to_value(kind).unwrap(),
4165 serde_json::Value::String(kind.code().to_string())
4166 );
4167 }
4168 }
4169
4170 // Locks the wire shape of `Query` across every combination of
4171 // set/unset fields. Agents compose queries on the fly; a drift here
4172 // silently changes the MCP tool's JSON contract.
4173 #[test]
4174 fn query_json_roundtrip_every_combination() {
4175 let cases: Vec<Query> = vec![
4176 Query::default(),
4177 Query {
4178 any: vec!["auth".into()],
4179 ..Default::default()
4180 },
4181 Query {
4182 not: vec!["mock".into()],
4183 ..Default::default()
4184 },
4185 Query {
4186 phrase: Some("client side agent".into()),
4187 ..Default::default()
4188 },
4189 Query {
4190 field: Some("identity".into()),
4191 ..Default::default()
4192 },
4193 Query {
4194 any: vec!["a".into(), "b".into()],
4195 not: vec!["x".into()],
4196 phrase: Some("ex act".into()),
4197 field: Some("purpose".into()),
4198 },
4199 ];
4200 for q in &cases {
4201 let json = serde_json::to_string(q).expect("serialize");
4202 let back: Query = serde_json::from_str(&json).expect("deserialize");
4203 assert_eq!(q.any, back.any, "any field round-trip: {json}");
4204 assert_eq!(q.not, back.not, "not field round-trip: {json}");
4205 assert_eq!(q.phrase, back.phrase, "phrase field round-trip: {json}");
4206 assert_eq!(q.field, back.field, "field field round-trip: {json}");
4207 assert_eq!(q.is_empty(), back.is_empty());
4208 }
4209 }
4210
4211 // Empty fields stay out of the wire shape — agents see a lean object.
4212 #[test]
4213 fn query_default_serializes_as_empty_object() {
4214 let q = Query::default();
4215 let json = serde_json::to_string(&q).unwrap();
4216 assert_eq!(json, "{}", "default query must serialize as `{{}}`");
4217 }
4218
4219 // Null / missing keys all round-trip to the same default via serde.
4220 #[test]
4221 fn query_accepts_missing_and_null_fields() {
4222 let with_missing: Query = serde_json::from_str("{}").unwrap();
4223 let with_nulls: Query =
4224 serde_json::from_str(r#"{"any":[],"not":[],"phrase":null,"field":null}"#).unwrap();
4225 assert!(with_missing.is_empty());
4226 assert!(with_nulls.is_empty());
4227 }
4228
4229 // Schema is generated via schemars so MCP agents see the full
4230 // structured contract. Cheap smoke test — locks that the four known
4231 // fields appear and nothing regresses to an action-discriminator.
4232 #[test]
4233 fn query_json_schema_exposes_four_fields() {
4234 let schema = schemars::schema_for!(Query);
4235 let rendered = serde_json::to_string(&schema).unwrap();
4236 for field in ["any", "not", "phrase", "field"] {
4237 assert!(
4238 rendered.contains(&format!("\"{field}\"")),
4239 "schema must mention `{field}`: {rendered}"
4240 );
4241 }
4242 }
4243
4244 // ------------------------------------------------------------------
4245 // WarningHint wire-envelope snapshots. Each variant locks `code`
4246 // (stable UPPER_SNAKE_CASE), a message substring (phrasing may
4247 // drift — we assert a durable anchor), and the `details` key-set.
4248 // Arrays are asserted shape-only because their content depends on
4249 // the active schema / allowed-include list.
4250 // ------------------------------------------------------------------
4251
4252 fn to_envelope(w: &WarningHint) -> serde_json::Value {
4253 serde_json::to_value(w).expect("WarningHint serializes")
4254 }
4255
4256 #[test]
4257 fn warning_hint_missing_required_section_envelope() {
4258 // F9: type-level write_rules moved out of per-warning details
4259 // to the mutation response's top-level `type_guidance` map.
4260 // The warning now carries only section-axis fields.
4261 let w = WarningHint::MissingRequiredSection {
4262 entity_type: "spec".into(),
4263 key: "purpose".into(),
4264 heading: "Purpose".into(),
4265 write_rules: vec!["one sentence".into(), "state the why".into()],
4266 };
4267 let json = to_envelope(&w);
4268 assert_eq!(json["code"], "MISSING_REQUIRED_SECTION");
4269 assert!(
4270 json["message"]
4271 .as_str()
4272 .unwrap()
4273 .contains("required section")
4274 );
4275 assert_eq!(json["details"]["entity_type"], "spec");
4276 assert_eq!(json["details"]["key"], "purpose");
4277 assert_eq!(json["details"]["heading"], "Purpose");
4278 assert!(json["details"]["write_rules"].is_array());
4279 // type_write_rules no longer rides on the per-warning envelope.
4280 assert!(json["details"].get("type_write_rules").is_none());
4281 }
4282
4283 #[test]
4284 fn warning_hint_undeclared_relationship_open_envelope() {
4285 let w = WarningHint::UndeclaredRelationshipOpen {
4286 rel_type: "USES".into(),
4287 message: "USES admitted in open mode".into(),
4288 };
4289 let json = to_envelope(&w);
4290 assert_eq!(json["code"], "UNDECLARED_RELATIONSHIP_OPEN");
4291 // Display delegates to the stored message — substring anchor is safe.
4292 assert!(json["message"].as_str().unwrap().contains("open mode"));
4293 assert_eq!(json["details"]["rel_type"], "USES");
4294 // Consistency rule: details must not duplicate the envelope message.
4295 assert!(json["details"].get("message").is_none());
4296 // Only rel_type belongs under details for this variant.
4297 assert_eq!(json["details"].as_object().unwrap().len(), 1);
4298 }
4299
4300 #[test]
4301 fn warning_hint_duplicate_relationship_envelope() {
4302 let w = WarningHint::DuplicateRelationship {
4303 rel_type: "USES".into(),
4304 from: EntityId("specs--a".into()),
4305 to: EntityId("specs--b".into()),
4306 };
4307 let json = to_envelope(&w);
4308 assert_eq!(json["code"], "DUPLICATE_RELATIONSHIP");
4309 assert!(json["message"].as_str().unwrap().contains("already exists"));
4310 assert_eq!(json["details"]["rel_type"], "USES");
4311 assert_eq!(json["details"]["from"], "specs--a");
4312 assert_eq!(json["details"]["to"], "specs--b");
4313 }
4314
4315 #[test]
4316 fn warning_hint_no_such_relationship_envelope() {
4317 let w = WarningHint::NoSuchRelationship {
4318 rel_type: "USES".into(),
4319 from: EntityId("specs--a".into()),
4320 to: EntityId("specs--b".into()),
4321 };
4322 let json = to_envelope(&w);
4323 assert_eq!(json["code"], "NO_SUCH_RELATIONSHIP");
4324 assert!(json["message"].as_str().unwrap().contains("does not exist"));
4325 assert_eq!(json["details"]["rel_type"], "USES");
4326 assert_eq!(json["details"]["from"], "specs--a");
4327 assert_eq!(json["details"]["to"], "specs--b");
4328 }
4329
4330 #[test]
4331 fn warning_hint_unknown_include_key_envelope() {
4332 let w = WarningHint::UnknownIncludeKey {
4333 key: "bogus".into(),
4334 allowed: vec!["orphans".into(), "stubs".into()],
4335 };
4336 let json = to_envelope(&w);
4337 assert_eq!(json["code"], "UNKNOWN_INCLUDE_KEY");
4338 assert!(json["message"].as_str().unwrap().contains("bogus"));
4339 assert_eq!(json["details"]["key"], "bogus");
4340 assert!(json["details"]["allowed"].is_array());
4341 }
4342
4343 #[test]
4344 fn warning_hint_limit_clamped_envelope() {
4345 let w = WarningHint::LimitClamped {
4346 requested: 1000,
4347 actual: 100,
4348 };
4349 let json = to_envelope(&w);
4350 assert_eq!(json["code"], "LIMIT_CLAMPED");
4351 assert!(json["message"].as_str().unwrap().contains("clamped"));
4352 assert_eq!(json["details"]["requested"].as_u64(), Some(1000));
4353 assert_eq!(json["details"]["actual"].as_u64(), Some(100));
4354 }
4355
4356 #[test]
4357 fn warning_hint_title_normalized_to_slug_noop_envelope() {
4358 let w = WarningHint::TitleNormalizedToSlugNoop {
4359 requested_title: "Hello World!".into(),
4360 current_slug: "hello-world".into(),
4361 };
4362 let json = to_envelope(&w);
4363 assert_eq!(json["code"], "TITLE_NORMALIZED_TO_SLUG_NOOP");
4364 assert!(
4365 json["message"]
4366 .as_str()
4367 .unwrap()
4368 .contains("no change written to disk")
4369 );
4370 assert_eq!(json["details"]["requested_title"], "Hello World!");
4371 assert_eq!(json["details"]["current_slug"], "hello-world");
4372 }
4373
4374 // Top-level envelope shape lock — every WarningHint emits exactly
4375 // three keys and nothing else. Protects against accidental field
4376 // additions at the envelope level.
4377 #[test]
4378 fn warning_hint_envelope_has_exactly_three_top_level_keys() {
4379 for w in &WarningHint::all_samples() {
4380 let json = to_envelope(w);
4381 let obj = json.as_object().expect("envelope is an object");
4382 assert_eq!(
4383 obj.len(),
4384 3,
4385 "{} must emit exactly 3 top-level keys; got {:?}",
4386 w.code(),
4387 obj.keys().collect::<Vec<_>>()
4388 );
4389 assert!(obj.contains_key("code"));
4390 assert!(obj.contains_key("message"));
4391 assert!(obj.contains_key("details"));
4392 }
4393 }
4394
4395 // Stability lock — `code()` values are a public wire contract. Every
4396 // variant must expose an UPPER_SNAKE_CASE identifier. Catches
4397 // accidental rename / case drift in a single test.
4398 #[test]
4399 fn warning_hint_code_values_are_upper_snake_case() {
4400 let re = regex::Regex::new(r"^[A-Z][A-Z0-9_]*$").unwrap();
4401 for w in &WarningHint::all_samples() {
4402 let code = w.code();
4403 assert!(
4404 re.is_match(code),
4405 "code() violates UPPER_SNAKE_CASE: {code}"
4406 );
4407 }
4408 }
4409
4410 // Envelope helper emits the same shape as WarningHint::serialize — one
4411 // constructor, two callers (warnings + MCP error path).
4412 #[test]
4413 fn envelope_shape_is_code_message_details() {
4414 let v = envelope("FOO_BAR", "hello", serde_json::json!({ "x": 1 }));
4415 assert_eq!(v["code"], "FOO_BAR");
4416 assert_eq!(v["message"], "hello");
4417 assert_eq!(v["details"]["x"], 1);
4418 assert_eq!(
4419 v.as_object().unwrap().len(),
4420 3,
4421 "envelope has exactly 3 top-level keys"
4422 );
4423 }
4424}
4425
4426#[cfg(test)]
4427mod write_id_doc_gloss_tests {
4428 /// The rustdoc guard, for the whole crate rather than one file.
4429 ///
4430 /// Two earlier versions of this check were too narrow and each let a
4431 /// real defect through. The first read only `ops/mod.rs`, so five
4432 /// copies of the gloss in `engine/outcomes.rs` — the base engine's
4433 /// public outcome types, on a crates.io-published crate, hence
4434 /// docs.rs — were invisible. The second was a phrase-exact banned
4435 /// list built for "Per-mem commit SHA", which "Per-mem commit
4436 /// identifier" walked straight past. A list of forbidden sentences
4437 /// is only ever as good as the sentences someone already wrote.
4438 ///
4439 /// So the rule is structural and positive instead. Every documented
4440 /// `write_id` field must say WHICH backend produces a commit and
4441 /// must say the value is not a cursor. Prose that calls the token a
4442 /// commit without qualification fails whatever words it uses,
4443 /// because it cannot satisfy the qualifier requirement.
4444 #[test]
4445 fn every_write_id_doc_qualifies_the_backend_and_denies_the_cursor() {
4446 fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
4447 let Ok(entries) = std::fs::read_dir(dir) else {
4448 return;
4449 };
4450 for e in entries.flatten() {
4451 let p = e.path();
4452 if p.is_dir() {
4453 walk(&p, out);
4454 } else if p.extension().is_some_and(|x| x == "rs") {
4455 out.push(p);
4456 }
4457 }
4458 }
4459 let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
4460 let mut files = Vec::new();
4461 walk(&src, &mut files);
4462 assert!(
4463 !files.is_empty(),
4464 "found no sources — check has gone vacuous"
4465 );
4466
4467 let mut documented = 0usize;
4468 let mut violations = Vec::new();
4469 for path in &files {
4470 let Ok(text) = std::fs::read_to_string(path) else {
4471 continue;
4472 };
4473 let lines: Vec<&str> = text.lines().collect();
4474 for (i, line) in lines.iter().enumerate() {
4475 let t = line.trim_start();
4476 if !(t.starts_with("pub write_id:") || t.starts_with("pub seed_write_id:")) {
4477 continue;
4478 }
4479 // Collect the contiguous doc block above the field,
4480 // skipping attributes like #[serde(default)].
4481 let mut block = Vec::new();
4482 let mut j = i;
4483 while j > 0 {
4484 j -= 1;
4485 let prev = lines[j].trim_start();
4486 if prev.starts_with("#[") {
4487 continue;
4488 }
4489 if prev.starts_with("///") {
4490 block.push(prev.trim_start_matches("///").trim());
4491 continue;
4492 }
4493 break;
4494 }
4495 if block.is_empty() {
4496 continue; // undocumented: nothing to gloss
4497 }
4498 documented += 1;
4499 block.reverse();
4500 let doc = block.join(" ");
4501 let lower = doc.to_lowercase();
4502 // Judge the DEFINING sentence, not every later mention.
4503 // "Empty on the no-op rename (no file change, no commit)"
4504 // is a true statement about a path, not a claim that the
4505 // token is a commit; only the summary sentence defines
4506 // the field, and it is what docs.rs renders as such.
4507 let definition = lower.split_once(". ").map(|(a, _)| a).unwrap_or(&lower);
4508 let claims_commit = definition.contains("commit") || definition.contains("sha");
4509 let names_backend = lower.contains("git-branch");
4510 let denies_cursor = lower.contains("not a change cursor")
4511 || lower.contains("never a change cursor")
4512 || lower.contains("not a cursor")
4513 || lower.contains("never a cursor");
4514 let inherits = lower.contains("see `updateresult::write_id`")
4515 || lower.contains("wire-equivalent to full's");
4516 if inherits && !claims_commit {
4517 continue; // documented by pointer at a doc this check governs
4518 }
4519 if claims_commit && !names_backend {
4520 violations.push(format!(
4521 "{}:{}: calls the token a commit without naming which backend produces one — {}",
4522 path.file_name().unwrap_or_default().to_string_lossy(),
4523 i + 1,
4524 doc
4525 ));
4526 } else if !denies_cursor && !inherits {
4527 violations.push(format!(
4528 "{}:{}: documents the token without stating it is not a change cursor — {}",
4529 path.file_name().unwrap_or_default().to_string_lossy(),
4530 i + 1,
4531 doc
4532 ));
4533 }
4534 }
4535 }
4536 assert!(
4537 documented >= 5,
4538 "expected the crate to document several write_id fields, saw {documented} — \
4539 this check has gone vacuous"
4540 );
4541 assert!(
4542 violations.is_empty(),
4543 "write_id docs that gloss the token as a git commit or omit the non-cursor statement:\n {}",
4544 violations.join("\n ")
4545 );
4546 }
4547
4548 /// The edge spelling in EMITTED JSON, not just in prose.
4549 ///
4550 /// Every guard before this one read documentation. None read the
4551 /// `json!` macros that build responses, which is how
4552 /// `render_relations_json` kept emitting the relation type under
4553 /// the bare key `"type"` through eight grades while
4554 /// `memstead entity --json` next to it emitted `rel_type` — two CLI
4555 /// commands, one concept, two spellings, on the same edge. Neither
4556 /// enumerator could see it either: one pattern wanted `"to"` beside
4557 /// `"type"`, and this shape pairs `"type"` with `"target"`.
4558 ///
4559 /// The rule is narrow on purpose: a line that writes a JSON key
4560 /// `"type"` and mentions `rel_type` is emitting a relation type
4561 /// under the retired name. An entity type or a content-block kind
4562 /// legitimately owns the word `type` and never mentions `rel_type`,
4563 /// so it does not match.
4564 #[test]
4565 fn no_emitted_json_spells_a_relation_type_as_bare_type() {
4566 fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
4567 let Ok(entries) = std::fs::read_dir(dir) else {
4568 return;
4569 };
4570 for e in entries.flatten() {
4571 let p = e.path();
4572 if p.is_dir() {
4573 walk(&p, out);
4574 } else if p.extension().is_some_and(|x| x == "rs") {
4575 out.push(p);
4576 }
4577 }
4578 }
4579 let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
4580 let mut roots = vec![base.join("src")];
4581 if let Some(ws) = base.parent().and_then(|p| p.parent()) {
4582 for sibling in ["crates/memstead-cli/src", "crates/memstead-mcp/src"] {
4583 let p = ws.join(sibling);
4584 if p.is_dir() {
4585 roots.push(p);
4586 }
4587 }
4588 if let Some(outer) = ws.parent() {
4589 let p = outer.join("ui-api/src");
4590 if p.is_dir() {
4591 roots.push(p);
4592 }
4593 }
4594 }
4595 let mut files = Vec::new();
4596 for r in &roots {
4597 walk(r, &mut files);
4598 }
4599 assert!(
4600 !files.is_empty(),
4601 "found no sources — check has gone vacuous"
4602 );
4603
4604 let mut violations = Vec::new();
4605 let mut saw_a_relation_emit = false;
4606 for path in &files {
4607 let Ok(text) = std::fs::read_to_string(path) else {
4608 continue;
4609 };
4610 let lines: Vec<&str> = text.lines().collect();
4611 for (i, line) in lines.iter().enumerate() {
4612 let t = line.trim_start();
4613 if t.starts_with("//") {
4614 continue; // prose is the other guards' business
4615 }
4616 if line.contains("rel_type") && line.contains('"') {
4617 saw_a_relation_emit = true;
4618 }
4619 // The serde form splits the two tokens across lines:
4620 // #[serde(rename = "type")]
4621 // rel_type: &'a str,
4622 // A same-line rule passed that in silence — a grader
4623 // proved it by reintroducing exactly this on
4624 // `EdgeTypeCount` and watching the check go green. So
4625 // look at a small window, not one line.
4626 let lo = i.saturating_sub(1);
4627 let hi = (i + 2).min(lines.len());
4628 let window = lines[lo..hi].join(" ");
4629 if window.contains("\"type\"") && window.contains("rel_type") {
4630 violations.push(format!(
4631 "{}:{}: {}",
4632 path.file_name().unwrap_or_default().to_string_lossy(),
4633 i + 1,
4634 t
4635 ));
4636 }
4637 }
4638 }
4639 assert!(
4640 saw_a_relation_emit,
4641 "no source mentions `rel_type` in a string context — check has gone vacuous"
4642 );
4643 assert!(
4644 violations.is_empty(),
4645 "emitted JSON spells a relation type as the retired bare `type`:\n {}",
4646 violations.join("\n ")
4647 );
4648 }
4649
4650 /// The edge spelling, across the same crate. The canonical
4651 /// `CreateArgs::relations` doc named both retired keys at once, on
4652 /// a field whose own type is `{target, rel_type}`. Neither
4653 /// enumerator matches that prose form, which is why this exists.
4654 #[test]
4655 fn no_doc_comment_spells_a_relation_entry_the_retired_way() {
4656 const RETIRED_EDGE_SHAPES: &[&str] = &[
4657 "to: EntityId, type:",
4658 "{ to, type }",
4659 "{to, type}",
4660 "{from, to, type}",
4661 "`from` / `type` / `to`",
4662 "(`from`/`to`/`type`)",
4663 ];
4664 fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
4665 let Ok(entries) = std::fs::read_dir(dir) else {
4666 return;
4667 };
4668 for e in entries.flatten() {
4669 let p = e.path();
4670 if p.is_dir() {
4671 walk(&p, out);
4672 } else if p.extension().is_some_and(|x| x == "rs") {
4673 out.push(p);
4674 }
4675 }
4676 }
4677 // Reach past this crate. Round five's finding was a ui-api
4678 // struct doc, and the guard installed in answer to it could not
4679 // see the file that produced it. The sibling crates and the two
4680 // private consumers all describe the same edge.
4681 let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
4682 let mut roots = vec![base.join("src")];
4683 let mut private_ui_api_present = false;
4684 let mut private_serve_present = false;
4685 if let Some(ws) = base.parent().and_then(|p| p.parent()) {
4686 for sibling in [
4687 "crates/memstead-mcp/src",
4688 "crates/memstead-cli/src",
4689 "crates/memstead-schema/src",
4690 ] {
4691 let p = ws.join(sibling);
4692 if p.is_dir() {
4693 roots.push(p);
4694 }
4695 }
4696 // ui-api and serve live beside the `public/` submodule.
4697 if let Some(outer) = ws.parent() {
4698 for private in ["ui-api/src", "serve/src"] {
4699 let p = outer.join(private);
4700 if p.is_dir() {
4701 roots.push(p);
4702 if private == "ui-api/src" {
4703 private_ui_api_present = true;
4704 } else {
4705 private_serve_present = true;
4706 }
4707 }
4708 }
4709 }
4710 }
4711 // Pin the widening itself. `>= 5` was too loose: `ui-api/src`
4712 // and `serve/src` could both silently drop out and this still
4713 // passed, so the round that widened the reach did not actually
4714 // fix it in place. Require every root that exists on disk.
4715 let expected = 4 + usize::from(private_ui_api_present) + usize::from(private_serve_present);
4716 assert_eq!(
4717 roots.len(),
4718 expected,
4719 "expected {expected} roots (three sibling crates plus the private consumers \
4720 present on disk), saw {} — the check has narrowed",
4721 roots.len()
4722 );
4723 let mut files = Vec::new();
4724 for r in &roots {
4725 walk(r, &mut files);
4726 }
4727 assert!(
4728 !files.is_empty(),
4729 "found no sources — check has gone vacuous"
4730 );
4731
4732 let mut violations = Vec::new();
4733 for path in &files {
4734 let Ok(text) = std::fs::read_to_string(path) else {
4735 continue;
4736 };
4737 for (i, line) in text.lines().enumerate() {
4738 let t = line.trim_start();
4739 if !t.starts_with("///") && !t.starts_with("//!") {
4740 continue;
4741 }
4742 for shape in RETIRED_EDGE_SHAPES {
4743 if line.contains(shape) {
4744 violations.push(format!(
4745 "{}:{}: {}",
4746 path.file_name().unwrap_or_default().to_string_lossy(),
4747 i + 1,
4748 t
4749 ));
4750 }
4751 }
4752 }
4753 }
4754 assert!(
4755 violations.is_empty(),
4756 "doc comments still spell a relation entry the retired way:\n {}",
4757 violations.join("\n ")
4758 );
4759 }
4760}