Skip to main content

memstead_base/engine/
outcomes.rs

1//! Argument/outcome shapes for the mutation entrypoints
2//! (`Engine::create_entity`, `update_entity`, `delete_entity`,
3//! `relate_entity`, `rename_entity`). The MCP wire envelopes and CLI
4//! command output formatters branch on these shapes; their field
5//! layouts are part of the engine's public surface.
6
7use indexmap::IndexMap;
8
9use crate::entity::EntityId;
10use crate::ops::{IncomingRef, ModifiedMetadata, ModifiedSections, WarningHint};
11
12/// Arguments for [`Engine::create_entity`].
13///
14/// Carries the target mem (routes to the right mount), the entity
15/// shape (title, type, sections, metadata), and nothing else. Caller
16/// identity (actor, client, note) goes through the standalone
17/// arguments so the same MCP-tool / CLI-direct shape works.
18#[derive(Debug, Clone)]
19pub struct CreateEntityArgs {
20    pub mem: String,
21    pub title: String,
22    pub entity_type: String,
23    pub sections: IndexMap<String, String>,
24    pub metadata: IndexMap<String, String>,
25    /// Inline relationships to wire as outgoing edges from the new
26    /// entity. Each entry's `to` may name an absent target — the
27    /// engine auto-stubs it (mirrors full's create + stub
28    /// creation on relate). Open-mode admissions surface as
29    /// [`WarningHint::UndeclaredRelationshipOpen`] in the outcome's
30    /// `warnings`. Empty default — callers omit when no inline
31    /// edges are needed.
32    pub relations: Vec<crate::ops::RelateArg>,
33    /// Permissive `anchors[]` provenance records to attach to the new
34    /// entity — validated ([`crate::anchor::AnchorInput::validate`]) and,
35    /// when non-empty, written into the mem-branch anchors sidecar in the
36    /// SAME commit as the entity so the two land atomically. Empty (the
37    /// default) writes no sidecar and leaves behaviour byte-identical to a
38    /// pre-anchor create. A malformed element refuses the whole create with
39    /// [`EngineError::InvalidAnchor`] (`INVALID_ANCHOR`) — the entity is not
40    /// written. Not folded into `_hash` (sidecar lives under `.memstead/`).
41    pub anchors: Vec<crate::anchor::AnchorInput>,
42    /// When `true`, validate and compute the prospective hash but
43    /// do not write to disk, mutate the store, create edges, or
44    /// commit. Outcome carries `content_hash` = the prospective
45    /// hash and `write_id` empty — wire-equivalent to full's
46    /// `CreateArgs.dry_run` semantics.
47    pub dry_run: bool,
48}
49
50/// Successful outcome of [`Engine::create_entity`].
51#[derive(Debug, Clone, serde::Serialize)]
52pub struct CreateEntityOutcome {
53    pub id: EntityId,
54    /// Echoed from the request — full's `CreateResult.title` carries
55    /// the same value so wire callers don't need to derive it from
56    /// the id.
57    pub title: String,
58    /// Echoed from the request — full's `CreateResult.mem`. The
59    /// `EntityId.mem()` accessor projects the same value, but
60    /// surfacing it explicitly mirrors full's wire shape.
61    pub mem: String,
62    /// Mem-relative path of the freshly-written `.md` file.
63    pub file_path: String,
64    /// SHA-256 of the canonical bytes. Round-trips as
65    /// `expected_hash` for the next mutation against this entity.
66    /// The wire
67    /// key is `_hash` to match `memstead_entity`'s read envelope and
68    /// the underscore-prefix convention for engine metadata. Pre-
69    /// fix mutation responses serialised this as `content_hash`,
70    /// forcing agents to rename the field when piping the value
71    /// into a follow-up call.
72    #[serde(rename = "_hash")]
73    pub content_hash: String,
74    /// The identity the mem's backend minted for this write — a commit
75    /// SHA on a git-branch mem, an opaque synthetic token on a folder or
76    /// in-memory mem. An identity, never a change cursor. Wire-equivalent to
77    /// full's `CreateResult.write_id`.
78    pub write_id: String,
79    /// ISO date string from the parsed entity's `created_date`
80    /// metadata. Today's date when the schema's auto-stamp filled
81    /// it in; the existing value when re-materialising a stub with
82    /// `init_timestamp` semantics. Wire-equivalent to full's
83    /// `CreateResult.created_date`.
84    pub created_date: String,
85    /// Typed Tier-2 warnings — today
86    /// [`WarningHint::MissingRequiredSection`] for empty / absent
87    /// required sections. Populated even when the create succeeded
88    /// so callers see the same self-correction prompts the existing
89    /// engines emit. Wire-equivalent to full's
90    /// `CreateResult.warnings`.
91    pub warnings: Vec<WarningHint>,
92    /// Type-level `write_rules` keyed by `entity_type` — the
93    /// MISSING_REQUIRED_SECTION / MISSING_REQUIRED_FIELD warnings
94    /// reference this top-level map via their `entity_type` field
95    /// rather than each carrying the (identical, type-axis) array.
96    /// Empty when no such warnings fire; stable empty shape ships
97    /// on the wire so consumers don't branch on field presence
98    /// (F9). Sorted by key for deterministic output.
99    pub type_guidance: std::collections::BTreeMap<String, Vec<String>>,
100    /// Number of incoming edges adopted from a pre-existing stub
101    /// at this id. `None` when no stub adoption happened (no
102    /// pre-existing entity, or a real entity at the id — but that
103    /// path errors with `AlreadyExists` before this field is
104    /// computed). Wire-equivalent to full's
105    /// `CreateResult.incoming_count`.
106    pub incoming_count: Option<usize>,
107    /// Incoming edges present at this id post-create — populated
108    /// from `store.incoming(id)` after the parse + upsert. Empty
109    /// when no pre-existing stub had referrers. Wire-equivalent to
110    /// full's `CreateResult.incoming`.
111    pub incoming: Vec<IncomingRef>,
112    /// Batched relation declarations from the request's existing
113    /// `relations[]` parameter. Mirrors
114    /// [`UpdateEntityOutcome::relations_declared`] so the agent sees
115    /// one wire shape across `memstead_create` and `memstead_update`. Empty
116    /// `[]` when no relations were declared. `target_was_stubbed`
117    /// reports the same flag the existing relate auto-stub path
118    /// emits via `WarningHint::InlineWikiLinkAutoStubbed`.
119    #[serde(default, skip_serializing_if = "Vec::is_empty")]
120    pub relations_declared: Vec<RelationDeclared>,
121}
122
123/// Arguments for [`Engine::update_entity`].
124#[derive(Debug, Clone)]
125pub struct UpdateEntityArgs {
126    pub id: EntityId,
127    /// Optimistic locking. `None` skips the check.
128    pub expected_hash: Option<String>,
129    /// Section keys whose body should be replaced wholesale. Empty
130    /// values overwrite with empty content.
131    pub sections: IndexMap<String, String>,
132    /// Section keys whose body should be appended to. Existing body
133    /// gets a `\n` separator before the append; empty/absent body
134    /// is replaced wholesale with the append value (parity with
135    /// full's append-on-empty behaviour). The same key may not
136    /// appear in both `sections` and `append_sections`; conflict
137    /// is rejected with [`EngineError::ConflictingSectionModes`].
138    pub append_sections: IndexMap<String, String>,
139    /// Section keys whose body should be patched via find-and-
140    /// replace. Each value is a [`crate::ops::PatchArg`] with
141    /// `old`, `new`, and `all` (replace every occurrence vs first
142    /// only). Errors with [`EngineError::PatchSectionEmpty`] when
143    /// the section is absent and [`EngineError::PatchOldNotFound`]
144    /// when `old` doesn't appear. Mutually exclusive with the
145    /// other two section modes for the same key.
146    pub patch_sections: IndexMap<String, crate::ops::PatchArg>,
147    /// Metadata fields to set or replace. Values land as
148    /// `MetadataValue::String` for V1.
149    pub metadata: IndexMap<String, String>,
150    /// Metadata field keys to unset. Silently no-ops on absent keys.
151    pub metadata_unset: Vec<String>,
152    /// When `true`, validate and compute the prospective hash but
153    /// do not write to disk, mutate the store, or commit. Outcome
154    /// carries `content_hash` = the unchanged on-disk hash (so the
155    /// caller can use it as `expected_hash` on the follow-up real
156    /// call) and `prospective_hash` = the hash the entity would
157    /// have after the proposed write. Wire-equivalent to full's
158    /// `UpdateArgs.dry_run`. Optimistic-lock check is skipped on
159    /// the dry_run path so an agent can preview a change without
160    /// holding a fresh hash — designated stale-hash recovery path.
161    pub dry_run: bool,
162    /// Atomic batched relation declarations applied before the
163    /// section/metadata changes land. Each entry is validated like
164    /// any individual `memstead_relate` call (schema-shape, cross-mem
165    /// policy, target-id grammar), appended to the entity's
166    /// `relationships` list, and — for absent Write-target peers —
167    /// auto-stubbed in the target's mem. The strict
168    /// wiki-link/relation validator then runs against the
169    /// post-mutation state with the freshly-declared relations
170    /// already in place, so a body wiki-link added in the same
171    /// `memstead_update` call passes the gate without a separate
172    /// `memstead_relate` round-trip. Empty default — omit when no
173    /// batched declarations are needed.
174    pub declare_relations: Vec<crate::ops::RelateArg>,
175    /// Permissive `anchors[]` provenance records to attach to this entity
176    /// — validated ([`crate::anchor::AnchorInput::validate`]) and, when
177    /// non-empty, **merged** into the entity's row in the mem-branch
178    /// anchors sidecar in the SAME commit as the update so entity +
179    /// anchors land atomically: an incoming anchor replaces the existing
180    /// anchor with the same `(artifact, grain, class)` triple and appends
181    /// otherwise — writing never removes an anchor this call did not name
182    /// in [`Self::anchors_unset`]. Empty (the default) merges nothing and
183    /// leaves the stored set untouched. A malformed element refuses the
184    /// whole update with [`EngineError::InvalidAnchor`] (`INVALID_ANCHOR`)
185    /// — nothing is written. Not folded into `_hash` (sidecar lives under
186    /// `.memstead/`).
187    pub anchors: Vec<crate::anchor::AnchorInput>,
188    /// Explicit anchor removals, applied **before** the [`Self::anchors`]
189    /// merge in the same mutation (mirroring the `metadata_unset` /
190    /// `relations_unset` conventions). Each selector names an `artifact`
191    /// and may narrow by `grain` and/or `class`; a bare artifact removes
192    /// every anchor on it. Unsetting an anchor that does not exist is a
193    /// no-op, not an error — removal is idempotent. A malformed selector
194    /// refuses the whole update with [`EngineError::InvalidAnchor`].
195    pub anchors_unset: Vec<crate::anchor::AnchorUnsetInput>,
196    /// Repair-shaped relation removals (`{ rel_type, target }`),
197    /// applied atomically within this update. Accepted only when the
198    /// entity currently FAILS the conformance check (against the
199    /// effective schema) — a conformant entity refuses with
200    /// `REPAIR_NOT_NEEDED` and stays unmodified; `memstead_relate(remove)`
201    /// is the everyday detach path. Absent pairs are silent no-ops
202    /// (symmetric with `metadata_unset`). The strict-write
203    /// post-condition is unchanged: the post-repair entity must be
204    /// integral or the whole update refuses with the relevant
205    /// write-time code.
206    pub relations_unset: Vec<crate::ops::RelationUnsetArg>,
207}
208
209impl UpdateEntityArgs {
210    /// Whether this payload names anything that can move the entity's content
211    /// hash. Anchors are deliberately absent from the list: the sidecar lives
212    /// outside the hash.
213    ///
214    /// WHY it lives here rather than on each surface: MCP (both flavours), the
215    /// CLI and the HTTP layer all gate an update on a compare-and-swap token,
216    /// and on an anchors-only payload that token compares a value the write
217    /// provably cannot move. Exempting the shape is right; exempting it four
218    /// times, once per surface, is how surfaces come to disagree about whether
219    /// a write is safe, which is the drift class this campaign closes. One
220    /// predicate, one answer. The engine core does not consult it: it checks
221    /// the token only when a caller supplies one, and always has.
222    ///
223    /// A payload naming NOTHING changes no content either, and must fall
224    /// through to the empty-update refusal rather than be told it is missing a
225    /// token: that refusal names the recognised keys, which is what a caller
226    /// who typo'd a mutation key actually needs. A first version asked
227    /// "is this anchors-only" instead, and turned every empty payload into a
228    /// hash complaint; the plan's criterion 5 caught it.
229    pub fn changes_content(&self) -> bool {
230        !self.sections.is_empty()
231            || !self.append_sections.is_empty()
232            || !self.patch_sections.is_empty()
233            || !self.metadata.is_empty()
234            || !self.metadata_unset.is_empty()
235            || !self.declare_relations.is_empty()
236            || !self.relations_unset.is_empty()
237    }
238}
239
240/// Successful outcome of [`Engine::update_entity`].
241#[derive(Debug, Clone, serde::Serialize)]
242pub struct UpdateEntityOutcome {
243    pub id: EntityId,
244    /// Title from the parsed entity after the write — wire-equivalent
245    /// to full's `UpdateResult.title`. Reflects post-write state in
246    /// case a future update path touches the title (today the update
247    /// surface doesn't, but reading from the parsed entity rather
248    /// than echoing `args` keeps the field correct as the surface
249    /// evolves).
250    pub title: String,
251    pub file_path: String,
252    /// Wire key `_hash`.
253    #[serde(rename = "_hash")]
254    pub content_hash: String,
255    /// The identity the mem's backend minted for this write — a commit
256    /// SHA on a git-branch mem, an opaque synthetic token on a folder or
257    /// in-memory mem. An identity, never a change cursor. Wire-equivalent to
258    /// full's `UpdateResult.write_id`.
259    pub write_id: String,
260    /// ISO date string from the parsed entity's `modified_date`
261    /// metadata. Populated when the schema auto-stamps the field
262    /// on update; empty when the schema doesn't declare it. Wire-
263    /// equivalent to full's `UpdateResult.modified_date`.
264    pub modified_date: String,
265    /// Section-level mutations grouped by mode (replaced / appended /
266    /// patched). Wire-equivalent to full's
267    /// `UpdateResult.modified_sections`. Empty inner vecs serde-omit
268    /// per `ModifiedSections`'s field attributes; the outer key is
269    /// always present.
270    pub modified_sections: ModifiedSections,
271    /// Metadata-level mutations grouped by direction (set / unset).
272    /// Wire-equivalent to full's `UpdateResult.modified_metadata`.
273    /// Same empty-vec-omit convention as `modified_sections`.
274    pub modified_metadata: ModifiedMetadata,
275    /// `Some(hash)` on the dry_run path — the hash the entity
276    /// would have after the proposed write. `None` on real
277    /// updates (the post-write hash is in `content_hash`).
278    /// Wire-equivalent to full's `UpdateResult.prospective_hash`.
279    pub prospective_hash: Option<String>,
280    /// Stub entities whose last incoming edge was severed by this
281    /// update — when a body wiki-link was removed, the alias-resync
282    /// drops the backing pointer-rel-type edge, and if that was the
283    /// stub target's last referrer the stub is GC'd here. Empty on
284    /// updates that didn't orphan a stub (including section edits with
285    /// no wiki-link change, dry-run, and no-op). Shares the field name
286    /// and always-present shape with
287    /// [`DeleteEntityOutcome::orphan_stubs_removed`] and
288    /// [`RelateEntityOutcome::orphan_stubs_removed`] so MCP / CLI
289    /// consumers branch uniformly across the three GC paths.
290    pub orphan_stubs_removed: Vec<EntityId>,
291    /// Typed non-fatal issues — empty on the unified path today
292    /// (update doesn't surface InlineWikiLinkAutoStubbed or
293    /// MissingRequiredOutgoing yet). Wire-equivalent to full's
294    /// `UpdateResult.warnings`; the field shape parity matters for
295    /// the upcoming handler migration so callers see the same
296    /// `warnings: []` envelope position across flavours.
297    pub warnings: Vec<WarningHint>,
298    /// Batched relation declarations applied by this call (per the
299    /// optional `declare_relations` request param). Empty `[]`
300    /// when no batched declarations were requested; populated with
301    /// one entry per declared relation otherwise. `target_was_stubbed`
302    /// flags which targets were absent at call time and got
303    /// auto-stubbed; agents use this to skip a follow-up
304    /// `memstead_entity` round-trip on the stubbed target.
305    #[serde(default, skip_serializing_if = "Vec::is_empty")]
306    pub relations_declared: Vec<RelationDeclared>,
307}
308
309/// One batched relation declaration applied by a mutation call.
310/// Echoed in [`UpdateEntityOutcome::relations_declared`] and
311/// [`CreateEntityOutcome::relations_declared`] so agents see, in the
312/// same response, what landed and which targets had to be stubbed.
313#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
314pub struct RelationDeclared {
315    pub rel_type: String,
316    pub target: EntityId,
317    /// `true` when the target was absent at call time and the
318    /// engine materialised a stub for it (subject to the same
319    /// rules as `memstead_relate`'s auto-stub mechanic).
320    pub target_was_stubbed: bool,
321}
322
323/// Arguments for [`Engine::delete_entity`].
324///
325/// No `force` flag — delete is binary. The engine refuses on any
326/// Write-Mem incoming reference (typed `HAS_INCOMING_REFS`); when
327/// only ReadOnly-mount referrers remain, the entity is demoted to a
328/// stub in-memory and the delete proceeds, surfaced via a typed
329/// `RESIDUAL_STUB_FOR_READONLY_REFERRERS` warning on the outcome.
330#[derive(Debug, Clone)]
331pub struct DeleteEntityArgs {
332    pub id: EntityId,
333    /// Optimistic locking. `None` skips the check.
334    pub expected_hash: Option<String>,
335}
336
337/// Successful outcome of [`Engine::delete_entity`].
338#[derive(Debug, Clone, serde::Serialize)]
339pub struct DeleteEntityOutcome {
340    pub id: EntityId,
341    pub file_path: String,
342    /// Ids of entities that referenced the deleted entity (only
343    /// populated on the residual-stub-demotion path — the surviving
344    /// ReadOnly-mount referrers are listed here for diagnostic
345    /// continuity with the warning payload).
346    pub removed_incoming: Vec<String>,
347    /// Total edges removed across incoming + outgoing — full
348    /// `DeleteResult.relations_removed`. Counted from the store
349    /// pre-delete; both directions sum into one number for callers
350    /// that need a single "how much did this delete cascade" signal.
351    pub relations_removed: usize,
352    /// The identity the mem's backend minted for this write — a commit
353    /// SHA on a git-branch mem, an opaque synthetic token on a folder or
354    /// in-memory mem. An identity, never a change cursor. Wire-equivalent to
355    /// full's `DeleteResult.write_id`.
356    pub write_id: String,
357    /// Stub entities that became orphaned by this delete (their last
358    /// incoming edge disappeared with this entity) and were
359    /// garbage-collected. Empty on deletes that didn't sever a
360    /// stub's last referrer. Wire-equivalent to full's
361    /// `DeleteResult.orphan_stubs_removed`.
362    pub orphan_stubs_removed: Vec<EntityId>,
363    /// Typed non-fatal issues — populated on the residual-stub
364    /// demotion path with a `RESIDUAL_STUB_FOR_READONLY_REFERRERS`
365    /// warning naming the surviving ReadOnly-mount referrers. Empty
366    /// on the clean-removal path.
367    pub warnings: Vec<WarningHint>,
368}
369
370/// Arguments for [`Engine::relate_entity`].
371#[derive(Debug, Clone)]
372pub struct RelateEntityArgs {
373    pub source: EntityId,
374    /// Optimistic locking on the source. `None` skips the check.
375    pub expected_hash: Option<String>,
376    pub rel_type: String,
377    pub target: EntityId,
378    /// `false` (default) appends. `true` removes the matching pair.
379    pub remove: bool,
380    /// Optional per-edge description applied on the add path.
381    /// Validated against the rel-type's `per_edge_description`
382    /// posture at call time — `forbidden` rejects `Some`; `required`
383    /// rejects `None`. Empty / whitespace-only strings normalise to
384    /// `None` before validation. Ignored on the remove path (`None`
385    /// keeps the existing behaviour intact).
386    pub description: Option<String>,
387    /// Rehearsal mode (agent-trust plan 07): run the FULL validation
388    /// stage — identical refusals, identical warnings (including the
389    /// would-be `AUTO_STUB_CREATED`) — then stop before any write.
390    /// The response carries the marker form: empty `write_id` with
391    /// `_hash` set to the PROSPECTIVE post-write hash. Nothing is
392    /// staged, committed, or stubbed.
393    pub dry_run: bool,
394}
395
396/// What a relate call did to the source's relationships.
397#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
398#[serde(rename_all = "snake_case")]
399pub enum RelateAction {
400    Added,
401    Removed,
402    NoOpAlreadyPresent,
403    NoOpAbsent,
404}
405
406/// Successful outcome of [`Engine::relate_entity`].
407#[derive(Debug, Clone, serde::Serialize)]
408pub struct RelateEntityOutcome {
409    pub from: EntityId,
410    pub to: EntityId,
411    pub rel_type: String,
412    pub action: RelateAction,
413    /// Source entity's content hash after the call. Unchanged on
414    /// no-op paths so callers can chain follow-ups without
415    /// refetching. Wire key `_hash`.
416    #[serde(rename = "_hash")]
417    pub content_hash: String,
418    /// The identity the mem's backend minted for this write — a commit
419    /// SHA on a git-branch mem, an opaque synthetic token on a folder or
420    /// in-memory mem. An identity, never a change cursor. Empty on the no-op
421    /// paths ([`RelateAction::NoOpAlreadyPresent`],
422    /// [`RelateAction::NoOpAbsent`]) — those branches skip the disk
423    /// write so no commit happens. Wire-equivalent to the full
424    /// `RelateResult.write_id`.
425    pub write_id: String,
426    /// Edge provenance label — always `"explicit"` for relate-call
427    /// outcomes. Wire-equivalent to full's `RelateResult.source` field;
428    /// reserved for future inline-link-derived edge surfacing.
429    pub source: String,
430    /// Typed non-fatal issues — open-mode schema admissions
431    /// ([`WarningHint::UndeclaredRelationshipOpen`]), duplicate-add
432    /// no-ops ([`WarningHint::DuplicateRelationship`]),
433    /// remove-nonexistent no-ops ([`WarningHint::NoSuchRelationship`]),
434    /// and auto-stubbed targets
435    /// ([`WarningHint::AutoStubCreated`]). Pre-Item-03 the auto-stub
436    /// case rode through a deprecated top-level
437    /// `stub_warning: Option<String>` field that didn't follow the
438    /// `warnings[]` shape — agents iterating diagnostics silently
439    /// skipped it; the field has been retired in favour of the
440    /// uniform warning vocabulary. Empty on the strict-add and
441    /// strict-remove happy paths.
442    pub warnings: Vec<WarningHint>,
443    /// Stub entities whose last incoming edge was severed by a
444    /// `remove=true` call and that were garbage-collected as orphans.
445    /// Empty on the add path and on remove paths that didn't strip
446    /// the last referrer. Wire-equivalent to
447    /// [`DeleteEntityOutcome::orphan_stubs_removed`]; both surfaces
448    /// share the same field name so MCP / CLI consumers can branch
449    /// uniformly (F7).
450    pub orphan_stubs_removed: Vec<EntityId>,
451}
452
453/// Arguments for [`Engine::rename_entity`].
454#[derive(Debug, Clone)]
455pub struct RenameEntityArgs {
456    pub id: EntityId,
457    /// Optimistic locking. `None` skips the check.
458    pub expected_hash: Option<String>,
459    pub new_title: String,
460}
461
462/// Successful outcome of [`Engine::rename_entity`].
463#[derive(Debug, Clone, serde::Serialize)]
464pub struct RenameEntityOutcome {
465    pub old_id: EntityId,
466    pub new_id: EntityId,
467    /// Mem-relative path of the renamed entity before the rewrite.
468    /// Wire-equivalent to full's `RenameResult.old_path`.
469    pub old_path: String,
470    /// Mem-relative path of the renamed entity after the rewrite.
471    /// Wire-equivalent to full's `RenameResult.new_path`.
472    pub new_path: String,
473    /// Wire key `_hash`.
474    #[serde(rename = "_hash")]
475    pub content_hash: String,
476    /// The identity the mem's backend minted for this write — a commit
477    /// SHA on a git-branch mem, an opaque synthetic token on a folder or
478    /// in-memory mem. An identity, never a change cursor. Empty on the
479    /// slug-noop short-circuit (no disk write happened).
480    /// Wire-equivalent to full's `RenameResult.write_id`.
481    pub write_id: String,
482    /// Typed non-fatal issues. The slug-noop short-circuit
483    /// ([`WarningHint::TitleNormalizedToSlugNoop`]) surfaces here
484    /// when a requested title normalises to the existing slug — the
485    /// op stays a silent no-op on disk, but the warning tells
486    /// autonomous skills not to trust `old_id == new_id` as
487    /// "cosmetic rewrite landed". Empty on the real-rename happy
488    /// path. Wire-equivalent to full's `RenameResult.warnings`.
489    pub warnings: Vec<WarningHint>,
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495
496    #[test]
497    fn outcome_types_serialize_to_json() {
498        // Lock the Serialize derives: every
499        // outcome type round-trips through `serde_json::to_string`
500        // without panicking. The wire shape's specific field names
501        // are exercised end-to-end via the MCP handlers; this test
502        // is the structural lock.
503        let create = CreateEntityOutcome {
504            id: EntityId("v--e".to_string()),
505            title: "t".to_string(),
506            mem: "v".to_string(),
507            file_path: "v/e.md".to_string(),
508            content_hash: "h".to_string(),
509            write_id: "sha".to_string(),
510            created_date: "2026-05-11".to_string(),
511            warnings: Vec::new(),
512            type_guidance: std::collections::BTreeMap::new(),
513            incoming_count: None,
514            incoming: Vec::new(),
515            relations_declared: Vec::new(),
516        };
517        assert!(serde_json::to_string(&create).is_ok());
518
519        let update = UpdateEntityOutcome {
520            id: EntityId("v--e".to_string()),
521            title: "t".to_string(),
522            file_path: "v/e.md".to_string(),
523            content_hash: "h".to_string(),
524            write_id: "sha".to_string(),
525            modified_date: "2026-05-11".to_string(),
526            modified_sections: ModifiedSections::default(),
527            modified_metadata: ModifiedMetadata::default(),
528            prospective_hash: None,
529            orphan_stubs_removed: Vec::new(),
530            warnings: Vec::new(),
531            relations_declared: Vec::new(),
532        };
533        assert!(serde_json::to_string(&update).is_ok());
534
535        let delete = DeleteEntityOutcome {
536            id: EntityId("v--e".to_string()),
537            file_path: "v/e.md".to_string(),
538            removed_incoming: Vec::new(),
539            write_id: "sha".to_string(),
540            relations_removed: 0,
541            orphan_stubs_removed: Vec::new(),
542            warnings: Vec::new(),
543        };
544        assert!(serde_json::to_string(&delete).is_ok());
545
546        let relate = RelateEntityOutcome {
547            from: EntityId("v--a".to_string()),
548            to: EntityId("v--b".to_string()),
549            rel_type: "PART_OF".to_string(),
550            action: RelateAction::Added,
551            content_hash: "h".to_string(),
552            write_id: "sha".to_string(),
553            source: "explicit".to_string(),
554            warnings: Vec::new(),
555            orphan_stubs_removed: Vec::new(),
556        };
557        assert!(serde_json::to_string(&relate).is_ok());
558
559        let rename = RenameEntityOutcome {
560            old_id: EntityId("v--a".to_string()),
561            new_id: EntityId("v--b".to_string()),
562            old_path: "v/a.md".to_string(),
563            new_path: "v/b.md".to_string(),
564            content_hash: "h".to_string(),
565            write_id: "sha".to_string(),
566            warnings: Vec::new(),
567        };
568        let rename_json = serde_json::to_string(&rename).unwrap();
569        // Field names match full's RenameResult wire shape directly.
570        assert!(
571            rename_json.contains("\"old_path\""),
572            "RenameEntityOutcome must serialize old_path: {rename_json}",
573        );
574        assert!(
575            rename_json.contains("\"new_path\""),
576            "RenameEntityOutcome must serialize new_path: {rename_json}",
577        );
578    }
579}
580
581/// Outcome discriminator for [`Engine::set_mem_schema`]. The agent
582/// branches on this — never on which response fields are populated
583/// (stable additive shape, no response-shape polymorphism).
584#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
585#[serde(rename_all = "snake_case")]
586pub enum SetSchemaResult {
587    /// Requested schema == current pin; no state change.
588    Noop,
589    /// Mem was (or became) integral against the target — the pin
590    /// now IS the target and any migration state is cleared.
591    Switched,
592    /// Mem was not integral against the target; dual-pin state
593    /// entered, `findings` carries the non-integral entities.
594    MigrationStarted,
595    /// Re-issued with the same in-flight target while still not
596    /// integral; `findings` carries the *remaining* non-integral
597    /// entities.
598    MigrationPending,
599}
600
601/// Stable response shape of [`Engine::set_mem_schema`] — all five
602/// fields are always present, populated per outcome.
603#[derive(Debug, Clone, serde::Serialize)]
604pub struct SetSchemaOutcome {
605    pub mem: String,
606    /// The settled pin after this call (`<name>@<version>`).
607    pub schema_pin: String,
608    /// In-flight target while a migration is in progress, else `None`.
609    pub migration_target: Option<String>,
610    pub outcome: SetSchemaResult,
611    /// Integrity-linter findings (`{ id, axis, code, detail }`) for
612    /// the entities not yet integral against the target; empty unless
613    /// a migration is in progress.
614    pub findings: Vec<crate::ops::integrity::IntegrityFinding>,
615}