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 /// 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/// What a content-changing mutation (update, delete, rename, retype, batch
124/// update) states about the entity's hash.
125///
126/// The engine, not a surface, decides what a missing statement means: it
127/// refuses it with `EXPECTED_HASH_REQUIRED` for a real entity. An omission
128/// that silently disabled the compare is how the surfaces came to differ
129/// (three codes for one refusal, and an MCP delete that skipped the compare
130/// for any entity), so the unguarded write has its own named variant
131/// instead of riding on an absent value.
132#[derive(Debug, Clone, PartialEq, Eq, Default)]
133pub enum ExpectedHash {
134 /// The caller states nothing. Refused for a real entity; a stub, which
135 /// has no content to protect, and the two exempt shapes (an update that
136 /// changes no content, a dry run) pass.
137 #[default]
138 Missing,
139 /// The hash the caller read from storage. Compared under the mem's
140 /// write lock; a mismatch refuses `HASH_MISMATCH` with the current hash.
141 Current(String),
142 /// The engine skips the compare. For internal callers only: no tool
143 /// parameter and no command-line flag maps to it, and every use names
144 /// its reason as the variant of [`HashOverride`].
145 Override(HashOverride),
146}
147
148/// Why an internal caller may write without a compare.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub enum HashOverride {
151 /// A proposal merge writes from a recorded common ancestor under its
152 /// own lock: it has already compared the target against that ancestor,
153 /// which is a stronger statement than a hash read a moment earlier.
154 ProposalMerge,
155}
156
157impl ExpectedHash {
158 /// The statement a surface token makes: a non-empty token is the hash
159 /// the caller holds; no token and an empty one both state nothing
160 /// (`Missing`). No content hash is empty, so an empty token cannot be
161 /// a hash read from storage, and every surface reads it alike: a stub
162 /// (whose `_hash` is empty) passes, a real entity refuses
163 /// `EXPECTED_HASH_REQUIRED`.
164 pub fn from_token(token: Option<String>) -> Self {
165 match token {
166 Some(h) if !h.is_empty() => Self::Current(h),
167 _ => Self::Missing,
168 }
169 }
170
171 /// The hash the caller holds, when it states one.
172 pub fn as_current(&self) -> Option<&str> {
173 match self {
174 Self::Current(h) => Some(h),
175 _ => None,
176 }
177 }
178
179 pub fn is_missing(&self) -> bool {
180 matches!(self, Self::Missing)
181 }
182
183 /// The one compare every content-changing verb runs, under its lock,
184 /// after its existence and stub gates. The two exemptions stay apart
185 /// because they waive different things: `required: false` (an update
186 /// that changes no content) waives only the requirement, so a hash the
187 /// caller does state is still compared; `compare: false` (a dry run, the
188 /// stale-hash recovery path) waives the compare and with it the
189 /// requirement, because nothing is written.
190 pub(crate) fn check(
191 &self,
192 id: &EntityId,
193 entity: &crate::entity::Entity,
194 required: bool,
195 compare: bool,
196 ) -> Result<(), super::EngineError> {
197 if !compare {
198 return Ok(());
199 }
200 match self {
201 Self::Override(_) => Ok(()),
202 Self::Missing if entity.stub || !required => Ok(()),
203 Self::Missing => Err(super::EngineError::ExpectedHashRequired { id: id.to_string() }),
204 Self::Current(expected) if entity.content_hash == *expected => Ok(()),
205 Self::Current(_) => Err(super::EngineError::HashMismatch {
206 id: id.to_string(),
207 current: entity.content_hash.clone(),
208 is_stub: entity.stub,
209 }),
210 }
211 }
212}
213
214/// Arguments for [`Engine::update_entity`].
215#[derive(Debug, Clone)]
216pub struct UpdateEntityArgs {
217 pub id: EntityId,
218 /// Optimistic locking; see [`ExpectedHash`]. Not required (and not
219 /// compared) on a dry run or on an update that changes no content.
220 pub expected_hash: ExpectedHash,
221 /// Section keys whose body should be replaced wholesale. Empty
222 /// values overwrite with empty content.
223 pub sections: IndexMap<String, String>,
224 /// Section keys whose body should be appended to. Existing body
225 /// gets a `\n` separator before the append; empty/absent body
226 /// is replaced wholesale with the append value (parity with
227 /// full's append-on-empty behaviour). The same key may not
228 /// appear in both `sections` and `append_sections`; conflict
229 /// is rejected with [`EngineError::ConflictingSectionModes`].
230 pub append_sections: IndexMap<String, String>,
231 /// Section keys whose body should be patched via find-and-
232 /// replace. Each value is a LIST of [`crate::ops::PatchArg`]
233 /// (`old`, `new`, `all`), applied in order against the section's
234 /// evolving body — batched edits to one section land in one call
235 /// instead of one call per patch. Errors with
236 /// [`EngineError::PatchSectionEmpty`] when the section is absent
237 /// and [`EngineError::PatchOldNotFound`] when an `old` doesn't
238 /// appear at its turn. Mutually exclusive with the other section
239 /// modes for the same key.
240 pub patch_sections: IndexMap<String, Vec<crate::ops::PatchArg>>,
241 /// Section keys to REMOVE from the entity — heading and body both.
242 /// The close gesture for a declared-but-empty heading with nothing
243 /// to receive (the shape a discovery build leaves behind), and the
244 /// repair for a legacy undeclared heading. Silently no-ops on an
245 /// absent key (symmetric with `metadata_unset`). Refused for a
246 /// schema-REQUIRED section (`MISSING_REQUIRED_SECTION` — the right
247 /// repair there is filling, not removing), for `relationships`
248 /// (`SECTION_NOT_UPDATABLE`), and for a key also named in any other
249 /// section mode (`CONFLICTING_SECTION_MODES`).
250 pub sections_unset: Vec<String>,
251 /// Metadata fields to set or replace. Values land as
252 /// `MetadataValue::String` for V1.
253 pub metadata: IndexMap<String, String>,
254 /// Metadata field keys to unset. Silently no-ops on absent keys.
255 pub metadata_unset: Vec<String>,
256 /// When `true`, validate and compute the prospective hash but
257 /// do not write to disk, mutate the store, or commit. Outcome
258 /// carries `content_hash` = the unchanged on-disk hash (so the
259 /// caller can use it as `expected_hash` on the follow-up real
260 /// call) and `prospective_hash` = the hash the entity would
261 /// have after the proposed write. Wire-equivalent to full's
262 /// `UpdateArgs.dry_run`. Optimistic-lock check is skipped on
263 /// the dry_run path so an agent can preview a change without
264 /// holding a fresh hash — designated stale-hash recovery path.
265 pub dry_run: bool,
266 /// Atomic batched relation declarations applied before the
267 /// section/metadata changes land. Each entry is validated like
268 /// any individual `memstead_relate` call (schema-shape, cross-mem
269 /// policy, target-id grammar), appended to the entity's
270 /// `relationships` list, and — for absent Write-target peers —
271 /// auto-stubbed in the target's mem. The strict
272 /// wiki-link/relation validator then runs against the
273 /// post-mutation state with the freshly-declared relations
274 /// already in place, so a body wiki-link added in the same
275 /// `memstead_update` call passes the gate without a separate
276 /// `memstead_relate` round-trip. Empty default — omit when no
277 /// batched declarations are needed.
278 pub declare_relations: Vec<crate::ops::RelateArg>,
279 /// Permissive `anchors[]` provenance records to attach to this entity
280 /// — validated ([`crate::anchor::AnchorInput::validate`]) and, when
281 /// non-empty, **merged** into the entity's row in the mem-branch
282 /// anchors sidecar in the SAME commit as the update so entity +
283 /// anchors land atomically: an incoming anchor replaces the existing
284 /// anchor with the same `(artifact, grain, class, span)` identity and
285 /// appends otherwise — writing never removes an anchor this call did not name
286 /// in [`Self::anchors_unset`]. Empty (the default) merges nothing and
287 /// leaves the stored set untouched. A malformed element refuses the
288 /// whole update with [`EngineError::InvalidAnchor`] (`INVALID_ANCHOR`)
289 /// — nothing is written. Not folded into `_hash` (sidecar lives under
290 /// `.memstead/`).
291 pub anchors: Vec<crate::anchor::AnchorInput>,
292 /// Explicit anchor removals, applied **before** the [`Self::anchors`]
293 /// merge in the same mutation (mirroring the `metadata_unset` /
294 /// `relations_unset` conventions). Each selector names an `artifact`
295 /// and may narrow by `grain` and/or `class`; a bare artifact removes
296 /// every anchor on it. Unsetting an anchor that does not exist is a
297 /// no-op, not an error — removal is idempotent. A malformed selector
298 /// refuses the whole update with [`EngineError::InvalidAnchor`].
299 pub anchors_unset: Vec<crate::anchor::AnchorUnsetInput>,
300 /// Repair-shaped relation removals (`{ rel_type, target }`),
301 /// applied atomically within this update. Accepted only when the
302 /// entity currently FAILS the conformance check (against the
303 /// effective schema) — a conformant entity refuses with
304 /// `REPAIR_NOT_NEEDED` and stays unmodified; `memstead_relate(remove)`
305 /// is the everyday detach path. Absent pairs are silent no-ops
306 /// (symmetric with `metadata_unset`). The strict-write
307 /// post-condition is unchanged: the post-repair entity must be
308 /// integral or the whole update refuses with the relevant
309 /// write-time code.
310 pub relations_unset: Vec<crate::ops::RelationUnsetArg>,
311}
312
313impl UpdateEntityArgs {
314 /// Whether this payload names anything that can move the entity's content
315 /// hash. Anchors are deliberately absent from the list: the sidecar lives
316 /// outside the hash.
317 ///
318 /// WHY it lives here rather than on each surface: MCP, the
319 /// CLI and the HTTP layer all gate an update on a compare-and-swap token,
320 /// and on an anchors-only payload that token compares a value the write
321 /// provably cannot move. Exempting the shape is right; exempting it four
322 /// times, once per surface, is how surfaces come to disagree about whether
323 /// a write is safe. One
324 /// predicate, one answer. The engine core does not consult it: it checks
325 /// the token only when a caller supplies one, and always has.
326 ///
327 /// A payload naming NOTHING changes no content either, and must fall
328 /// through to the empty-update refusal rather than be told it is missing a
329 /// token: that refusal names the recognised keys, which is what a caller
330 /// who typo'd a mutation key actually needs. A first version asked
331 /// "is this anchors-only" instead, and turned every empty payload into a
332 /// hash complaint; the grade of that change caught it.
333 pub fn changes_content(&self) -> bool {
334 !self.sections.is_empty()
335 || !self.append_sections.is_empty()
336 || !self.patch_sections.is_empty()
337 || !self.sections_unset.is_empty()
338 || !self.metadata.is_empty()
339 || !self.metadata_unset.is_empty()
340 || !self.declare_relations.is_empty()
341 || !self.relations_unset.is_empty()
342 }
343}
344
345/// Successful outcome of [`Engine::update_entity`].
346#[derive(Debug, Clone, serde::Serialize)]
347pub struct UpdateEntityOutcome {
348 pub id: EntityId,
349 /// Title from the parsed entity after the write — wire-equivalent
350 /// to full's `UpdateResult.title`. Reflects post-write state in
351 /// case a future update path touches the title (today the update
352 /// surface doesn't, but reading from the parsed entity rather
353 /// than echoing `args` keeps the field correct as the surface
354 /// evolves).
355 pub title: String,
356 pub file_path: String,
357 /// Wire key `_hash`.
358 #[serde(rename = "_hash")]
359 pub content_hash: String,
360 /// The identity the mem's backend minted for this write — a commit
361 /// SHA on a git-branch mem, an opaque synthetic token on a folder or
362 /// in-memory mem. An identity, never a change cursor. Wire-equivalent to
363 /// full's `UpdateResult.write_id`.
364 pub write_id: String,
365 /// ISO date string from the parsed entity's `modified_date`
366 /// metadata. Populated when the schema auto-stamps the field
367 /// on update; empty when the schema doesn't declare it. Wire-
368 /// equivalent to full's `UpdateResult.modified_date`.
369 pub modified_date: String,
370 /// Section-level mutations grouped by mode (replaced / appended /
371 /// patched). Wire-equivalent to full's
372 /// `UpdateResult.modified_sections`. Empty inner vecs serde-omit
373 /// per `ModifiedSections`'s field attributes; the outer key is
374 /// always present.
375 pub modified_sections: ModifiedSections,
376 /// Metadata-level mutations grouped by direction (set / unset).
377 /// Wire-equivalent to full's `UpdateResult.modified_metadata`.
378 /// Same empty-vec-omit convention as `modified_sections`.
379 pub modified_metadata: ModifiedMetadata,
380 /// `Some(hash)` on the dry_run path — the hash the entity
381 /// would have after the proposed write. `None` on real
382 /// updates (the post-write hash is in `content_hash`).
383 /// Wire-equivalent to full's `UpdateResult.prospective_hash`.
384 pub prospective_hash: Option<String>,
385 /// Stub entities whose last incoming edge was severed by this
386 /// update — when a body wiki-link was removed, the alias-resync
387 /// drops the backing pointer-rel-type edge, and if that was the
388 /// stub target's last referrer the stub is GC'd here. Empty on
389 /// updates that didn't orphan a stub (including section edits with
390 /// no wiki-link change, dry-run, and no-op). Shares the field name
391 /// and always-present shape with
392 /// [`DeleteEntityOutcome::orphan_stubs_removed`] and
393 /// [`RelateEntityOutcome::orphan_stubs_removed`] so MCP / CLI
394 /// consumers branch uniformly across the three GC paths.
395 pub orphan_stubs_removed: Vec<EntityId>,
396 /// Typed non-fatal issues — empty on the unified path today
397 /// (update doesn't surface InlineWikiLinkAutoStubbed or
398 /// MissingRequiredOutgoing yet). Wire-equivalent to full's
399 /// `UpdateResult.warnings`; the field shape parity matters for
400 /// the upcoming handler migration so callers see the same
401 /// `warnings: []` envelope position across surfaces.
402 pub warnings: Vec<WarningHint>,
403 /// Batched relation declarations applied by this call (per the
404 /// optional `declare_relations` request param). Empty `[]`
405 /// when no batched declarations were requested; populated with
406 /// one entry per declared relation otherwise. `target_was_stubbed`
407 /// flags which targets were absent at call time and got
408 /// auto-stubbed; agents use this to skip a follow-up
409 /// `memstead_entity` round-trip on the stubbed target.
410 #[serde(default, skip_serializing_if = "Vec::is_empty")]
411 pub relations_declared: Vec<RelationDeclared>,
412 /// Whether the update's anchors changed the sidecar: absent when the
413 /// update carried no anchors or unsets, `true` when a row was added,
414 /// replaced or removed, `false` when every supplied row restated
415 /// what was stored (nothing written, the sidecar bytes untouched).
416 #[serde(default, skip_serializing_if = "Option::is_none")]
417 pub anchors_changed: Option<bool>,
418}
419
420/// One batched relation declaration applied by a mutation call.
421/// Echoed in [`UpdateEntityOutcome::relations_declared`] and
422/// [`CreateEntityOutcome::relations_declared`] so agents see, in the
423/// same response, what landed and which targets had to be stubbed.
424#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
425pub struct RelationDeclared {
426 pub rel_type: String,
427 pub target: EntityId,
428 /// `true` when the target was absent at call time and the
429 /// engine materialised a stub for it (subject to the same
430 /// rules as `memstead_relate`'s auto-stub mechanic).
431 pub target_was_stubbed: bool,
432}
433
434/// Arguments for [`Engine::delete_entity`].
435///
436/// No `force` flag — delete is binary. The engine refuses on any
437/// Write-Mem incoming reference (typed `HAS_INCOMING_REFS`); when
438/// only ReadOnly-mount referrers remain, the entity is demoted to a
439/// stub in-memory and the delete proceeds, surfaced via a typed
440/// `RESIDUAL_STUB_FOR_READONLY_REFERRERS` warning on the outcome.
441#[derive(Debug, Clone)]
442pub struct DeleteEntityArgs {
443 pub id: EntityId,
444 /// Optimistic locking; see [`ExpectedHash`]. A stub needs none.
445 pub expected_hash: ExpectedHash,
446}
447
448/// Successful outcome of [`Engine::delete_entity`].
449#[derive(Debug, Clone, serde::Serialize)]
450pub struct DeleteEntityOutcome {
451 pub id: EntityId,
452 pub file_path: String,
453 /// Ids of entities that referenced the deleted entity (only
454 /// populated on the residual-stub-demotion path — the surviving
455 /// ReadOnly-mount referrers are listed here for diagnostic
456 /// continuity with the warning payload).
457 pub removed_incoming: Vec<String>,
458 /// Total edges removed across incoming + outgoing — full
459 /// `DeleteResult.relations_removed`. Counted from the store
460 /// pre-delete; both directions sum into one number for callers
461 /// that need a single "how much did this delete cascade" signal.
462 pub relations_removed: usize,
463 /// The identity the mem's backend minted for this write — a commit
464 /// SHA on a git-branch mem, an opaque synthetic token on a folder or
465 /// in-memory mem. An identity, never a change cursor. Wire-equivalent to
466 /// full's `DeleteResult.write_id`.
467 pub write_id: String,
468 /// Stub entities that became orphaned by this delete (their last
469 /// incoming edge disappeared with this entity) and were
470 /// garbage-collected. Empty on deletes that didn't sever a
471 /// stub's last referrer. Wire-equivalent to full's
472 /// `DeleteResult.orphan_stubs_removed`.
473 pub orphan_stubs_removed: Vec<EntityId>,
474 /// Typed non-fatal issues — populated on the residual-stub
475 /// demotion path with a `RESIDUAL_STUB_FOR_READONLY_REFERRERS`
476 /// warning naming the surviving ReadOnly-mount referrers. Empty
477 /// on the clean-removal path.
478 pub warnings: Vec<WarningHint>,
479}
480
481/// Arguments for [`Engine::relate_entity`].
482#[derive(Debug, Clone)]
483pub struct RelateEntityArgs {
484 pub source: EntityId,
485 /// Optimistic locking on the source. `None` skips the check: relate
486 /// stays outside the [`ExpectedHash`] rule on purpose. It adds or
487 /// removes one edge idempotently, cannot overwrite a section, and its
488 /// response returns the hash the next content change must present.
489 pub expected_hash: Option<String>,
490 pub rel_type: String,
491 pub target: EntityId,
492 /// `false` (default) appends. `true` removes the matching pair.
493 pub remove: bool,
494 /// Optional per-edge description applied on the add path.
495 /// Validated against the rel-type's `per_edge_description`
496 /// posture at call time — `forbidden` rejects `Some`; `required`
497 /// rejects `None`. Empty / whitespace-only strings normalise to
498 /// `None` before validation. Ignored on the remove path (`None`
499 /// keeps the existing behaviour intact).
500 pub description: Option<String>,
501 /// Rehearsal mode: run the FULL validation
502 /// stage — identical refusals, identical warnings (including the
503 /// would-be `AUTO_STUB_CREATED`) — then stop before any write.
504 /// The response carries the marker form: empty `write_id` with
505 /// `_hash` set to the PROSPECTIVE post-write hash. Nothing is
506 /// staged, committed, or stubbed.
507 pub dry_run: bool,
508}
509
510/// What a relate call did to the source's relationships.
511#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
512#[serde(rename_all = "snake_case")]
513pub enum RelateAction {
514 Added,
515 Removed,
516 NoOpAlreadyPresent,
517 NoOpAbsent,
518}
519
520/// Successful outcome of [`Engine::relate_entity`].
521#[derive(Debug, Clone, serde::Serialize)]
522pub struct RelateEntityOutcome {
523 pub from: EntityId,
524 pub to: EntityId,
525 pub rel_type: String,
526 pub action: RelateAction,
527 /// Source entity's content hash after the call. Unchanged on
528 /// no-op paths so callers can chain follow-ups without
529 /// refetching. Wire key `_hash`.
530 #[serde(rename = "_hash")]
531 pub content_hash: String,
532 /// The identity the mem's backend minted for this write — a commit
533 /// SHA on a git-branch mem, an opaque synthetic token on a folder or
534 /// in-memory mem. An identity, never a change cursor. Empty on the no-op
535 /// paths ([`RelateAction::NoOpAlreadyPresent`],
536 /// [`RelateAction::NoOpAbsent`]) — those branches skip the disk
537 /// write so no commit happens. Wire-equivalent to the full
538 /// `RelateResult.write_id`.
539 pub write_id: String,
540 /// Edge provenance label — always `"explicit"` for relate-call
541 /// outcomes. Wire-equivalent to full's `RelateResult.source` field;
542 /// reserved for future inline-link-derived edge surfacing.
543 pub source: String,
544 /// Typed non-fatal issues — open-mode schema admissions
545 /// ([`WarningHint::UndeclaredRelationshipOpen`]), duplicate-add
546 /// no-ops ([`WarningHint::DuplicateRelationship`]),
547 /// remove-nonexistent no-ops ([`WarningHint::NoSuchRelationship`]),
548 /// and auto-stubbed targets
549 /// ([`WarningHint::AutoStubCreated`]). The auto-stub case once
550 /// rode through a deprecated top-level
551 /// `stub_warning: Option<String>` field that didn't follow the
552 /// `warnings[]` shape — agents iterating diagnostics silently
553 /// skipped it; the field has been retired in favour of the
554 /// uniform warning vocabulary. Empty on the strict-add and
555 /// strict-remove happy paths.
556 pub warnings: Vec<WarningHint>,
557 /// Stub entities whose last incoming edge was severed by a
558 /// `remove=true` call and that were garbage-collected as orphans.
559 /// Empty on the add path and on remove paths that didn't strip
560 /// the last referrer. Wire-equivalent to
561 /// [`DeleteEntityOutcome::orphan_stubs_removed`]; both surfaces
562 /// share the same field name so MCP / CLI consumers can branch
563 /// uniformly.
564 pub orphan_stubs_removed: Vec<EntityId>,
565}
566
567/// Arguments for [`Engine::rename_entity`].
568#[derive(Debug, Clone)]
569pub struct RenameEntityArgs {
570 pub id: EntityId,
571 /// Optimistic locking; see [`ExpectedHash`].
572 pub expected_hash: ExpectedHash,
573 pub new_title: String,
574}
575
576/// Successful outcome of [`Engine::rename_entity`].
577#[derive(Debug, Clone, serde::Serialize)]
578pub struct RenameEntityOutcome {
579 pub old_id: EntityId,
580 pub new_id: EntityId,
581 /// Mem-relative path of the renamed entity before the rewrite.
582 /// Wire-equivalent to full's `RenameResult.old_path`.
583 pub old_path: String,
584 /// Mem-relative path of the renamed entity after the rewrite.
585 /// Wire-equivalent to full's `RenameResult.new_path`.
586 pub new_path: String,
587 /// Wire key `_hash`.
588 #[serde(rename = "_hash")]
589 pub content_hash: String,
590 /// The identity the mem's backend minted for this write — a commit
591 /// SHA on a git-branch mem, an opaque synthetic token on a folder or
592 /// in-memory mem. An identity, never a change cursor. Empty on the
593 /// slug-noop short-circuit (no disk write happened).
594 /// Wire-equivalent to full's `RenameResult.write_id`.
595 pub write_id: String,
596 /// Typed non-fatal issues. The slug-noop short-circuit
597 /// ([`WarningHint::TitleNormalizedToSlugNoop`]) surfaces here
598 /// when a requested title normalises to the existing slug — the
599 /// op stays a silent no-op on disk, but the warning tells
600 /// autonomous skills not to trust `old_id == new_id` as
601 /// "cosmetic rewrite landed". Empty on the real-rename happy
602 /// path. Wire-equivalent to full's `RenameResult.warnings`.
603 pub warnings: Vec<WarningHint>,
604}
605
606/// Arguments for [`Engine::retype_entity`].
607#[derive(Debug, Clone)]
608pub struct RetypeEntityArgs {
609 pub id: EntityId,
610 /// Optimistic locking; see [`ExpectedHash`]. A dry run needs none and
611 /// skips the compare.
612 pub expected_hash: ExpectedHash,
613 /// The type the entity becomes; must be declared by the mem's schema.
614 pub target_type: String,
615 /// Section keys to rename on the way: `old key → new key`. A key not
616 /// mapped keeps its name and must be declared by the target type (or
617 /// the retype refuses `UNKNOWN_SECTION` with a proposed map).
618 pub section_map: IndexMap<String, String>,
619 /// Metadata keys the caller explicitly lets go — the fields the
620 /// source type declared and the target does not (a spec's `level`
621 /// on the way to a memo). Never inferred: an undeclared field that is
622 /// not listed here refuses `UNKNOWN_METADATA_FIELD`, because dropping
623 /// data unannounced is what the write gates exist to prevent. A key
624 /// the entity does not carry is a silent no-op.
625 pub drop_metadata: Vec<String>,
626 /// Validate everything and compute the prospective hash without
627 /// writing, committing, or touching the store.
628 pub dry_run: bool,
629}
630
631/// Successful outcome of [`Engine::retype_entity`].
632#[derive(Debug, Clone, serde::Serialize)]
633pub struct RetypeEntityOutcome {
634 pub id: EntityId,
635 /// Unchanged by the retype — the id and path are the point.
636 pub file_path: String,
637 pub old_type: String,
638 pub new_type: String,
639 /// Wire key `_hash`: the content hash after the write (the next
640 /// `expected_hash`); on a dry run the UNCHANGED current hash.
641 #[serde(rename = "_hash")]
642 pub content_hash: String,
643 /// The hash the entity would carry after the write — dry runs only.
644 #[serde(skip_serializing_if = "Option::is_none")]
645 pub prospective_hash: Option<String>,
646 /// The identity the mem's backend minted for this write — a commit
647 /// SHA on a git-branch mem, an opaque synthetic token on a folder or
648 /// in-memory mem. An identity, never a change cursor. Empty on a dry
649 /// run (no disk write happened).
650 pub write_id: String,
651 /// `(old key, new key)` pairs the `section_map` applied.
652 pub sections_renamed: Vec<(String, String)>,
653 /// Every edge examined against the target type's pins: outgoing,
654 /// incoming (loaded), and incoming from deferred mems.
655 pub edges_rechecked: usize,
656 /// Always true: the content hash moved, so every check record and
657 /// derivation baseline keyed to the previous hash is stale.
658 pub checks_stale: bool,
659 /// The sentence that says so, for the surface to print.
660 pub staleness_note: String,
661 pub warnings: Vec<WarningHint>,
662}
663
664/// Which side of an edge the retyped entity is on.
665#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
666#[serde(rename_all = "lowercase")]
667pub enum RetypeEdgeDirection {
668 Outgoing,
669 Incoming,
670}
671
672/// One edge the target type's pins refuse.
673#[derive(Debug, Clone, PartialEq, serde::Serialize)]
674pub struct RetypeEdge {
675 pub direction: RetypeEdgeDirection,
676 pub from: String,
677 pub to: String,
678 pub rel_type: String,
679 pub cross_mem: bool,
680 /// The shape validator's own recovery detail (allowed source and
681 /// target types, suggestion).
682 pub detail: serde_json::Value,
683}
684
685/// One reason a retype is refused. Every problem found is reported
686/// together in [`EngineError::RetypeRefused`]; each carries the wire code
687/// the same condition has on the create/update/relate surfaces.
688#[derive(Debug, Clone, serde::Serialize)]
689#[serde(tag = "kind", rename_all = "snake_case")]
690pub enum RetypeProblem {
691 /// A (mapped) section key the target type does not declare.
692 UnknownSection {
693 key: String,
694 declared: Vec<String>,
695 suggestion: Option<String>,
696 },
697 /// A section the target type requires is absent or empty.
698 MissingRequiredSection {
699 key: String,
700 heading: String,
701 write_rules: Vec<String>,
702 },
703 /// A metadata field the target type requires is unset and has no
704 /// default.
705 MissingRequiredField {
706 key: String,
707 description: String,
708 enum_values: Vec<String>,
709 },
710 /// A validator refusal carried verbatim: body content, an unknown
711 /// metadata field, an enum or field value the target rejects.
712 Validation {
713 code: &'static str,
714 message: String,
715 details: serde_json::Value,
716 },
717 /// `section_map` names a key the entity does not carry.
718 SectionMapSourceMissing {
719 key: String,
720 present: Vec<String>,
721 },
722 /// Two sections would land under one key.
723 SectionMapCollision {
724 from: String,
725 to: String,
726 also_from: String,
727 },
728 EdgeShape(RetypeEdge),
729 RequiredOutgoingUnsatisfied {
730 blocks: Vec<crate::ops::MissingRequiredOutgoingBlock>,
731 },
732 ConstraintUnsatisfied {
733 violations: Vec<crate::ops::health::UnsatisfiedConstraint>,
734 },
735}
736
737impl RetypeProblem {
738 /// The wire code this condition carries everywhere else.
739 pub fn code(&self) -> &'static str {
740 match self {
741 RetypeProblem::UnknownSection { .. } => "UNKNOWN_SECTION",
742 RetypeProblem::MissingRequiredSection { .. } => "MISSING_REQUIRED_SECTION",
743 RetypeProblem::MissingRequiredField { .. } => "REQUIRED_FIELD_UNSET",
744 RetypeProblem::Validation { code, .. } => code,
745 RetypeProblem::SectionMapSourceMissing { .. } => "SECTION_MAP_SOURCE_MISSING",
746 RetypeProblem::SectionMapCollision { .. } => "SECTION_MAP_COLLISION",
747 RetypeProblem::EdgeShape(_) => "INVALID_REL_SHAPE",
748 RetypeProblem::RequiredOutgoingUnsatisfied { .. } => "MISSING_REQUIRED_OUTGOING",
749 RetypeProblem::ConstraintUnsatisfied { .. } => "CONSTRAINT_UNSATISFIED",
750 }
751 }
752
753 /// One line a human or agent can act on.
754 pub fn message(&self) -> String {
755 match self {
756 RetypeProblem::UnknownSection {
757 key,
758 declared,
759 suggestion,
760 } => format!(
761 "section `{key}` is not declared by the target type (declared: {}){}",
762 declared.join(", "),
763 suggestion
764 .as_deref()
765 .map(|s| format!("; map it with section_map {key}={s}"))
766 .unwrap_or_default()
767 ),
768 RetypeProblem::MissingRequiredSection { key, heading, .. } => {
769 format!("required section `{key}` ({heading}) is missing or empty")
770 }
771 RetypeProblem::MissingRequiredField { key, .. } => {
772 format!("required metadata field `{key}` is unset and has no default")
773 }
774 RetypeProblem::Validation { message, .. } => message.clone(),
775 RetypeProblem::SectionMapSourceMissing { key, present } => format!(
776 "section_map names `{key}`, which the entity does not carry (present: {})",
777 present.join(", ")
778 ),
779 RetypeProblem::SectionMapCollision {
780 from,
781 to,
782 also_from,
783 } => {
784 format!("section_map sends both `{also_from}` and `{from}` to `{to}`")
785 }
786 RetypeProblem::EdgeShape(e) => format!(
787 "{} edge {} --{}--> {} is outside the target type's pins{}",
788 match e.direction {
789 RetypeEdgeDirection::Outgoing => "outgoing",
790 RetypeEdgeDirection::Incoming => "incoming",
791 },
792 e.from,
793 e.rel_type,
794 e.to,
795 if e.cross_mem { " (cross-mem)" } else { "" }
796 ),
797 RetypeProblem::RequiredOutgoingUnsatisfied { blocks } => format!(
798 "{} block-tier required_outgoing block(s) of the target type unsatisfied",
799 blocks.len()
800 ),
801 RetypeProblem::ConstraintUnsatisfied { violations: v } => {
802 format!(
803 "{} block-tier constraint(s) of the target type violated",
804 v.len()
805 )
806 }
807 }
808 }
809}
810
811#[cfg(test)]
812mod tests {
813 use super::*;
814
815 #[test]
816 fn outcome_types_serialize_to_json() {
817 // Lock the Serialize derives: every
818 // outcome type round-trips through `serde_json::to_string`
819 // without panicking. The wire shape's specific field names
820 // are exercised end-to-end via the MCP handlers; this test
821 // is the structural lock.
822 let create = CreateEntityOutcome {
823 id: EntityId("v--e".to_string()),
824 title: "t".to_string(),
825 mem: "v".to_string(),
826 file_path: "v/e.md".to_string(),
827 content_hash: "h".to_string(),
828 write_id: "sha".to_string(),
829 created_date: "2026-05-11".to_string(),
830 warnings: Vec::new(),
831 type_guidance: std::collections::BTreeMap::new(),
832 incoming_count: None,
833 incoming: Vec::new(),
834 relations_declared: Vec::new(),
835 };
836 assert!(serde_json::to_string(&create).is_ok());
837
838 let update = UpdateEntityOutcome {
839 id: EntityId("v--e".to_string()),
840 title: "t".to_string(),
841 file_path: "v/e.md".to_string(),
842 content_hash: "h".to_string(),
843 write_id: "sha".to_string(),
844 modified_date: "2026-05-11".to_string(),
845 modified_sections: ModifiedSections::default(),
846 modified_metadata: ModifiedMetadata::default(),
847 prospective_hash: None,
848 orphan_stubs_removed: Vec::new(),
849 warnings: Vec::new(),
850 relations_declared: Vec::new(),
851 anchors_changed: None,
852 };
853 assert!(serde_json::to_string(&update).is_ok());
854
855 let delete = DeleteEntityOutcome {
856 id: EntityId("v--e".to_string()),
857 file_path: "v/e.md".to_string(),
858 removed_incoming: Vec::new(),
859 write_id: "sha".to_string(),
860 relations_removed: 0,
861 orphan_stubs_removed: Vec::new(),
862 warnings: Vec::new(),
863 };
864 assert!(serde_json::to_string(&delete).is_ok());
865
866 let relate = RelateEntityOutcome {
867 from: EntityId("v--a".to_string()),
868 to: EntityId("v--b".to_string()),
869 rel_type: "PART_OF".to_string(),
870 action: RelateAction::Added,
871 content_hash: "h".to_string(),
872 write_id: "sha".to_string(),
873 source: "explicit".to_string(),
874 warnings: Vec::new(),
875 orphan_stubs_removed: Vec::new(),
876 };
877 assert!(serde_json::to_string(&relate).is_ok());
878
879 let rename = RenameEntityOutcome {
880 old_id: EntityId("v--a".to_string()),
881 new_id: EntityId("v--b".to_string()),
882 old_path: "v/a.md".to_string(),
883 new_path: "v/b.md".to_string(),
884 content_hash: "h".to_string(),
885 write_id: "sha".to_string(),
886 warnings: Vec::new(),
887 };
888 let rename_json = serde_json::to_string(&rename).unwrap();
889 // Field names match full's RenameResult wire shape directly.
890 assert!(
891 rename_json.contains("\"old_path\""),
892 "RenameEntityOutcome must serialize old_path: {rename_json}",
893 );
894 assert!(
895 rename_json.contains("\"new_path\""),
896 "RenameEntityOutcome must serialize new_path: {rename_json}",
897 );
898 }
899}
900
901/// Outcome discriminator for [`Engine::set_mem_schema`]. The agent
902/// branches on this — never on which response fields are populated
903/// (stable additive shape, no response-shape polymorphism).
904#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
905#[serde(rename_all = "snake_case")]
906pub enum SetSchemaResult {
907 /// Requested schema == current pin; no state change.
908 Noop,
909 /// Mem was (or became) integral against the target — the pin
910 /// now IS the target and any migration state is cleared.
911 Switched,
912 /// Mem was not integral against the target; dual-pin state
913 /// entered, `findings` carries the non-integral entities.
914 MigrationStarted,
915 /// Re-issued with the same in-flight target while still not
916 /// integral; `findings` carries the *remaining* non-integral
917 /// entities.
918 MigrationPending,
919}
920
921/// Stable response shape of [`Engine::set_mem_schema`] — all six
922/// fields are always present, populated per outcome.
923#[derive(Debug, Clone, serde::Serialize)]
924pub struct SetSchemaOutcome {
925 pub mem: String,
926 /// The settled pin after this call (`<name>@<version>`).
927 pub schema_pin: String,
928 /// In-flight target while a migration is in progress, else `None`.
929 pub migration_target: Option<String>,
930 pub outcome: SetSchemaResult,
931 /// Integrity-linter findings (`{ id, axis, code, detail }`) for
932 /// the entities not yet integral against the target; empty unless
933 /// a migration is in progress.
934 pub findings: Vec<crate::ops::integrity::IntegrityFinding>,
935 /// The resolved schema the mem's mutation stamp names after this
936 /// call — the marker the `ENGINE_VERSION_SKEW` hint reads. A
937 /// completed switch re-stamps it with the target; a dual-pin entry
938 /// leaves it where the last mutation put it, so a reader sees here
939 /// which generation the marker still carries. `None` when the mem
940 /// carries no stamp (config-less, or never mutated by a stamping
941 /// engine).
942 pub stamped_schema: Option<String>,
943}