Skip to main content

memstead_base/ops/
crud.rs

1//! Arguments and results for the entity CRUD operations, and the shared `envelope` builder both the warning wire and the MCP error wire use.
2
3use super::*;
4
5// ---------------------------------------------------------------------------
6// CRUD types
7// ---------------------------------------------------------------------------
8
9/// Arguments for creating an entity.
10#[derive(Debug, Clone)]
11pub struct CreateArgs {
12    pub title: String,
13    pub mem: String,
14    pub entity_type: String,
15    /// Section contents keyed by section key: `{ "<section-key>": "..." }`.
16    /// Valid keys depend on the schema (see `TypeDefinition::sections`).
17    pub sections: IndexMap<String, String>,
18    /// Metadata overrides: `{ "<field-key>": "value" }`.
19    pub metadata: IndexMap<String, String>,
20    /// Relationships to create: `[{ target: EntityId, rel_type: "USES" }]`.
21    pub relations: Vec<RelateArg>,
22    /// When true, validate and compute the result but do not write to
23    /// disk, mutate the store, create edges, or commit. Response carries
24    /// the prospective `id`, `file_path`, `content_hash`, and any
25    /// `warnings` — `write_id` is empty.
26    pub dry_run: bool,
27}
28
29/// Arguments for updating an entity.
30#[derive(Debug, Clone)]
31pub struct UpdateArgs {
32    pub id: EntityId,
33    /// Expected content hash (optimistic locking). Required.
34    pub expected_hash: String,
35    /// Section fields to set: `{ "<section-key>": "new content" }`.
36    pub sections: IndexMap<String, String>,
37    /// Section fields to append to: `{ "<section-key>": "extra content" }`.
38    pub append_sections: IndexMap<String, String>,
39    /// Section fields to patch: `{ "<section-key>": PatchArg { old, new } }`.
40    pub patch_sections: IndexMap<String, PatchArg>,
41    /// Metadata fields to set: `{ "<field-key>": "value" }`.
42    pub metadata: IndexMap<String, String>,
43    /// Metadata keys to remove from the entity. Silent no-op on absent
44    /// keys. Errors on read-only fields (mem, id, type) and on
45    /// schema-required fields for the entity's type.
46    pub metadata_unset: Vec<String>,
47    /// Dry-run mode — return proposed changes without persisting.
48    pub dry_run: bool,
49}
50
51/// Arguments for a patch (substring replacement).
52#[derive(Debug, Clone)]
53pub struct PatchArg {
54    pub old: String,
55    pub new: String,
56    /// When `true`, replace every occurrence of `old` in the target
57    /// section. Default `false` replaces only the first occurrence.
58    pub all: bool,
59}
60
61/// Section-level mutations applied by a single `memstead_update` call.
62/// Each vec lists the section keys that landed in that mutation mode.
63/// Empty inner vecs are serde-omitted so the wire stays quiet; the
64/// struct itself always serialises so the outer `modified_sections` key
65/// is a stable shape regardless of what the call actually touched.
66#[derive(Debug, Clone, Default, Serialize)]
67pub struct ModifiedSections {
68    /// Section keys whose body was replaced wholesale (`sections` input).
69    #[serde(default, skip_serializing_if = "Vec::is_empty")]
70    pub replaced: Vec<String>,
71    /// Section keys whose body received an append (`append_sections`).
72    #[serde(default, skip_serializing_if = "Vec::is_empty")]
73    pub appended: Vec<String>,
74    /// Section keys whose body was patched via find-and-replace
75    /// (`patch_sections`).
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub patched: Vec<String>,
78    /// Section keys removed outright — heading and body (`sections_unset`).
79    #[serde(default, skip_serializing_if = "Vec::is_empty")]
80    pub unset: Vec<String>,
81}
82
83/// Metadata-level mutations applied by a single `memstead_update` call.
84/// Same empty-vec-omit convention as `ModifiedSections`; auto-timestamp
85/// metadata fields written by the engine are NOT surfaced here (they are
86/// engine-driven, not user-driven — the caller has nothing to react to).
87#[derive(Debug, Clone, Default, Serialize)]
88pub struct ModifiedMetadata {
89    /// Metadata keys whose value was set or replaced.
90    #[serde(default, skip_serializing_if = "Vec::is_empty")]
91    pub set: Vec<String>,
92    /// Metadata keys that were removed from the frontmatter.
93    #[serde(default, skip_serializing_if = "Vec::is_empty")]
94    pub unset: Vec<String>,
95}
96
97/// Result of an update operation.
98#[derive(Debug, Clone, Serialize)]
99pub struct UpdateResult {
100    pub id: EntityId,
101    pub title: String,
102    /// Section-level mutations grouped by mode. Replaces the former flat
103    /// `modified_fields: Vec<String>` (which leaked mode as a string
104    /// prefix and collided on bare keys with `modified_metadata`).
105    pub modified_sections: ModifiedSections,
106    /// Metadata-level mutations grouped by direction (set vs unset).
107    pub modified_metadata: ModifiedMetadata,
108    pub modified_date: String,
109    /// On a real (non-dry-run) update: the new on-disk content hash after
110    /// the write. On a dry-run: the **current** on-disk hash (unchanged) —
111    /// the value an agent passes back as `expected_hash` on the follow-up
112    /// real call. Pair with `prospective_hash` to predict the post-write
113    /// hash without a second read. Wire key `_hash`.
114    #[serde(rename = "_hash")]
115    pub content_hash: String,
116    /// Dry-run only: the hash the entity *would* have after the proposed
117    /// write. `None` on real (non-dry-run) updates. Lets agents preview a
118    /// change and then call the real update with `expected_hash =
119    /// content_hash` (pinning the disk state) while still knowing what the
120    /// post-write hash will look like. Additive optional field — stable
121    /// shape for callers that ignore it.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub prospective_hash: Option<String>,
124    /// The identity the mem's backend minted for this write: a commit
125    /// SHA on a git-branch mem, an opaque synthetic token on a folder
126    /// or in-memory mem. It is an identity and NOT a change cursor —
127    /// `memstead_changes_since` takes a commit SHA on a git-branch mem
128    /// and an RFC3339 ledger timestamp on a folder mem, and feeding it
129    /// this token refuses with `INVALID_CURSOR` (before that guard it
130    /// silently replayed a folder mem's whole history).
131    /// Empty for dry runs (no write happens).
132    #[serde(default)]
133    pub write_id: String,
134    /// Typed non-fatal issues — same shape as `CreateResult::warnings`.
135    /// Pre-Bug-4 this was `Vec<String>` and unused; now carries
136    /// `WarningHint` so e.g. `INLINE_WIKI_LINK_AUTO_STUBBED` from update
137    /// flows out via the same `{code, message, details}` envelope agents
138    /// already branch on for create-time warnings.
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    pub warnings: Vec<WarningHint>,
141}
142
143/// Build the uniform `{ code, message, details }` envelope used on both the
144/// warning wire (`WarningHint`'s custom `Serialize`) and the MCP error wire
145/// (`tool_error_with_payload` payloads in `engine_err_with_suggestions`).
146/// Agents and other decoders branch on `code` (UPPER_SNAKE_CASE, stable)
147/// and parse `details` by `code` when they need structured fields.
148pub fn envelope(
149    code: &str,
150    message: impl Into<String>,
151    details: serde_json::Value,
152) -> serde_json::Value {
153    serde_json::json!({
154        "code": code,
155        "message": message.into(),
156        "details": details,
157    })
158}
159
160/// Result of a create operation.
161#[derive(Debug, Clone, Serialize)]
162pub struct CreateResult {
163    pub id: EntityId,
164    pub title: String,
165    pub mem: String,
166    pub file_path: String,
167    pub created_date: String,
168    /// Post-write content hash under the real path; the **prospective**
169    /// hash under `dry_run` — bit-identical to what a real call with the
170    /// same inputs would produce. Wire key `_hash`.
171    #[serde(rename = "_hash")]
172    pub content_hash: String,
173    /// The backend's identity for this write, never a cursor — see
174    /// `UpdateResult::write_id`. Empty under
175    /// `dry_run`.
176    #[serde(default)]
177    pub write_id: String,
178    /// Typed non-fatal issues — missing required sections (with writing
179    /// guidance) and open-mode relationship admissions.
180    #[serde(default, skip_serializing_if = "Vec::is_empty")]
181    pub warnings: Vec<WarningHint>,
182    /// Type-level `write_rules` keyed by `entity_type` — the
183    /// MISSING_REQUIRED_SECTION / MISSING_REQUIRED_FIELD warnings on
184    /// `warnings[]` reference this top-level map via their
185    /// `entity_type` field rather than each carrying the (identical,
186    /// type-axis) array (F9). Stable empty shape (`{}`) ships when no
187    /// such warnings fire — consumers don't branch on field presence.
188    #[serde(default)]
189    pub type_guidance: std::collections::BTreeMap<String, Vec<String>>,
190    /// Number of incoming edges adopted from a pre-existing stub at this
191    /// id (real path) or that would be adopted (dry_run). `None` means
192    /// no pre-existing stub / no incoming refs — field is serde-omitted.
193    #[serde(skip_serializing_if = "Option::is_none")]
194    pub incoming_count: Option<usize>,
195    /// Incoming edges present at this id at create time. Real path:
196    /// edges preserved during stub adoption. Dry_run: edges that would
197    /// be adopted if committed. Sorted by (rel_type, from) for
198    /// determinism. Empty vec is serde-omitted.
199    #[serde(default, skip_serializing_if = "Vec::is_empty")]
200    pub incoming: Vec<IncomingRef>,
201}
202
203/// Serialisable projection of `store::InEdge` for `CreateResult.incoming`.
204/// `source` is the lowercase `EdgeSource` variant:
205/// `"explicit" | "hierarchy" | "body_link"`.
206#[derive(Debug, Clone, Serialize)]
207pub struct IncomingRef {
208    pub from: EntityId,
209    pub rel_type: String,
210    pub source: String,
211}
212
213/// Project `&[store::InEdge]` into a sorted `Vec<IncomingRef>`. Ordering
214/// by (rel_type, from) ascending — deterministic output despite the
215/// underlying HashMap iteration order.
216pub fn project_incoming(edges: &[crate::store::InEdge]) -> Vec<IncomingRef> {
217    let mut out: Vec<IncomingRef> = edges
218        .iter()
219        .map(|e| IncomingRef {
220            from: e.from.clone(),
221            rel_type: e.rel_type.clone(),
222            source: match e.source {
223                crate::store::EdgeSource::Explicit => "explicit",
224                crate::store::EdgeSource::Hierarchy => "hierarchy",
225                crate::store::EdgeSource::BodyLink => "body_link",
226            }
227            .to_string(),
228        })
229        .collect();
230    out.sort_by(|a, b| a.rel_type.cmp(&b.rel_type).then(a.from.0.cmp(&b.from.0)));
231    out
232}
233
234/// Result of a delete operation.
235#[derive(Debug, Clone, Serialize)]
236pub struct DeleteResult {
237    pub id: EntityId,
238    pub relations_removed: usize,
239    /// The backend's identity for this write, never a cursor — see
240    /// `UpdateResult::write_id`.
241    #[serde(default)]
242    pub write_id: String,
243    /// Stub entities that became orphaned by this delete (their last
244    /// incoming edge disappeared with this entity) and were garbage-
245    /// collected. Empty vec is serde-omitted.
246    #[serde(default, skip_serializing_if = "Vec::is_empty")]
247    pub orphan_stubs_removed: Vec<EntityId>,
248}
249
250/// Result of a rename operation.
251#[derive(Debug, Clone, Serialize)]
252pub struct RenameResult {
253    pub old_id: EntityId,
254    pub new_id: EntityId,
255    pub old_path: String,
256    pub new_path: String,
257    /// Content hash of the renamed entity after the write. Sources by branch:
258    ///   - Real rename (slug change): post-write hash from the re-parsed
259    ///     entity, including the `modified_date` bump applied by
260    ///     `rename_entity` and any wiki-link rewrites in referrers.
261    ///   - Slug-noop short-circuit: the unchanged on-disk hash (no write
262    ///     happened).
263    ///
264    /// Pass this as `expected_hash` on the next hash-protected op
265    /// (`memstead_update`, `memstead_rename`, `memstead_delete`) on the entity — no
266    /// `memstead_entity` re-read required. Mirrors `RelateResult._hash`.
267    /// Wire key `_hash`.
268    #[serde(default, rename = "_hash", skip_serializing_if = "String::is_empty")]
269    pub content_hash: String,
270    /// The backend's identity for this write, never a cursor — see
271    /// `UpdateResult::write_id`. Empty on the
272    /// no-op same-title rename (no file change, no commit).
273    #[serde(default)]
274    pub write_id: String,
275    /// Typed non-fatal issues. The slug-noop short-circuit
276    /// (`TitleNormalizedToSlugNoop`) surfaces here when a requested title
277    /// normalises to the existing slug — the op stays a silent no-op on
278    /// disk, but the warning tells autonomous skills not to trust
279    /// `old_id == new_id` as "cosmetic rewrite landed".
280    #[serde(default, skip_serializing_if = "Vec::is_empty")]
281    pub warnings: Vec<WarningHint>,
282}
283
284/// Arguments for a relate/unrelate operation.
285#[derive(Debug, Clone)]
286pub struct RelateArg {
287    /// The far end of the edge. Named `target` rather than `to`
288    /// because the near end is implied by the call (the entity being
289    /// created or updated) — the rule the response shapes already
290    /// follow: a pair is `from`/`to`, an implied near end leaves
291    /// `target`.
292    pub target: EntityId,
293    pub rel_type: String,
294    /// Optional per-edge description text. Validated against the
295    /// rel-type's `per_edge_description` posture at call time —
296    /// `forbidden` rejects `Some`; `required` rejects `None`.
297    /// Empty / whitespace-only strings normalise to `None` before
298    /// validation.
299    pub description: Option<String>,
300}
301
302/// One repair-shaped relation removal on `memstead_update` —
303/// `relations_unset: [{ rel_type, target }]`. Symmetric with
304/// `metadata_unset`: an absent `(rel_type, target)` pair is a silent
305/// no-op. Only accepted when the target entity currently fails the
306/// conformance check (`REPAIR_NOT_NEEDED` otherwise) — the everyday
307/// detach path stays `memstead_relate(remove)`.
308#[derive(Debug, Clone, serde::Deserialize)]
309pub struct RelationUnsetArg {
310    pub rel_type: String,
311    pub target: EntityId,
312}
313
314/// Result of a relate operation.
315#[derive(Debug, Clone, Serialize)]
316pub struct RelateResult {
317    pub from: EntityId,
318    pub to: EntityId,
319    pub rel_type: String,
320    pub source: String,
321    /// Content hash of the source entity after the relate. On successful
322    /// add/remove, reflects the re-rendered file (Relationships section
323    /// updated); on duplicate-add and remove-nonexistent no-ops, reflects
324    /// the unchanged file. Pass this as `expected_hash` on the next
325    /// hash-protected op (`memstead_update`, `memstead_rename`, `memstead_delete`) on
326    /// the source — no `memstead_entity` re-read required. Wire key `_hash`.
327    #[serde(default, rename = "_hash", skip_serializing_if = "String::is_empty")]
328    pub content_hash: String,
329    /// The backend's identity for this write, never a cursor — see
330    /// `UpdateResult::write_id`.
331    #[serde(default)]
332    pub write_id: String,
333    /// Typed non-fatal issues — open-mode schema admissions, duplicate-add
334    /// no-ops (`DuplicateRelationship`), remove-nonexistent no-ops
335    /// (`NoSuchRelationship`). Previously silent edge cases now surface here.
336    #[serde(default, skip_serializing_if = "Vec::is_empty")]
337    pub warnings: Vec<WarningHint>,
338    /// True if the op wrote to disk (real add or real remove). False on
339    /// duplicate-add and remove-nonexistent-edge. Internal signal — the
340    /// wrapper gates reindex + vcs_commit on this; the MCP wire relies on
341    /// `write_id.is_empty()` as the external no-op indicator.
342    #[serde(skip)]
343    pub disk_changed: bool,
344    /// Stub entities that became orphaned by an edge removal (their last
345    /// incoming edge was this one) and were garbage-collected. Only
346    /// populated on `remove: true` calls where the edge actually existed;
347    /// empty on add paths and no-op removes. Empty vec is serde-omitted.
348    #[serde(default, skip_serializing_if = "Vec::is_empty")]
349    pub orphan_stubs_removed: Vec<EntityId>,
350}
351
352fn is_zero(n: &usize) -> bool {
353    *n == 0
354}
355
356/// Result of an **atomic** batch update — all-or-nothing.
357///
358/// A batch either applies in full as a single commit (`applied: true`)
359/// or, if any item fails (validation, hash mismatch, missing entity),
360/// applies *nothing* and refuses (`applied: false`) with the offending
361/// item named. There is no partial-application middle state: a refused
362/// batch leaves the on-disk mem and the in-memory store byte-identical
363/// to the pre-call state.
364#[derive(Debug, Clone, Serialize)]
365pub struct BatchResult {
366    /// Batch-level warnings. Today this carries `CONFIG_WRITE_INTERVENED`
367    /// when the mutation version stamp merged over another writer's config
368    /// change: the batch is the operation, so the batch
369    /// result is where its report belongs. Empty on the ordinary path.
370    #[serde(default, skip_serializing_if = "Vec::is_empty")]
371    pub warnings: Vec<WarningHint>,
372    /// `true` when every item applied (one commit); `false` when the
373    /// batch was refused (a single item failed → nothing committed).
374    pub applied: bool,
375    /// One entry per submitted item, in submission order. On an applied
376    /// batch every entry's `action` is `"updated"` (a real write) or
377    /// `"noop"` (content unchanged). On a refused batch the failing
378    /// item's `action` is `"error"` with a populated `error` envelope,
379    /// and every other item's `action` is `"not_applied"`.
380    pub results: Vec<BatchEntry>,
381    /// Count of applied items when `applied`; `0` when refused.
382    pub succeeded: usize,
383    /// Number of FAILING entries whose error envelopes were suppressed
384    /// beyond the reporting cap (bounded reporting for very large
385    /// failing batches — the entries still carry `action: "error"`,
386    /// only the detailed envelope is omitted). `0` when every failure
387    /// is fully reported.
388    #[serde(default, skip_serializing_if = "is_zero")]
389    pub errors_suppressed: usize,
390    /// Count of failed items when refused (≥1); `0` when applied.
391    pub failed: usize,
392    /// Ids of stub entities GC'd because a removed edge in this batch
393    /// was their last incoming reference — the batch sibling of the
394    /// single relate response's `orphan_stubs_removed`. Empty (and
395    /// serde-omitted) for batch-create / batch-update and for batches
396    /// that removed nothing.
397    #[serde(default, skip_serializing_if = "Vec::is_empty")]
398    pub orphan_stubs_removed: Vec<EntityId>,
399    /// The backend's identity for the batch's write — a commit SHA on
400    /// a git-branch mem, a synthetic token on a folder mem, and never a
401    /// change cursor. Present when the batch applied and produced at
402    /// least one write. Empty when the batch was
403    /// refused, when it was empty, or when every item was a no-op (no
404    /// commit happens). For a batch spanning multiple mems this names
405    /// the last mem committed; single-mem batches (the common case)
406    /// name their one commit.
407    #[serde(default)]
408    pub write_id: String,
409}
410
411#[derive(Debug, Clone, Serialize)]
412pub struct BatchEntry {
413    pub id: EntityId,
414    pub action: String,
415    /// Structured error envelope when this entry failed. Mirrors the
416    /// `{code, message, details}` shape single-update errors carry on
417    /// the wire so a mixed-success batch is structurally uniform —
418    /// consumers branch on `code` rather than prose-parsing a string.
419    /// Empty (`None`) for successful entries.
420    pub error: Option<BatchError>,
421}
422
423/// Per-item error envelope on a batch result. The shape matches the
424/// MCP wire envelope for single-entry failures: `code` is the stable
425/// `UPPER_SNAKE_CASE` token from [`crate::EngineError::code()`];
426/// `details` carries the variant-specific recovery payload (e.g.
427/// declared list, allowed enum values, hash-mismatch current) when
428/// available, or an empty object for variants without a structured
429/// payload.
430#[derive(Debug, Clone, Serialize)]
431pub struct BatchError {
432    pub code: String,
433    pub message: String,
434    pub details: serde_json::Value,
435}