quorum-rs 0.7.0-rc.6

Rust SDK and CLI for multi-agent deliberation systems — ships the `quorum` binary (run / status / trace / tui / init) plus the underlying agent, LLM, tool, prompt, and worker library.
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
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Cell, Paragraph, Row, Table, Wrap};

use super::common::{ListState, render_error, render_key_hints, render_loading, truncate};
use super::{ConfigMutation, FetchRequest, View, ViewAction};
use crate::cli::tui::event::{self, AppEvent, DataEvent, PolicyInfo};
use crate::cli::tui::views::agents::LoadState;

/// Policies list view with tag filtering and inline detail panel.
pub struct PoliciesView {
    orchestrator: String,
    policies: LoadState<Vec<PolicyInfo>>,
    list_state: ListState,
    filter_active: bool,
    filter_text: String,
    /// When true, shows a detail panel for the selected policy.
    detail_visible: bool,
}

impl PoliciesView {
    pub fn new(orchestrator: String) -> Self {
        Self {
            orchestrator,
            policies: LoadState::NotLoaded,
            list_state: ListState::new(0),
            filter_active: false,
            filter_text: String::new(),
            detail_visible: false,
        }
    }

    fn filtered_policies(&self) -> Vec<&PolicyInfo> {
        match &self.policies {
            LoadState::Loaded(policies) => {
                if self.filter_text.is_empty() {
                    policies.iter().collect()
                } else {
                    let filter = self.filter_text.to_lowercase();
                    policies
                        .iter()
                        .filter(|p| {
                            p.tags.iter().any(|t| t.to_lowercase().contains(&filter))
                                || p.name.to_lowercase().contains(&filter)
                        })
                        .collect()
                }
            }
            _ => Vec::new(),
        }
    }

    /// Get the currently selected policy from the filtered list.
    fn selected_policy(&self) -> Option<&PolicyInfo> {
        self.filtered_policies()
            .get(self.list_state.selected)
            .copied()
    }
}

impl View for PoliciesView {
    fn on_enter(&mut self) -> Vec<ViewAction> {
        self.policies = LoadState::Loading;
        vec![ViewAction::Fetch(FetchRequest::Policies {
            orchestrator: self.orchestrator.clone(),
            tag: None,
        })]
    }

    fn update(&mut self, app_event: &AppEvent) -> Option<ViewAction> {
        match app_event {
            AppEvent::Terminal(event) => {
                if self.filter_active {
                    return self.update_filter(event);
                }

                // In detail mode, Esc closes detail
                if self.detail_visible {
                    if event::is_escape(event) || event::is_key(event, 'q') {
                        self.detail_visible = false;
                        return None;
                    }
                    if event::is_up(event) {
                        self.list_state.up();
                    }
                    if event::is_down(event) {
                        self.list_state.down();
                    }
                    // Enter = create room from detail mode
                    if event::is_enter(event)
                        && let Some(policy) = self.selected_policy().cloned()
                    {
                        self.detail_visible = false;
                        return Some(ViewAction::WriteConfig(ConfigMutation::AddRoom {
                            name: format!("{}-room", policy.name),
                            policy: policy.policy_id,
                            orchestrator: self.orchestrator.clone(),
                        }));
                    }
                    return None;
                }

                if event::is_escape(event) || event::is_key(event, 'q') {
                    return Some(ViewAction::Pop);
                }
                if event::is_up(event) {
                    self.list_state.up();
                }
                if event::is_down(event) {
                    self.list_state.down();
                }
                if event::is_key(event, '/') {
                    self.filter_active = true;
                    return None;
                }
                // Enter = main CTA: create room from policy
                if event::is_enter(event) {
                    let filtered = self.filtered_policies();
                    if let Some(policy) = filtered.get(self.list_state.selected) {
                        return Some(ViewAction::WriteConfig(ConfigMutation::AddRoom {
                            name: format!("{}-room", policy.name),
                            policy: policy.policy_id.clone(),
                            orchestrator: self.orchestrator.clone(),
                        }));
                    }
                }
                // d = detail panel
                if event::is_key(event, 'd') && self.selected_policy().is_some() {
                    self.detail_visible = true;
                    return None;
                }
                if event::is_key(event, 'r') {
                    self.policies = LoadState::Loading;
                    self.detail_visible = false;
                    return Some(ViewAction::Fetch(FetchRequest::Policies {
                        orchestrator: self.orchestrator.clone(),
                        tag: None,
                    }));
                }
                None
            }
            AppEvent::Data(DataEvent::PoliciesLoaded {
                orchestrator,
                policies,
            }) if *orchestrator == self.orchestrator => {
                self.list_state.set_count(policies.len());
                self.policies = LoadState::Loaded(policies.clone());
                None
            }
            AppEvent::Data(DataEvent::FetchError { context, error })
                if context.contains("policies") =>
            {
                self.policies = LoadState::Error(error.clone());
                None
            }
            _ => None,
        }
    }

    fn draw(&mut self, frame: &mut Frame, area: Rect) {
        let chunks = Layout::vertical([
            Constraint::Length(if self.filter_active { 3 } else { 0 }),
            Constraint::Min(0),
            Constraint::Length(1),
        ])
        .split(area);

        // Filter input
        if self.filter_active {
            let input = Paragraph::new(format!("/{}", self.filter_text))
                .style(Style::default().fg(Color::Yellow))
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .title(" Filter by tag "),
                );
            frame.render_widget(input, chunks[0]);
        }

        // Policy list + optional detail
        match &self.policies {
            LoadState::NotLoaded | LoadState::Loading => {
                render_loading(frame, chunks[1], "Loading policies...");
            }
            LoadState::Error(e) => {
                render_error(frame, chunks[1], e);
            }
            LoadState::Loaded(_) => {
                let visible_height = chunks[1].height.saturating_sub(3) as usize;
                self.list_state.set_visible_height(visible_height);
                let filtered = self.filtered_policies();
                if filtered.is_empty() {
                    render_error(frame, chunks[1], "No policies found");
                } else if self.detail_visible {
                    let h_chunks = Layout::horizontal([
                        Constraint::Percentage(45),
                        Constraint::Percentage(55),
                    ])
                    .split(chunks[1]);
                    self.draw_table(frame, h_chunks[0], &filtered);
                    if let Some(policy) = self.selected_policy() {
                        draw_policy_detail(frame, h_chunks[1], policy);
                    }
                } else {
                    self.draw_table(frame, chunks[1], &filtered);
                }
            }
        }

        let hints = if self.filter_active {
            vec![("Enter/Esc", "Close filter"), ("Type", "Filter")]
        } else if self.detail_visible {
            vec![
                ("↑↓", "Navigate"),
                ("Enter", "Create Room"),
                ("Esc", "Close detail"),
            ]
        } else {
            vec![
                ("↑↓", "Navigate"),
                ("Enter", "Create Room"),
                ("d", "Detail"),
                ("/", "Filter"),
                ("r", "Refresh"),
                ("Esc", "Back"),
            ]
        };
        render_key_hints(frame, chunks[2], &hints);
    }
}

impl PoliciesView {
    fn update_filter(&mut self, event: &crossterm::event::Event) -> Option<ViewAction> {
        if event::is_escape(event) || event::is_enter(event) {
            self.filter_active = false;
            let count = self.filtered_policies().len();
            self.list_state.set_count(count);
            return None;
        }
        if let crossterm::event::Event::Key(key) = event
            && key.kind == crossterm::event::KeyEventKind::Press
        {
            match key.code {
                crossterm::event::KeyCode::Char(c) => {
                    self.filter_text.push(c);
                }
                crossterm::event::KeyCode::Backspace => {
                    self.filter_text.pop();
                }
                _ => {}
            }
            let count = self.filtered_policies().len();
            self.list_state.set_count(count);
        }
        None
    }

    fn draw_table(&self, frame: &mut Frame, area: Rect, policies: &[&PolicyInfo]) {
        let header = Row::new(vec![
            Cell::from("Name"),
            Cell::from("Max Rounds"),
            Cell::from("Effort"),
            Cell::from("Type"),
            Cell::from("Tags"),
        ])
        .style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );

        let visible = area.height.saturating_sub(3) as usize;
        let rows: Vec<Row> = policies
            .iter()
            .enumerate()
            .skip(self.list_state.scroll_offset)
            .take(visible.max(1))
            .map(|(i, policy)| {
                let style = if i == self.list_state.selected {
                    Style::default().add_modifier(Modifier::REVERSED)
                } else {
                    Style::default()
                };

                let policy_type = if policy.is_role_based {
                    "role-based"
                } else {
                    "static"
                };

                Row::new(vec![
                    Cell::from(truncate(&policy.name, 25)),
                    Cell::from(policy.max_rounds.to_string()),
                    Cell::from(format!("{:.2}", policy.effort)),
                    Cell::from(policy_type),
                    Cell::from(truncate(&policy.tags.join(", "), 30)),
                ])
                .style(style)
            })
            .collect();

        let table = Table::new(
            rows,
            [
                Constraint::Length(27),
                Constraint::Length(12),
                Constraint::Length(11),
                Constraint::Length(12),
                Constraint::Min(20),
            ],
        )
        .header(header)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" Policies ({}) ", policies.len())),
        );

        frame.render_widget(table, area);
    }
}

/// Render a detail panel for a single policy.
fn draw_policy_detail(frame: &mut Frame, area: Rect, policy: &PolicyInfo) {
    let policy_type = if policy.is_role_based {
        "Role-based"
    } else {
        "Static"
    };

    let mut lines = vec![
        Line::from(vec![
            Span::styled("ID: ", Style::default().fg(Color::Cyan)),
            Span::raw(&policy.policy_id),
        ]),
        Line::from(vec![
            Span::styled("Type: ", Style::default().fg(Color::Cyan)),
            Span::raw(policy_type),
        ]),
        Line::from(vec![
            Span::styled("Max Rounds: ", Style::default().fg(Color::Cyan)),
            Span::raw(policy.max_rounds.to_string()),
        ]),
        Line::from(vec![
            Span::styled("Effort: ", Style::default().fg(Color::Cyan)),
            Span::raw(format!("{:.0}%", policy.effort * 100.0)),
        ]),
    ];

    if !policy.tags.is_empty() {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "Tags",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )));
        for tag in &policy.tags {
            lines.push(Line::from(vec![
                Span::styled("", Style::default().fg(Color::DarkGray)),
                Span::raw(tag),
            ]));
        }
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "Press Enter to create a room from this policy",
        Style::default().fg(Color::DarkGray),
    )));

    let detail = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" {} ", policy.name)),
        )
        .wrap(Wrap { trim: false });

    frame.render_widget(detail, area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};

    fn make_key(code: KeyCode) -> AppEvent {
        AppEvent::Terminal(Event::Key(KeyEvent {
            code,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        }))
    }

    fn sample_policies() -> Vec<PolicyInfo> {
        vec![
            PolicyInfo {
                policy_id: "abc123".into(),
                name: "code-review".into(),
                tags: vec!["review".into(), "security".into()],
                max_rounds: 3,
                effort: 0.85,
                is_role_based: true,
            },
            PolicyInfo {
                policy_id: "def456".into(),
                name: "brainstorm".into(),
                tags: vec!["creative".into()],
                max_rounds: 2,
                effort: 0.70,
                is_role_based: false,
            },
        ]
    }

    #[test]
    fn on_enter_triggers_fetch() {
        let mut view = PoliciesView::new("orch".into());
        let actions = view.on_enter();
        assert_eq!(actions.len(), 1);
        assert!(matches!(
            &actions[0],
            ViewAction::Fetch(FetchRequest::Policies { orchestrator, tag }) if orchestrator == "orch" && tag.is_none()
        ));
    }

    #[test]
    fn policies_loaded() {
        let mut view = PoliciesView::new("orch".into());
        let event = AppEvent::Data(DataEvent::PoliciesLoaded {
            orchestrator: "orch".into(),
            policies: sample_policies(),
        });
        view.update(&event);
        assert!(matches!(view.policies, LoadState::Loaded(_)));
        assert_eq!(view.list_state.count, 2);
    }

    #[test]
    fn filter_by_tag() {
        let mut view = PoliciesView::new("orch".into());
        view.policies = LoadState::Loaded(sample_policies());
        view.filter_text = "security".into();

        let filtered = view.filtered_policies();
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].name, "code-review");
    }

    #[test]
    fn filter_by_name() {
        let mut view = PoliciesView::new("orch".into());
        view.policies = LoadState::Loaded(sample_policies());
        view.filter_text = "brain".into();

        let filtered = view.filtered_policies();
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].name, "brainstorm");
    }

    #[test]
    fn slash_activates_filter() {
        let mut view = PoliciesView::new("orch".into());
        view.policies = LoadState::Loaded(sample_policies());
        view.update(&make_key(KeyCode::Char('/')));
        assert!(view.filter_active);
    }

    #[test]
    fn enter_creates_room() {
        let mut view = PoliciesView::new("orch".into());
        view.policies = LoadState::Loaded(sample_policies());
        view.list_state.set_count(2);

        let action = view.update(&make_key(KeyCode::Enter));
        assert_eq!(
            action,
            Some(ViewAction::WriteConfig(ConfigMutation::AddRoom {
                name: "code-review-room".into(),
                policy: "abc123".into(),
                orchestrator: "orch".into(),
            }))
        );
    }

    #[test]
    fn d_opens_detail_panel() {
        let mut view = PoliciesView::new("orch".into());
        view.policies = LoadState::Loaded(sample_policies());
        view.list_state.set_count(2);

        let action = view.update(&make_key(KeyCode::Char('d')));
        assert!(action.is_none());
        assert!(view.detail_visible);
    }

    #[test]
    fn escape_in_detail_closes_detail() {
        let mut view = PoliciesView::new("orch".into());
        view.policies = LoadState::Loaded(sample_policies());
        view.list_state.set_count(2);
        view.detail_visible = true;

        let action = view.update(&make_key(KeyCode::Esc));
        assert!(action.is_none()); // Does NOT pop
        assert!(!view.detail_visible);
    }

    #[test]
    fn enter_in_detail_creates_room() {
        let mut view = PoliciesView::new("orch".into());
        view.policies = LoadState::Loaded(sample_policies());
        view.list_state.set_count(2);
        view.detail_visible = true;

        let action = view.update(&make_key(KeyCode::Enter));
        assert_eq!(
            action,
            Some(ViewAction::WriteConfig(ConfigMutation::AddRoom {
                name: "code-review-room".into(),
                policy: "abc123".into(),
                orchestrator: "orch".into(),
            }))
        );
        assert!(!view.detail_visible);
    }

    #[test]
    fn navigation_works_in_detail_mode() {
        let mut view = PoliciesView::new("orch".into());
        view.policies = LoadState::Loaded(sample_policies());
        view.list_state.set_count(2);
        view.detail_visible = true;

        assert_eq!(view.list_state.selected, 0);
        view.update(&make_key(KeyCode::Down));
        assert_eq!(view.list_state.selected, 1);
        assert!(view.detail_visible);
    }

    #[test]
    fn escape_pops() {
        let mut view = PoliciesView::new("orch".into());
        let action = view.update(&make_key(KeyCode::Esc));
        assert_eq!(action, Some(ViewAction::Pop));
    }

    #[test]
    fn fetch_error_transitions_to_error_state() {
        let mut view = PoliciesView::new("orch".into());
        view.policies = LoadState::Loading;

        let event = AppEvent::Data(DataEvent::FetchError {
            context: "policies".into(),
            error: "orchestrator has empty token".into(),
        });
        let action = view.update(&event);
        assert!(action.is_none());
        assert!(matches!(view.policies, LoadState::Error(ref e) if e.contains("empty token")));
    }
}