osp-cli 1.5.1

CLI and REPL for querying and managing OSP infrastructure data
Documentation
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
use super::adapter::{ReplCompleter, ReplHistoryCompleter};
use super::config::{DEFAULT_HISTORY_MENU_ROWS, ReplAppearance};
use super::overlay::{build_completion_menu, build_history_menu};
use super::{HISTORY_MENU_NAME, SharedHistory};
use crate::completion::{CompletionEngine, CompletionTree};
use crate::repl::menu::{
    MenuDebug, MenuStyleDebug, OspCompletionMenu, debug_snapshot, display_text,
};
use reedline::{Completer, Editor, Menu, MenuEvent, UndoBehavior};
use serde::Serialize;

/// One rendered completion entry in the debug surface.
#[derive(Debug, Clone, Serialize)]
pub struct CompletionDebugMatch {
    /// Stable completion identifier or inserted value.
    pub id: String,
    /// Primary rendered label for the suggestion.
    pub label: String,
    /// Optional secondary description for the suggestion.
    pub description: Option<String>,
    /// Classified suggestion kind used by the debug view.
    pub kind: String,
}

/// Snapshot of completion/menu state for a given line and cursor position.
///
/// This is primarily consumed by REPL debug commands and tests.
#[derive(Debug, Clone, Serialize)]
pub struct CompletionDebug {
    /// Original input line.
    pub line: String,
    /// Cursor position used for analysis.
    pub cursor: usize,
    /// Replacement byte range for the active suggestion set.
    pub replace_range: [usize; 2],
    /// Current completion stub under the cursor.
    pub stub: String,
    /// Candidate matches visible to the menu.
    pub matches: Vec<CompletionDebugMatch>,
    /// Selected match index, or `-1` when no match is selected.
    pub selected: i64,
    /// Selected menu row.
    pub selected_row: u16,
    /// Selected menu column.
    pub selected_col: u16,
    /// Number of menu columns.
    pub columns: u16,
    /// Number of menu rows.
    pub rows: u16,
    /// Number of visible menu rows after clipping.
    pub visible_rows: u16,
    /// Menu indentation used for rendering.
    pub menu_indent: u16,
    /// Effective menu style snapshot.
    pub menu_styles: MenuStyleDebug,
    /// Optional selected-item description.
    pub menu_description: Option<String>,
    /// Rendered description as shown in the menu.
    pub menu_description_rendered: Option<String>,
    /// Virtual render width.
    pub width: u16,
    /// Virtual render height.
    pub height: u16,
    /// Whether Unicode menu chrome was enabled.
    pub unicode: bool,
    /// Whether ANSI styling was enabled.
    pub color: bool,
    /// Rendered menu lines captured for debugging.
    pub rendered: Vec<String>,
}

/// Synthetic editor action used by completion-debug stepping.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebugStep {
    /// Advance to the next item or open the menu.
    Tab,
    /// Move to the previous item.
    BackTab,
    /// Move selection upward.
    Up,
    /// Move selection downward.
    Down,
    /// Move selection left.
    Left,
    /// Move selection right.
    Right,
    /// Accept the selected item.
    Accept,
    /// Close the completion menu.
    Close,
}

impl DebugStep {
    /// Parses a step name accepted by REPL debug commands.
    pub fn parse(raw: &str) -> Option<Self> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "tab" => Some(Self::Tab),
            "backtab" | "shift-tab" | "shift_tab" => Some(Self::BackTab),
            "up" => Some(Self::Up),
            "down" => Some(Self::Down),
            "left" => Some(Self::Left),
            "right" => Some(Self::Right),
            "accept" | "enter" => Some(Self::Accept),
            "close" | "esc" | "escape" => Some(Self::Close),
            _ => None,
        }
    }

    /// Returns the stable lowercase name used in debug payloads.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Tab => "tab",
            Self::BackTab => "backtab",
            Self::Up => "up",
            Self::Down => "down",
            Self::Left => "left",
            Self::Right => "right",
            Self::Accept => "accept",
            Self::Close => "close",
        }
    }
}

/// One frame from a stepped completion-debug session.
#[derive(Debug, Clone, Serialize)]
pub struct CompletionDebugFrame {
    /// Synthetic step that produced this frame.
    pub step: String,
    /// Captured completion state after the step.
    pub state: CompletionDebug,
}

/// Rendering and capture options for completion-debug helpers.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
#[must_use]
pub struct CompletionDebugOptions<'a> {
    /// Virtual render width for the debug menu.
    pub width: u16,
    /// Virtual render height for the debug menu.
    pub height: u16,
    /// Whether ANSI styling should be enabled in captured output.
    pub ansi: bool,
    /// Whether Unicode menu chrome should be enabled in captured output.
    pub unicode: bool,
    /// Optional appearance override used for the debug session.
    pub appearance: Option<&'a ReplAppearance>,
}

impl<'a> CompletionDebugOptions<'a> {
    /// Creates a new debug snapshot configuration for a virtual terminal size.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::repl::CompletionDebugOptions;
    ///
    /// let options = CompletionDebugOptions::new(100, 12)
    ///     .with_ansi(true)
    ///     .with_unicode(true);
    ///
    /// assert_eq!(options.width, 100);
    /// assert_eq!(options.height, 12);
    /// assert!(options.ansi);
    /// assert!(options.unicode);
    /// ```
    pub fn new(width: u16, height: u16) -> Self {
        Self {
            width,
            height,
            ansi: false,
            unicode: false,
            appearance: None,
        }
    }

    /// Enables ANSI styling in captured menu output.
    pub fn with_ansi(mut self, ansi: bool) -> Self {
        self.ansi = ansi;
        self
    }

    /// Selects unicode or ASCII menu chrome when rendering debug output.
    pub fn with_unicode(mut self, unicode: bool) -> Self {
        self.unicode = unicode;
        self
    }

    /// Applies REPL appearance overrides to the debug menu session.
    pub fn with_appearance(mut self, appearance: Option<&'a ReplAppearance>) -> Self {
        self.appearance = appearance;
        self
    }
}

/// Builds a single completion-debug snapshot for `line` at `cursor`.
pub fn debug_completion(
    tree: &CompletionTree,
    line: &str,
    cursor: usize,
    options: CompletionDebugOptions<'_>,
) -> CompletionDebug {
    let (editor, mut completer, mut menu) =
        build_debug_completion_session(tree, line, cursor, options.appearance);
    let mut editor = editor;

    menu.menu_event(MenuEvent::Activate(false));
    menu.apply_event(&mut editor, completer.as_mut());

    snapshot_completion_debug(
        tree,
        &mut menu,
        &editor,
        options.width,
        options.height,
        options.ansi,
        options.unicode,
    )
}

/// Builds a single history-menu debug snapshot for `line` at `cursor`.
pub fn debug_history_menu(
    history: &SharedHistory,
    line: &str,
    cursor: usize,
    options: CompletionDebugOptions<'_>,
) -> CompletionDebug {
    let (editor, mut completer, mut menu) =
        build_debug_history_session(history, line, cursor, options.appearance);
    let mut editor = editor;

    menu.menu_event(MenuEvent::Activate(false));
    menu.apply_event(&mut editor, completer.as_mut());

    snapshot_history_debug(
        &mut menu,
        &editor,
        cursor,
        options.width,
        options.height,
        options.ansi,
        options.unicode,
    )
}

/// Replays a sequence of synthetic editor actions and captures each frame.
pub fn debug_completion_steps(
    tree: &CompletionTree,
    line: &str,
    cursor: usize,
    options: CompletionDebugOptions<'_>,
    steps: &[DebugStep],
) -> Vec<CompletionDebugFrame> {
    let (mut editor, mut completer, mut menu) =
        build_debug_completion_session(tree, line, cursor, options.appearance);

    let steps = steps.to_vec();
    if steps.is_empty() {
        return Vec::new();
    }

    let mut frames = Vec::with_capacity(steps.len());
    for step in steps {
        apply_debug_step(step, &mut menu, &mut editor, completer.as_mut());
        let state = snapshot_completion_debug(
            tree,
            &mut menu,
            &editor,
            options.width,
            options.height,
            options.ansi,
            options.unicode,
        );
        frames.push(CompletionDebugFrame {
            step: step.as_str().to_string(),
            state,
        });
    }

    frames
}

/// Replays synthetic editor actions for the history menu and captures each frame.
pub fn debug_history_menu_steps(
    history: &SharedHistory,
    line: &str,
    cursor: usize,
    options: CompletionDebugOptions<'_>,
    steps: &[DebugStep],
) -> Vec<CompletionDebugFrame> {
    let (mut editor, mut completer, mut menu) =
        build_debug_history_session(history, line, cursor, options.appearance);

    let steps = steps.to_vec();
    if steps.is_empty() {
        return Vec::new();
    }

    let mut frames = Vec::with_capacity(steps.len());
    for step in steps {
        apply_debug_step(step, &mut menu, &mut editor, completer.as_mut());
        let state = snapshot_history_debug(
            &mut menu,
            &editor,
            cursor,
            options.width,
            options.height,
            options.ansi,
            options.unicode,
        );
        frames.push(CompletionDebugFrame {
            step: step.as_str().to_string(),
            state,
        });
    }

    frames
}

fn build_debug_completion_session(
    tree: &CompletionTree,
    line: &str,
    cursor: usize,
    appearance: Option<&ReplAppearance>,
) -> (Editor, Box<dyn Completer>, OspCompletionMenu) {
    let mut editor = Editor::default();
    editor.edit_buffer(
        |buf| {
            buf.set_buffer(line.to_string());
            buf.set_insertion_point(cursor.min(buf.get_buffer().len()));
        },
        UndoBehavior::CreateUndoPoint,
    );

    let completer = Box::new(ReplCompleter::new(Vec::new(), Some(tree.clone()), None));
    let menu = if let Some(appearance) = appearance {
        build_completion_menu(appearance)
    } else {
        OspCompletionMenu::default()
    };

    (editor, completer, menu)
}

fn build_debug_history_session(
    history: &SharedHistory,
    line: &str,
    cursor: usize,
    appearance: Option<&ReplAppearance>,
) -> (Editor, Box<dyn Completer>, OspCompletionMenu) {
    let mut editor = Editor::default();
    editor.edit_buffer(
        |buf| {
            buf.set_buffer(line.to_string());
            buf.set_insertion_point(cursor.min(buf.get_buffer().len()));
        },
        UndoBehavior::CreateUndoPoint,
    );

    let completer = Box::new(ReplHistoryCompleter::new(history.clone()));
    let menu = if let Some(appearance) = appearance {
        build_history_menu(appearance)
    } else {
        OspCompletionMenu::default()
            .with_name(HISTORY_MENU_NAME)
            .with_quick_complete(false)
            .with_columns(1)
            .with_max_rows(DEFAULT_HISTORY_MENU_ROWS)
    };

    (editor, completer, menu)
}

fn apply_debug_step(
    step: DebugStep,
    menu: &mut OspCompletionMenu,
    editor: &mut Editor,
    completer: &mut dyn Completer,
) {
    match step {
        DebugStep::Tab => {
            if menu.is_active() {
                dispatch_menu_event(menu, editor, completer, MenuEvent::NextElement);
            } else {
                dispatch_menu_event(menu, editor, completer, MenuEvent::Activate(false));
            }
        }
        DebugStep::BackTab => {
            if menu.is_active() {
                dispatch_menu_event(menu, editor, completer, MenuEvent::PreviousElement);
            } else {
                dispatch_menu_event(menu, editor, completer, MenuEvent::Activate(false));
            }
        }
        DebugStep::Up => {
            if menu.is_active() {
                dispatch_menu_event(menu, editor, completer, MenuEvent::MoveUp);
            }
        }
        DebugStep::Down => {
            if menu.is_active() {
                dispatch_menu_event(menu, editor, completer, MenuEvent::MoveDown);
            }
        }
        DebugStep::Left => {
            if menu.is_active() {
                dispatch_menu_event(menu, editor, completer, MenuEvent::MoveLeft);
            }
        }
        DebugStep::Right => {
            if menu.is_active() {
                dispatch_menu_event(menu, editor, completer, MenuEvent::MoveRight);
            }
        }
        DebugStep::Accept => {
            if menu.is_active() {
                menu.accept_selection_in_buffer(editor);
                dispatch_menu_event(menu, editor, completer, MenuEvent::Deactivate);
            }
        }
        DebugStep::Close => {
            dispatch_menu_event(menu, editor, completer, MenuEvent::Deactivate);
        }
    }
}

fn dispatch_menu_event(
    menu: &mut OspCompletionMenu,
    editor: &mut Editor,
    completer: &mut dyn Completer,
    event: MenuEvent,
) {
    menu.menu_event(event);
    menu.apply_event(editor, completer);
}

fn snapshot_completion_debug(
    tree: &CompletionTree,
    menu: &mut OspCompletionMenu,
    editor: &Editor,
    width: u16,
    height: u16,
    ansi: bool,
    unicode: bool,
) -> CompletionDebug {
    let line = editor.get_buffer().to_string();
    let cursor = editor.line_buffer().insertion_point();
    let values = menu.get_values();
    let engine = CompletionEngine::new(tree.clone());
    let analysis = engine.analyze(&line, cursor);

    let (stub, replace_range) = if let Some(first) = values.first() {
        let start = first.span.start;
        let end = first.span.end;
        let stub = line.get(start..end).unwrap_or("").to_string();
        (stub, [start, end])
    } else {
        (
            analysis.cursor.raw_stub.clone(),
            [
                analysis.cursor.replace_range.start,
                analysis.cursor.replace_range.end,
            ],
        )
    };

    let matches = values
        .iter()
        .map(|item| CompletionDebugMatch {
            id: item.value.clone(),
            label: display_text(item).to_string(),
            description: item.description.clone(),
            kind: engine
                .classify_match(&analysis, &item.value)
                .as_str()
                .to_string(),
        })
        .collect::<Vec<_>>();

    let MenuDebug {
        columns,
        rows,
        visible_rows,
        indent,
        selected_index,
        selected_row,
        selected_col,
        description,
        description_rendered,
        styles,
        rendered,
    } = debug_snapshot(menu, editor, width, height, ansi);

    let selected = if matches.is_empty() {
        -1
    } else {
        selected_index
    };

    CompletionDebug {
        line,
        cursor,
        replace_range,
        stub,
        matches,
        selected,
        selected_row,
        selected_col,
        columns,
        rows,
        visible_rows,
        menu_indent: indent,
        menu_styles: styles,
        menu_description: description,
        menu_description_rendered: description_rendered,
        width,
        height,
        unicode,
        color: ansi,
        rendered,
    }
}

fn snapshot_history_debug(
    menu: &mut OspCompletionMenu,
    editor: &Editor,
    cursor: usize,
    width: u16,
    height: u16,
    ansi: bool,
    unicode: bool,
) -> CompletionDebug {
    let line = editor.get_buffer().to_string();
    let cursor = cursor
        .min(editor.line_buffer().insertion_point())
        .min(line.len());
    let values = menu.get_values();
    let query = line.get(..cursor).unwrap_or(&line).trim().to_string();

    let (stub, replace_range) = if let Some(first) = values.first() {
        let start = first.span.start;
        let end = first.span.end;
        let stub = line.get(start..end).unwrap_or("").to_string();
        (stub, [start, end])
    } else {
        (query, [0, line.len()])
    };

    let matches = values
        .iter()
        .map(|item| CompletionDebugMatch {
            id: item.value.clone(),
            label: display_text(item).to_string(),
            description: item.description.clone(),
            kind: "history".to_string(),
        })
        .collect::<Vec<_>>();

    let MenuDebug {
        columns,
        rows,
        visible_rows,
        indent,
        selected_index,
        selected_row,
        selected_col,
        description,
        description_rendered,
        styles,
        rendered,
    } = debug_snapshot(menu, editor, width, height, ansi);

    let selected = if matches.is_empty() {
        -1
    } else {
        selected_index
    };

    CompletionDebug {
        line,
        cursor,
        replace_range,
        stub,
        matches,
        selected,
        selected_row,
        selected_col,
        columns,
        rows,
        visible_rows,
        menu_indent: indent,
        menu_styles: styles,
        menu_description: description,
        menu_description_rendered: description_rendered,
        width,
        height,
        unicode,
        color: ansi,
        rendered,
    }
}