memstead_base/ops/mod.rs
1//! Operation request/response types and the gix-free read paths
2//! (`health`, `search`).
3//!
4//! Per-entity delta envelopes for `memstead_changes_since` live in
5//! [`changes`] — backend-neutral so both the git-branch tree-diff
6//! and any future folder-backend JSONL-walk produce the same shape.
7//! Wire types for the agent-notes payload live in [`agent_notes`] —
8//! pure data shapes, no gix. The producer functions
9//! (`agent_notes_since`, `read_memstead_ref`) stay in
10//! `memstead-git-branch::ops::agent_notes` because they read from a
11//! gitdir.
12//! The git-touching operation submodules (`crud`, `export`) still
13//! live in `memstead-git-branch` and are re-exported into
14//! `memstead_git_branch::ops` for downstream callers.
15
16pub mod agent_notes;
17pub mod branch_reset;
18pub mod changes;
19pub mod commit_envelope;
20pub mod coverage;
21pub mod diff;
22pub mod export;
23pub mod health;
24pub mod health_compose;
25pub mod integrity;
26pub mod labelling;
27pub mod proposal;
28pub mod redaction;
29#[cfg(not(target_arch = "wasm32"))]
30pub mod search;
31pub mod signals;
32pub mod strict;
33pub mod transport;
34
35pub use agent_notes::{AgentNotesReport, CommitNote};
36pub use branch_reset::{BranchResetOutcome, StrandedCrossMemRef};
37pub use changes::{
38 BackendChanges, ChangeEnvelope, ChangesReport, EMPTY_TREE_SHA, MemChangedNotice, NewestWrite,
39 NoticeByChange, NoticeChanges, NoticeEntry, RENAME_SIMILARITY_DEFAULT, RENAME_SIMILARITY_MAX,
40 RENAME_SIMILARITY_MIN, StoreLookup, folder_changes_since,
41};
42pub use commit_envelope::{CommitEnvelope, EntityChange};
43pub use diff::{Diff, DiffConfig, EntityDiff, IncomingRipple};
44pub use export::{MemExportBytes, MemExportError};
45pub use proposal::{
46 MergeWarning, ProposalBrief, ProposalChange, ProposalEntry, ProposalMergeOutcome,
47 ProposalRecord, render_proposal_brief, render_proposal_merge, render_proposal_record,
48};
49pub use transport::{
50 FetchOutcome, PullAllOutcome, PullOutcome, PulledRef, PushAllOutcome, PushOutcome, PushedRef,
51 QuarantinedAfterPull, RefusedRef, RemoteAddOutcome, RemoteRefState, RemoteRefStatus,
52 RemoteStatusOutcome, UnmountedRemoteMem, UpdatedRef,
53};
54
55use crate::entity::EntityId;
56use indexmap::IndexMap;
57use schemars::JsonSchema;
58use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct};
59use std::collections::HashMap;
60use std::fmt;
61
62/// Allowed `include` keys for `memstead_overview` — single source of
63/// truth shared across the MCP server and the
64/// CLI's `overview` command. Mirrors `HEALTH_INCLUDE_KEYS` for
65/// the `health` surface. The CLI `--include` flag validates against
66/// this list and surfaces `UNKNOWN_INCLUDE_KEY` warnings, matching the
67/// MCP tool's behaviour.
68pub const OVERVIEW_INCLUDE_KEYS: &[&str] = &[
69 "community_members",
70 "community_bridges",
71 "mem_distribution",
72 "dangling_links",
73];
74
75// The unknown-filter warning prose lives in the `Display` impl of the
76// typed `WarningHint::UnknownFilterKey` / `WarningHint::UnknownRangeFilterField`
77// variants below. These helpers are shared with that Display impl. They
78// are pure string formatting with no search/tantivy dependency, so they
79// live here (not in the wasm-gated `search` module) and stay available
80// on `wasm32`.
81
82/// Render the type-list clause as quoted items only — `"'X'"` for one
83/// declarer, `"'X', 'Y'"` for many — without a leading "type" /
84/// "types" word. Caller composes the leading word via
85/// [`type_word_for`] so prose contexts like `"of types ..."` don't
86/// produce the duplicate-word output `"of types types '...'"`.
87pub(crate) fn format_types_clause(types: &[String]) -> String {
88 types
89 .iter()
90 .map(|t| format!("'{t}'"))
91 .collect::<Vec<_>>()
92 .join(", ")
93}
94
95/// Leading word to pair with [`format_types_clause`]: `"type"` for a
96/// single declarer, `"types"` for many. Empty slice maps to `"types"`
97/// (callers should not invoke this for an empty list; the typed-
98/// warning sites guard the `is_empty` case already).
99pub(crate) fn type_word_for(types: &[String]) -> &'static str {
100 if types.len() == 1 { "type" } else { "types" }
101}
102
103// ---------------------------------------------------------------------------
104// Type families, cut along this file's own section headers. Each child is
105// re-exported so every `memstead_base::ops::X` path that resolved before
106// still resolves, and no consumer import changes.
107// ---------------------------------------------------------------------------
108
109mod crud;
110mod export_types;
111mod health_types;
112mod search_types;
113mod warning_hint;
114
115pub use crud::*;
116pub use export_types::*;
117pub use health_types::*;
118pub use search_types::*;
119pub use warning_hint::*;
120
121// ---------------------------------------------------------------------------
122// Context types
123// ---------------------------------------------------------------------------
124
125/// Context around an entity — neighbors, community, related entities.
126#[derive(Debug, Clone, Serialize)]
127pub struct ContextResult {
128 pub entity_id: EntityId,
129 pub community: Option<String>,
130 pub neighbors: Vec<NeighborInfo>,
131}
132
133#[derive(Debug, Clone, Serialize)]
134pub struct NeighborInfo {
135 pub id: EntityId,
136 pub title: String,
137 pub relationship: String,
138 pub direction: Direction,
139}
140
141#[derive(Debug, Clone, Serialize)]
142pub enum Direction {
143 Outgoing,
144 Incoming,
145}
146
147// ---------------------------------------------------------------------------
148// Status
149// ---------------------------------------------------------------------------
150
151/// Graph status — node / edge counts and schema distribution. Renamed from
152/// the former `Stats` when the `stats` command became `status`; the fields are unchanged so every caller's
153/// payload stays byte-compatible.
154#[derive(Debug, Clone, Serialize)]
155pub struct Status {
156 pub entity_count: usize,
157 pub edge_count: usize,
158 /// Edge count per relationship type, in name order: a `BTreeMap` so
159 /// every renderer (CLI, MCP, ui-api) emits the same bytes run after run.
160 pub edge_types: std::collections::BTreeMap<String, usize>,
161 pub community_count: usize,
162 pub mem_count: usize,
163 pub types_in_use: Vec<String>,
164}
165
166// ---------------------------------------------------------------------------
167// Reload result
168// ---------------------------------------------------------------------------
169
170#[derive(Debug, Clone, Serialize)]
171pub struct ReloadResult {
172 pub added: Vec<EntityId>,
173 pub changed: Vec<EntityId>,
174 pub removed: Vec<EntityId>,
175}
176
177/// Per-mem reload outcome — produced by [`Engine::reload_one_mem`]
178/// and surfaced verbatim in the `memstead_reload` MCP tool's response when
179/// an explicit operator-triggered reload runs against a single mem.
180/// Auto-reloads on the read path consume this internally and emit a
181/// [`WarningHint::MemReloaded`] (which carries `mem`, `old_head`,
182/// `new_head`, `entities_loaded` — the diff list is intentionally
183/// omitted from the lean warning payload; agents that need it call
184/// `memstead_changes_since` themselves with the supplied `old_head`).
185///
186/// `head_before` / `head_after` are hex-rendered SHAs (or
187/// `EMPTY_TREE_SHA` for the no-baseline case) so the wire shape
188/// matches what `memstead_changes_since` already accepts as `since`.
189/// `changed_entity_ids` is the list of non-stub IDs whose
190/// `content_hash` differs between the pre- and post-reload store
191/// snapshots, plus every newly-added or newly-removed id — same
192/// semantic as `ReloadResult { added, changed, removed }` flattened
193/// into a single set so callers don't have to merge three lists.
194#[derive(Debug, Clone, Serialize)]
195pub struct ReloadReport {
196 pub mem: String,
197 pub head_before: String,
198 pub head_after: String,
199 pub entities_loaded: usize,
200 pub changed_entity_ids: Vec<EntityId>,
201}
202
203/// What `Engine::full_refresh` changed — and, just as deliberately,
204/// what it SKIPPED. The refresh is additive-only: removals never take
205/// effect warm, and this report is how the caller learns whether its
206/// next call will succeed instead of guessing.
207#[derive(Debug, Clone, Default, Serialize)]
208pub struct FullRefreshReport {
209 /// Schema versions (`name@version`) newly resolvable.
210 pub schemas_added: Vec<String>,
211 /// In-memory schema versions absent from the re-scanned sources —
212 /// the removal was skipped; they stay resolvable until restart.
213 pub schema_removals_skipped: Vec<String>,
214 /// Mems newly mounted (cold-loaded like any boot-time mount).
215 pub mems_mounted: Vec<String>,
216 /// Mounted writable mems absent from the re-scanned roster — unmounted
217 /// atomically, no longer served (applied since 2026-09-02; the former
218 /// `mem_removals_skipped` reported them as left live until restart).
219 pub mems_unmounted: Vec<String>,
220 /// Roster entries that failed to mount and sit on the quarantine
221 /// roster with their reason.
222 pub mems_quarantined: Vec<String>,
223 /// Per-item failures: a source or mount that failed to refresh.
224 /// Failed items never surface as newly available; the others
225 /// proceed.
226 pub failures: Vec<RefreshFailure>,
227 /// Wall-clock cost of the refresh (the bounded-cost report).
228 pub elapsed_ms: u64,
229}
230
231/// One failed refresh item — `item` is `schema-source:<which>`,
232/// `mount:<mem>`, `mount-manifest`, or `workspace`.
233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
234pub struct RefreshFailure {
235 pub item: String,
236 pub error: String,
237}
238
239#[cfg(test)]
240mod tests;
241#[cfg(test)]
242mod write_id_doc_gloss_tests;