Skip to main content

memstead_base/ops/
search_types.rs

1//! Search arguments, results and facets.
2
3use super::*;
4
5// ---------------------------------------------------------------------------
6// Search types
7// ---------------------------------------------------------------------------
8
9/// Flat query shape for full-text search. Four optional fields, all
10/// combined with implicit AND across fields.
11///
12/// Within `any`: at least one term must match (OR semantics). Entities
13/// matching more terms rank higher automatically — no explicit `and`.
14/// Within `not`: none of the listed terms may appear. `phrase` requires
15/// exact adjacency (case- and diacritic-folded). `field` narrows the match
16/// region for all three to a single indexed field; `None` = match anywhere
17/// indexed.
18///
19/// Empty/unset everywhere ⇒ no text predicate; `search` behaves as a
20/// metadata-only filter (subsumes the former `list` semantics).
21///
22/// No stemming, wildcards, or regex — the caller expands morphology and
23/// synonyms by enumerating variants in `any`.
24#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
25pub struct Query {
26    /// Terms where at least one must match (OR semantics).
27    #[serde(default, skip_serializing_if = "Vec::is_empty")]
28    pub any: Vec<String>,
29    /// Terms that must not match (exclusion).
30    #[serde(default, skip_serializing_if = "Vec::is_empty")]
31    pub not: Vec<String>,
32    /// Exact phrase that must appear (case- and diacritic-folded).
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub phrase: Option<String>,
35    /// Restrict `any` / `not` / `phrase` to a single field (title or section
36    /// key). `None` = match anywhere indexed.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub field: Option<String>,
39}
40
41impl Query {
42    /// True if no text predicate is set — caller falls back to the
43    /// metadata-only filter path.
44    pub fn is_empty(&self) -> bool {
45        self.any.is_empty() && self.not.is_empty() && self.phrase.is_none()
46    }
47}
48
49/// Scope filters for search and list operations.
50#[derive(Debug, Clone, Default)]
51pub struct SearchScope {
52    /// Structured flat query. All text matching flows through this field;
53    /// see [`Query`] for semantics. `None` (or an empty query) makes
54    /// `search` behave as a metadata-only filter.
55    pub query: Option<Query>,
56    pub mem: Option<String>,
57    pub entity_type: Option<String>,
58    pub limit: Option<usize>,
59    pub offset: Option<usize>,
60    /// Equality filters on metadata fields: `{ "level": "M0" }`.
61    pub filters: HashMap<String, String>,
62    /// Range filters: `{ "min_coverage": "0.5", "max_coverage": "1.0" }`.
63    pub range_filters: HashMap<String, String>,
64    /// Only entities with this edge type (incoming or outgoing).
65    pub edge_type: Option<String>,
66    /// Only entities reachable from this entity within `depth` hops.
67    pub related_to: Option<EntityId>,
68    pub depth: Option<usize>,
69    /// Relationship types to follow from primary hits to pull in graph-proximal
70    /// neighbours.
71    pub expand_via: Option<Vec<String>>,
72    /// Maximum hops to traverse via `expand_via` (default: 1 when `expand_via`
73    /// is set).
74    pub expand_depth: Option<usize>,
75    /// Traversal direction for `related_to` AND `expand_via`, applied at
76    /// EVERY hop (depth > 1 is a pure transitive closure in the chosen
77    /// direction, never a mixed walk). Defaults to `both` — the
78    /// historical undirected behaviour, so a query omitting the
79    /// selector returns exactly what it always returned.
80    pub direction: crate::graph::query::TraversalDirection,
81    /// Filter by stub status. `None` = no filter (returns both stubs and real
82    /// entities); `Some(true)` = only stubs; `Some(false)` = only real entities.
83    pub stub: Option<bool>,
84    /// Token budget bounding the returned hit payload (search path only).
85    /// `None` uses the engine default. A page whose hits exceed the budget is
86    /// greedily trimmed (at least one hit always returns) with a
87    /// `SEARCH_RESULTS_TRUNCATED` warning; `total` still reflects the full
88    /// match count so the agent can page with `offset`.
89    pub token_budget: Option<usize>,
90}
91
92/// Per-hit score components surfaced so agents can understand ranking.
93///
94/// Note: this is illustrative feedback, not a numerically authoritative
95/// decomposition — tantivy's `Explanation` for `BoostQuery` over
96/// `BooleanQuery` does not always sum cleanly. Agents should treat these
97/// as proportions, not exact sums.
98#[derive(Debug, Clone, Serialize, JsonSchema)]
99pub struct ScoreBreakdown {
100    pub bm25: f32,
101    pub title_boost: f32,
102    pub field_weights: HashMap<String, f32>,
103    /// `Some(f32)` on expanded hits only, carrying the depth-based decay
104    /// factor (`0.5.powi(depth)`). `None` on primary hits.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub expansion_decay: Option<f32>,
107}
108
109/// One snippet-level match recorded per (term, field). `heading_path` is
110/// `Some` when the match falls under an H3–H6 sub-heading; elements are
111/// ordered outermost → innermost.
112#[derive(Debug, Clone, Serialize, JsonSchema)]
113pub struct TermMatch {
114    pub field: String,
115    pub snippet: String,
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub heading_path: Option<Vec<String>>,
118}
119
120/// Metadata attached to hits reached via graph expansion. The
121/// primary hit that seeded the expansion is identified by `of`; `via_edge`
122/// is the exact `rel_type` string; `depth` counts hops from the seed.
123#[derive(Debug, Clone, Serialize, JsonSchema)]
124pub struct ExpansionInfo {
125    pub of: EntityId,
126    pub via_edge: String,
127    pub depth: usize,
128    /// The direction the first-reaching edge was traversed in (`out` =
129    /// away from the seed, `in` = at the seed) — keeps a `both` result
130    /// interpretable. Additive: clients that ignore it decode unchanged.
131    pub via_direction: crate::graph::query::TraversalDirection,
132}
133
134/// One sub-section-level facet entry. `path` is ordered outermost →
135/// innermost, prefixed with the H2 section key (e.g. `["specifies",
136/// "Response Shapes", "Markdown Output"]`). Structured vector (not a
137/// delimiter-joined string) so headings containing punctuation don't break
138/// the key.
139#[derive(Debug, Clone, Serialize, JsonSchema)]
140pub struct SubsectionFacet {
141    pub path: Vec<String>,
142    pub count: usize,
143}
144
145/// Fixed set of facet dimensions computed over the unpaginated hit set.
146/// Tier 1 freezes the dimensions; extend later only if empirical use
147/// demands it. Zero-count entries are excluded to keep the payload small.
148#[derive(Debug, Clone, Default, Serialize, JsonSchema)]
149pub struct Facets {
150    pub by_type: HashMap<String, usize>,
151    pub by_mem: HashMap<String, usize>,
152    pub by_level: HashMap<String, usize>,
153    pub by_status: HashMap<String, usize>,
154    pub by_confidence: HashMap<String, usize>,
155    pub by_subsection: Vec<SubsectionFacet>,
156    /// `"primary"` / `"expanded"` — counts of primary vs. graph-expanded
157    /// hits. Always present; `expanded` is `0` when no expansion ran.
158    pub by_expansion: HashMap<String, usize>,
159}
160
161/// A search result hit.
162#[derive(Debug, Clone, Serialize)]
163pub struct SearchHit {
164    pub id: EntityId,
165    pub title: String,
166    pub mem: String,
167    pub entity_type: String,
168    pub stub: bool,
169    pub score: f32,
170    pub tokens: usize,
171    /// The entity's `last_modified` stamp (RFC-3339 date) — list/roster
172    /// consumers (the app's Liste, agents asking "what moved lately")
173    /// sort on it without per-entity reads. `None` for stubs and hits
174    /// built outside the engine ops.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub last_modified: Option<String>,
177    pub snippet: Option<String>,
178    /// Lead/key section bodies for the hit. The `search` op leaves this
179    /// **empty** — search finds entities, `memstead_entity` reads their
180    /// bodies; carrying every required section per hit overflowed the MCP
181    /// transport cap. The `list` op still populates it (its human-facing
182    /// roster consumers read the lead section as a one-line summary).
183    /// Empty maps are omitted from the serialized envelope.
184    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
185    pub sections: HashMap<String, String>,
186    /// Score component breakdown — populated when the call supplied a
187    /// text predicate; `None` on the metadata-only path. Always on the
188    /// wire (as `null` when absent): the envelope the `memstead_search`
189    /// description promises is one stable shape, so a consumer reads
190    /// the key and branches on its value, never on its presence.
191    #[serde(default)]
192    pub score_breakdown: Option<ScoreBreakdown>,
193    /// Per-term match details keyed by query term — populated when the
194    /// call supplied a text predicate; `None` on the metadata-only path.
195    /// Always on the wire, as `score_breakdown` is.
196    #[serde(default)]
197    pub matched_terms: Option<HashMap<String, Vec<TermMatch>>>,
198    /// Expansion metadata — populated on hits reached via graph
199    /// expansion; `None` on primary hits. Always on the wire, as
200    /// `score_breakdown` is.
201    #[serde(default)]
202    pub expansion: Option<ExpansionInfo>,
203    /// Lead-section summary resolved against the hit's *own* mem schema
204    /// at search time (see [`SummaryPair`]). The renderer cannot resolve
205    /// it correctly on its own — the global `type_by_name` only sees the
206    /// `default` schema, so a `software`-schema hit (`requirement` →
207    /// `Statement`, `actor` → `Role`) would miss its anchor section and
208    /// render `—`. `#[serde(skip)]` keeps `SearchHit`'s wire shape
209    /// unchanged; the value surfaces on the envelope's `summary_heading` /
210    /// `summary_value`. `None` only on hits built outside the engine
211    /// search op (FFI/bridge and test fixtures), where the renderer falls
212    /// back to the default-schema lookup.
213    #[serde(skip)]
214    pub summary: Option<SummaryPair>,
215}
216
217/// Lead-section `(heading, value)` for a search/list hit, resolved
218/// against the hit's own mem schema at search time. Carried in-memory
219/// from the search op to the renderers; see [`SearchHit::summary`].
220#[derive(Debug, Clone)]
221pub struct SummaryPair {
222    pub heading: String,
223    pub value: String,
224}
225
226/// Search result with metadata.
227#[derive(Debug, Clone, Serialize)]
228pub struct SearchResult {
229    pub total: usize,
230    pub returned: usize,
231    pub offset: usize,
232    /// Sum of estimated tokens across all matching entities (pre-pagination).
233    /// Lets agents judge read cost before paging.
234    pub total_tokens: usize,
235    pub hits: Vec<SearchHit>,
236    /// Faceted counts over the unpaginated hit set. Stable closed
237    /// struct; zero-count entries are excluded.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub facets: Option<Facets>,
240    /// Non-fatal issues surfaced to the caller. Structured
241    /// `WarningHint` shape (`{code, details, message}`) — same wire
242    /// envelope every other tool's warnings already use. Agents
243    /// branch on `code`; the message field carries the existing
244    /// remediation prose.
245    #[serde(default, skip_serializing_if = "Vec::is_empty")]
246    pub warnings: Vec<WarningHint>,
247}
248
249/// List result with token totals.
250#[derive(Debug, Clone, Serialize)]
251pub struct ListResult {
252    pub total: usize,
253    pub returned: usize,
254    pub offset: usize,
255    pub total_tokens: usize,
256    pub hits: Vec<SearchHit>,
257    /// Non-fatal issues surfaced to the caller — same structured
258    /// shape as `SearchResult.warnings`.
259    #[serde(default, skip_serializing_if = "Vec::is_empty")]
260    pub warnings: Vec<WarningHint>,
261}