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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//! Command shortcuts and aliases for improved CLI usability
use crate::cache::models::{CachedCommand, CachedSpec};
use crate::constants;
use crate::utils::to_kebab_case;
use std::collections::{BTreeMap, HashMap};
/// Builds the full command path for a resolved shortcut, using effective
/// display names when command mappings are active.
fn build_full_command(api_name: &str, command: &CachedCommand) -> Vec<String> {
// Use `command.name` (not `tags.first()`) for consistency with
// `engine::generator::effective_group_name` and `search::effective_command_path`.
let group = command.display_group.as_ref().map_or_else(
|| {
if command.name.is_empty() {
constants::DEFAULT_GROUP.to_string()
} else {
to_kebab_case(&command.name)
}
},
|g| to_kebab_case(g),
);
let operation = command.display_name.as_ref().map_or_else(
|| {
if command.operation_id.is_empty() {
command.method.to_lowercase()
} else {
to_kebab_case(&command.operation_id)
}
},
|n| to_kebab_case(n),
);
vec!["api".to_string(), api_name.to_string(), group, operation]
}
/// Represents a resolved command shortcut
#[derive(Debug, Clone)]
pub struct ResolvedShortcut {
/// The full command path that should be executed
pub full_command: Vec<String>,
/// The spec containing the command
pub spec: CachedSpec,
/// The resolved command
pub command: CachedCommand,
/// Confidence score (0-100, higher is better)
pub confidence: u8,
}
/// Command resolution result
#[derive(Debug)]
pub enum ResolutionResult {
/// Exact match found
Resolved(Box<ResolvedShortcut>),
/// Multiple possible matches
Ambiguous(Vec<ResolvedShortcut>),
/// No matches found
NotFound,
}
/// Command shortcut resolver
#[allow(clippy::struct_field_names)]
pub struct ShortcutResolver {
/// Map of operation IDs to specs and commands
operation_map: HashMap<String, Vec<(String, CachedSpec, CachedCommand)>>,
/// Map of HTTP method + path combinations
method_path_map: HashMap<String, Vec<(String, CachedSpec, CachedCommand)>>,
/// Map of tag-based shortcuts
tag_map: HashMap<String, Vec<(String, CachedSpec, CachedCommand)>>,
}
impl ShortcutResolver {
/// Create a new shortcut resolver
#[must_use]
pub fn new() -> Self {
Self {
operation_map: HashMap::new(),
method_path_map: HashMap::new(),
tag_map: HashMap::new(),
}
}
/// Index all available commands for shortcut resolution
pub fn index_specs(&mut self, specs: &BTreeMap<String, CachedSpec>) {
// Clear existing indexes
self.operation_map.clear();
self.method_path_map.clear();
self.tag_map.clear();
for (api_name, spec) in specs {
for command in &spec.commands {
// Index by operation ID (both original and kebab-case)
let operation_kebab = to_kebab_case(&command.operation_id);
// Original operation ID
if !command.operation_id.is_empty() {
self.operation_map
.entry(command.operation_id.clone())
.or_default()
.push((api_name.clone(), spec.clone(), command.clone()));
}
// Kebab-case operation ID
if operation_kebab != command.operation_id {
self.operation_map
.entry(operation_kebab.clone())
.or_default()
.push((api_name.clone(), spec.clone(), command.clone()));
}
// Index by HTTP method + path
let method = command.method.to_uppercase();
let path = &command.path;
let method_path_key = format!("{method} {path}");
self.method_path_map
.entry(method_path_key)
.or_default()
.push((api_name.clone(), spec.clone(), command.clone()));
// Index by display name (custom command name override)
if let Some(ref display_name) = command.display_name {
let display_kebab = to_kebab_case(display_name);
self.operation_map.entry(display_kebab).or_default().push((
api_name.clone(),
spec.clone(),
command.clone(),
));
}
// Index by aliases
for alias in &command.aliases {
let alias_kebab = to_kebab_case(alias);
self.operation_map.entry(alias_kebab).or_default().push((
api_name.clone(),
spec.clone(),
command.clone(),
));
}
// Index by tags (and display_group override)
let effective_tags: Vec<String> = command.display_group.as_ref().map_or_else(
|| command.tags.iter().map(|t| to_kebab_case(t)).collect(),
|dg| {
let mut tags: Vec<String> =
command.tags.iter().map(|t| to_kebab_case(t)).collect();
tags.push(to_kebab_case(dg));
tags
},
);
for tag_key in &effective_tags {
self.tag_map.entry(tag_key.clone()).or_default().push((
api_name.clone(),
spec.clone(),
command.clone(),
));
// Also index tag + operation combinations (with effective name)
let effective_name = command
.display_name
.as_ref()
.map_or(&operation_kebab, |n| n);
let tag_operation_key = format!("{tag_key} {}", to_kebab_case(effective_name));
self.tag_map.entry(tag_operation_key).or_default().push((
api_name.clone(),
spec.clone(),
command.clone(),
));
}
}
}
}
/// Resolve a command shortcut to full command path
///
/// # Panics
///
/// Panics if candidates is empty when exactly one match is expected.
/// This should not happen in practice due to the length check.
#[must_use]
pub fn resolve_shortcut(&self, args: &[String]) -> ResolutionResult {
if args.is_empty() {
return ResolutionResult::NotFound;
}
let mut candidates = Vec::new();
// Try different resolution strategies in order of preference
// 1. Direct operation ID match
if let Some(matches) = self.try_operation_id_resolution(args) {
candidates.extend(matches);
}
// 2. HTTP method + path resolution
if let Some(matches) = self.try_method_path_resolution(args) {
candidates.extend(matches);
}
// 3. Tag-based resolution
if let Some(matches) = self.try_tag_resolution(args) {
candidates.extend(matches);
}
// 4. Partial matching (fuzzy) - only if no candidates found yet
if candidates.is_empty() {
candidates.extend(self.try_partial_matching(args).unwrap_or_default());
}
match candidates.len() {
0 => ResolutionResult::NotFound,
1 => {
// Handle the single candidate case safely
candidates.into_iter().next().map_or_else(
|| {
// This should never happen given len() == 1, but handle defensively
// ast-grep-ignore: no-println
eprintln!("Warning: Expected exactly one candidate but found none");
ResolutionResult::NotFound
},
|candidate| ResolutionResult::Resolved(Box::new(candidate)),
)
}
_ => {
// Sort by confidence score (descending)
candidates.sort_by(|a, b| b.confidence.cmp(&a.confidence));
// Check if the top candidate has significantly higher confidence
let has_high_confidence = candidates[0].confidence >= 85
&& (candidates.len() == 1
|| candidates[0].confidence > candidates[1].confidence + 10);
if !has_high_confidence {
return ResolutionResult::Ambiguous(candidates);
}
// Handle the high-confidence candidate case safely
candidates.into_iter().next().map_or_else(
|| {
// This should never happen given we just accessed candidates[0], but handle defensively
// ast-grep-ignore: no-println
eprintln!("Warning: Expected candidates after sorting but found none");
ResolutionResult::NotFound
},
|candidate| ResolutionResult::Resolved(Box::new(candidate)),
)
}
}
}
/// Try to resolve using direct operation ID matching
fn try_operation_id_resolution(&self, args: &[String]) -> Option<Vec<ResolvedShortcut>> {
let operation_id = &args[0];
self.operation_map.get(operation_id).map(|matches| {
matches
.iter()
.map(|(api_name, spec, command)| ResolvedShortcut {
full_command: build_full_command(api_name, command),
spec: spec.clone(),
command: command.clone(),
confidence: 95, // High confidence for exact operation ID match
})
.collect()
})
}
/// Try to resolve using HTTP method + path
fn try_method_path_resolution(&self, args: &[String]) -> Option<Vec<ResolvedShortcut>> {
if args.len() < 2 {
return None;
}
let method = args[0].to_uppercase();
let path = &args[1];
let method_path_key = format!("{method} {path}");
self.method_path_map.get(&method_path_key).map(|matches| {
matches
.iter()
.map(|(api_name, spec, command)| ResolvedShortcut {
full_command: build_full_command(api_name, command),
spec: spec.clone(),
command: command.clone(),
confidence: 90, // High confidence for exact method+path match
})
.collect()
})
}
/// Try to resolve using tag-based matching
fn try_tag_resolution(&self, args: &[String]) -> Option<Vec<ResolvedShortcut>> {
let mut candidates = Vec::new();
// Try single tag lookup - convert to kebab-case for matching
let tag_kebab = to_kebab_case(&args[0]);
if let Some(matches) = self.tag_map.get(&tag_kebab) {
for (api_name, spec, command) in matches {
candidates.push(ResolvedShortcut {
full_command: build_full_command(api_name, command),
spec: spec.clone(),
command: command.clone(),
confidence: 70, // Medium confidence for tag-only match
});
}
}
// Try tag + operation combination if we have 2+ args
if args.len() < 2 {
return if candidates.is_empty() {
None
} else {
Some(candidates)
};
}
let tag = to_kebab_case(&args[0]);
let operation = to_kebab_case(&args[1]);
let tag_operation_key = format!("{tag} {operation}");
if let Some(matches) = self.tag_map.get(&tag_operation_key) {
for (api_name, spec, command) in matches {
candidates.push(ResolvedShortcut {
full_command: build_full_command(api_name, command),
spec: spec.clone(),
command: command.clone(),
confidence: 85, // Higher confidence for tag+operation match
});
}
}
if candidates.is_empty() {
None
} else {
Some(candidates)
}
}
/// Try partial matching using fuzzy logic
fn try_partial_matching(&self, args: &[String]) -> Option<Vec<ResolvedShortcut>> {
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
let matcher = SkimMatcherV2::default().ignore_case();
let query = args.join(" ");
let mut candidates = Vec::new();
// Search through operation IDs
for (operation_id, matches) in &self.operation_map {
if let Some(score) = matcher.fuzzy_match(operation_id, &query) {
for (api_name, spec, command) in matches {
candidates.push(ResolvedShortcut {
full_command: build_full_command(api_name, command),
spec: spec.clone(),
command: command.clone(),
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
confidence: std::cmp::min(60, (score / 10).max(20) as u8), // Scale fuzzy score
});
}
}
}
if candidates.is_empty() {
None
} else {
Some(candidates)
}
}
/// Generate suggestions for ambiguous matches
#[must_use]
pub fn format_ambiguous_suggestions(&self, matches: &[ResolvedShortcut]) -> String {
let mut suggestions = Vec::new();
for (i, shortcut) in matches.iter().take(5).enumerate() {
let cmd = shortcut.full_command.join(" ");
let desc = shortcut
.command
.description
.as_deref()
.unwrap_or("No description");
let num = i + 1;
suggestions.push(format!("{num}. aperture {cmd} - {desc}"));
}
format!(
"Multiple commands match. Did you mean:\n{}",
suggestions.join("\n")
)
}
}
impl Default for ShortcutResolver {
fn default() -> Self {
Self::new()
}
}