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