1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use std::collections::HashMap;
use clap::Parser;
use memstead_base::EntityId;
use memstead_base::ops::{Query, SearchScope};
use memstead_base::render;
use crate::output::{print_json, print_markdown};
use crate::setup::{CliContext, CliEngine};
/// Find entities by text or graph proximity.
#[derive(Parser, Debug)]
#[command(after_long_help = super::FILTER_HELP)]
pub struct Args {
/// Free-text query. Omit for a pure structural filter.
pub text: Option<String>,
#[arg(long)]
pub mem: Option<String>,
#[arg(long = "type")]
pub entity_type: Option<String>,
/// Restrict text matching to a single field (title or section key).
/// Maps to `Query.field` — narrows `any`, `not`, and `phrase` for the
/// query. Replaces the former repeatable plural form, which was orphaned
/// at the engine level.
#[arg(long = "field")]
pub field: Option<String>,
/// Exclude entities whose text matches this token. Repeatable —
/// `--exclude OAuth --exclude SAML` drops every hit driven by
/// either. Maps to `Query.not`. When combined with `--field`, the
/// exclude scopes to that field via the engine's existing
/// `Query.field` semantics.
///
/// Example: `memstead search auth --exclude OAuth` returns
/// "auth"-matching entities that are not driven by an `OAuth`
/// match.
#[arg(long = "exclude", value_name = "TOKEN")]
pub exclude: Vec<String>,
/// Restrict hits to entities containing this exact phrase
/// (adjacency-sensitive). Maps to `Query.phrase`. Composable with
/// `--field` (narrows the phrase match to one field) and
/// `--exclude` (drops phrase-matching hits that also match the
/// excluded token). Shell quoting is stripped before the binary
/// sees the positional text argument — use this flag rather than
/// quoting in the positional to express adjacency.
#[arg(long = "phrase", value_name = "TEXT")]
pub phrase: Option<String>,
/// Filter by edge type (e.g. USES, IMPLEMENTS).
#[arg(long)]
pub edge_type: Option<String>,
/// Only entities within `--depth` hops of this ID.
#[arg(long)]
pub related_to: Option<String>,
#[arg(long)]
pub depth: Option<usize>,
#[arg(long)]
pub limit: Option<usize>,
#[arg(long)]
pub offset: Option<usize>,
#[arg(long)]
pub level: Option<String>,
#[arg(long)]
pub status: Option<String>,
/// Equality filter on any schema-declared filterable field:
/// repeatable `--filter KEY=VALUE`. The four named-flag
/// shortcuts (`--type` / `--level` / `--status` / `--edge-type`)
/// handle their common cases; every other `filterable: equality`
/// field (e.g. `tags`, `scope`) is reachable via this generic
/// flag. Unknown keys are dropped and surface as engine
/// warnings. There is no `--confidence` shortcut: a field reached
/// only when a schema declares it goes through
/// `--filter <field>=<value>` rather than a dedicated flag.
#[arg(long = "filter", value_name = "KEY=VALUE")]
pub filter: Vec<String>,
/// Range filter on any `filterable: range` field: repeatable
/// `--range-filter KEY=VALUE` with the same key grammar as the MCP
/// `range_filters` map — `min_<field>` / `max_<field>` for numbers,
/// `<field>_after` / `<field>_before` for dates. The strings go to
/// the same engine path the MCP tool uses, so the same four outcome
/// codes apply with the same meaning: `RANGE_FILTER_KEY_MALFORMED`
/// (key ignored), `UNKNOWN_RANGE_FILTER_FIELD` (no type declares
/// the field — results stay unfiltered), `RANGE_FILTER_TYPE_SCOPED`
/// (other types declare it — applied with strict type-narrowing),
/// `FIELD_NOT_RANGE_FILTERABLE` (declared, but not `filterable:
/// range`). Composable with `--filter` and the named shortcuts.
#[arg(long = "range-filter", value_name = "KEY=VALUE")]
pub range_filter: Vec<String>,
/// Relationship types to follow from primary hits to pull in
/// graph-proximal neighbours: repeatable `--expand-via REL_TYPE`.
/// Mirrors the MCP `expand_via` parameter — expanded hits carry
/// `expansion: { of, via_edge, via_direction, depth }` and a
/// decayed score (0.5^depth).
#[arg(long = "expand-via", value_name = "REL_TYPE")]
pub expand_via: Vec<String>,
/// Max hops to traverse via `--expand-via` (default: 1). Mirrors
/// the MCP `expand_depth` parameter.
#[arg(long = "expand-depth", value_name = "N")]
pub expand_depth: Option<usize>,
/// Traversal direction for `--related-to` and `--expand-via`,
/// applied at EVERY hop: `out` follows edges pointing away from
/// the seed (what does this rest on), `in` follows edges pointing
/// at it (what rests on this), `both` (default) is the historical
/// undirected walk. Depth > 1 is a pure transitive closure in the
/// chosen direction — never a mixed walk.
#[arg(long, value_enum, default_value_t = DirectionArg::Both)]
pub direction: DirectionArg,
/// Return only stub entities (conflicts with --no-stub).
#[arg(long, conflicts_with = "no_stub")]
pub stub: bool,
/// Return only real (non-stub) entities (conflicts with --stub).
#[arg(long, conflicts_with = "stub")]
pub no_stub: bool,
}
/// CLI form of the traversal-direction selector. clap's `ValueEnum`
/// refuses an unrecognised value with a typed error naming the
/// accepted values — never a silent fallback to `both`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum DirectionArg {
Out,
In,
Both,
}
impl From<DirectionArg> for memstead_base::graph::query::TraversalDirection {
fn from(d: DirectionArg) -> Self {
match d {
DirectionArg::Out => Self::Out,
DirectionArg::In => Self::In,
DirectionArg::Both => Self::Both,
}
}
}
pub fn run(ctx: &CliContext, args: Args) -> anyhow::Result<()> {
let mut filters = HashMap::new();
if let Some(level) = args.level {
filters.insert("level".to_string(), level);
}
if let Some(status) = args.status {
filters.insert("status".to_string(), status);
}
for raw in &args.filter {
let (key, value) = super::parse_filter_arg(raw)?;
filters.insert(key, value);
}
// Range filters: the CLI only splits KEY=VALUE — the key grammar
// (`min_*` / `max_*` / `*_before` / `*_after`) is parsed by the
// same engine path the MCP `range_filters` map goes through, so
// the typed outcome codes are identical on both surfaces. A
// second grammar parser here is a defect.
let mut range_filters = HashMap::new();
for raw in &args.range_filter {
let (key, value) = super::parse_filter_arg(raw)?;
range_filters.insert(key, value);
}
// Wrap a positional CLI text argument into the flat Query shape. Each
// whitespace-separated token becomes an `any` term (OR semantics). Empty
// or missing `text` falls through to the metadata-only filter path.
// `--field` (when set) narrows the query to a single field via
// `Query.field`. `--exclude` (repeatable) routes each token into
// `Query.not` for the engine's exclude predicate. `--phrase` routes
// into `Query.phrase` for adjacency-sensitive matching. Either positional
// text or `--phrase` triggers Query construction; pure `--field` or
// `--exclude` without a text/phrase predicate fall through to the
// metadata-only filter path.
let any: Vec<String> = args
.text
.as_deref()
.map(|t| t.split_whitespace().map(|s| s.to_string()).collect())
.unwrap_or_default();
let query = if any.is_empty() && args.phrase.is_none() {
None
} else {
Some(Query {
any,
not: args.exclude.clone(),
field: args.field.clone(),
phrase: args.phrase.clone(),
})
};
let stub = match (args.stub, args.no_stub) {
(true, _) => Some(true),
(_, true) => Some(false),
_ => None,
};
let scope = SearchScope {
query,
mem: args.mem,
entity_type: args.entity_type,
limit: args.limit,
offset: args.offset,
filters,
range_filters,
edge_type: args.edge_type,
related_to: args.related_to.map(EntityId),
depth: args.depth,
expand_via: if args.expand_via.is_empty() {
None
} else {
Some(args.expand_via.clone())
},
expand_depth: args.expand_depth,
direction: args.direction.into(),
stub,
token_budget: None,
};
let result = match ctx.cli_engine()? {
#[cfg(feature = "mem-repo")]
CliEngine::MemRepo(engine) => {
if let Some(name) = scope.mem.as_deref()
&& engine.mount(name).is_none()
{
return Err(super::list::unknown_mem_error(name, &engine).into());
}
engine.search(&scope)?
}
CliEngine::Filesystem(engine) => {
if let Some(name) = scope.mem.as_deref()
&& engine.mount(name).is_none()
{
return Err(super::list::unknown_mem_error(name, &engine).into());
}
engine.search(&scope)?
}
};
let offset = scope.offset.unwrap_or(0);
if ctx.json {
let envelope = render::build_search_envelope(&result, offset);
print_json(&envelope)?;
} else {
print_markdown(&render::render_search_markdown(&result, offset));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
/// There is no `--confidence` flag: the CLI parser doesn't
/// recognise it — agents pass `--filter confidence=<value>`
/// instead, which works for any schema that declares the field.
#[test]
fn search_rejects_removed_confidence_flag() {
let parsed = Args::try_parse_from(["search", "--confidence", "high"]);
assert!(
parsed.is_err(),
"--confidence must be removed from the CLI parser",
);
let err = parsed.unwrap_err();
// clap's "unknown argument" diagnostic shape — substrings
// present across clap minor versions.
let msg = err.to_string();
assert!(
msg.contains("--confidence") || msg.contains("unexpected"),
"expected clap unknown-argument diagnostic, got: {msg}",
);
}
/// The four remaining named-flag shortcuts still parse.
#[test]
fn search_accepts_remaining_named_shortcuts() {
let parsed = Args::try_parse_from([
"search",
"--type",
"spec",
"--level",
"M0",
"--status",
"active",
"--edge-type",
"USES",
]);
assert!(
parsed.is_ok(),
"remaining shortcuts must still parse: {:?}",
parsed.err()
);
}
/// `--filter confidence=high` parses via the generic filter
/// path, which covers any schema that declares the field.
#[test]
fn search_filter_confidence_still_parses() {
let parsed = Args::try_parse_from(["search", "--filter", "confidence=high"]);
assert!(
parsed.is_ok(),
"--filter confidence=high must parse: {:?}",
parsed.err()
);
let args = parsed.unwrap();
assert!(
args.filter.iter().any(|f| f.contains("confidence")),
"filter list must carry the generic confidence pair: {:?}",
args.filter,
);
}
}