crosslink 0.8.0

A synced issue tracker CLI for multi-agent AI development
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! TUI walkthrough for `crosslink init` — registry-driven interactive setup.

use anyhow::{Context, Result};
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use crossterm::terminal::{self, disable_raw_mode, enable_raw_mode};
use crossterm::{cursor, execute};
use ratatui::{
    layout::{Constraint, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, ListState, Padding, Paragraph},
    Frame, TerminalOptions, Viewport,
};
use std::fs;
use std::io::{self, IsTerminal};

use super::{InitUI, TuiChoices, HOOK_CONFIG_JSON};
use crate::commands::config_registry::{WalkthroughCore, REGISTRY};

// ── Ratatui TUI walkthrough (registry-driven, REQ-5) ────────────────────────

struct InitWalkthroughApp {
    core: WalkthroughCore,
    /// Shell alias question
    alias_selected: usize, // 0=Yes, 1=No
    shell_config_file: String,
}

impl InitWalkthroughApp {
    fn new(existing: &serde_json::Value) -> Self {
        let core = WalkthroughCore::new(existing, 1); // 1 extra screen: alias

        // Detect shell for alias question
        let shell_env = std::env::var("SHELL").unwrap_or_default();
        let home = std::env::var("HOME").unwrap_or_default();
        let (shell_name, shell_config_file) = if shell_env.ends_with("fish") {
            (
                "fish".to_string(),
                format!("{home}/.config/fish/config.fish"),
            )
        } else if shell_env.ends_with("zsh") {
            ("zsh".to_string(), format!("{home}/.zshrc"))
        } else if shell_env.ends_with("bash") {
            ("bash".to_string(), format!("{home}/.bashrc"))
        } else {
            ("unknown".to_string(), String::new())
        };

        // Check if alias already installed
        let alias_already = if shell_config_file.is_empty() {
            false
        } else {
            let alias_line = if shell_name == "fish" {
                "abbr -a xl crosslink"
            } else {
                "alias xl='crosslink'"
            };
            fs::read_to_string(&shell_config_file)
                .is_ok_and(|c| c.lines().any(|l| l.trim() == alias_line))
        };

        Self {
            core,
            alias_selected: usize::from(alias_already),
            shell_config_file,
        }
    }

    const fn is_alias_screen(&self) -> bool {
        self.core.extra_screen_idx().is_some()
    }

    const fn move_up(&mut self) {
        if self.is_alias_screen() {
            self.alias_selected = self.alias_selected.saturating_sub(1);
        } else {
            self.core.move_up();
        }
    }

    fn move_down(&mut self) {
        if self.is_alias_screen() {
            if self.alias_selected < 1 {
                self.alias_selected += 1;
            }
        } else {
            self.core.move_down();
        }
    }

    fn build_choices(&self) -> TuiChoices {
        TuiChoices {
            values: self.core.build_config(),
            install_alias: self.alias_selected == 0,
        }
    }
}

fn draw_init_walkthrough(frame: &mut Frame, app: &InitWalkthroughApp) {
    let area = frame.area();

    let outer = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::DarkGray))
        .title(Line::from(vec![
            Span::raw(" "),
            Span::styled(
                "crosslink",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" setup ", Style::default().fg(Color::DarkGray)),
        ]))
        .padding(Padding::new(2, 2, 1, 1));

    let inner = outer.inner(area);
    frame.render_widget(outer, area);

    // Progress dots
    let total = app.core.total_screens();
    let progress_spans: Vec<Span> = (0..total)
        .map(|i| match i.cmp(&app.core.screen) {
            std::cmp::Ordering::Less => {
                Span::styled(" \u{25cf} ", Style::default().fg(Color::Green))
            }
            std::cmp::Ordering::Equal => Span::styled(
                " \u{25cf} ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            std::cmp::Ordering::Greater => {
                Span::styled(" \u{25cb} ", Style::default().fg(Color::DarkGray))
            }
        })
        .collect();

    if app.core.is_preset_screen() {
        draw_init_preset(frame, app, inner, progress_spans);
    } else if app.is_alias_screen() {
        draw_init_alias(frame, app, inner, progress_spans);
    } else if app.core.is_confirm_screen() {
        draw_init_confirm(frame, app, inner, progress_spans);
    } else if let Some(gi) = app.core.current_group_idx() {
        draw_init_group(frame, app, gi, inner, progress_spans);
    }
}

fn draw_init_preset(
    frame: &mut Frame,
    app: &InitWalkthroughApp,
    area: Rect,
    progress_spans: Vec<Span>,
) {
    let chunks = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Min(3),
        Constraint::Length(1),
    ])
    .split(area);

    frame.render_widget(Paragraph::new(Line::from(progress_spans)), chunks[0]);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            "Quick-start presets",
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ))),
        chunks[2],
    );
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            "Choose a preset or configure each setting individually",
            Style::default().fg(Color::DarkGray),
        ))),
        chunks[3],
    );

    let presets = [
        ("Team", "strict tracking, CI verification, signing enforced"),
        ("Solo", "relaxed tracking, local verification, no signing"),
        ("Custom", "configure each setting individually"),
    ];
    let items: Vec<ListItem> = presets
        .iter()
        .enumerate()
        .map(|(i, (label, desc))| {
            let (marker, style) = if i == app.core.preset_selected {
                (
                    "\u{276f} ",
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                )
            } else {
                ("  ", Style::default().fg(Color::Gray))
            };
            ListItem::new(Line::from(vec![
                Span::styled(marker, style),
                Span::styled(*label, style),
                Span::raw("  "),
                Span::styled(*desc, Style::default().fg(Color::DarkGray)),
            ]))
        })
        .collect();
    let list = List::new(items);
    let mut state = ListState::default().with_selected(Some(app.core.preset_selected));
    frame.render_stateful_widget(list, chunks[5], &mut state);

    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            "\u{2191}\u{2193} select  Enter confirm  Esc cancel",
            Style::default().fg(Color::DarkGray),
        ))),
        chunks[6],
    );
}

fn draw_init_group(
    frame: &mut Frame,
    app: &InitWalkthroughApp,
    group_idx: usize,
    area: Rect,
    progress_spans: Vec<Span>,
) {
    let keys = &app.core.group_keys[group_idx];
    let chunks = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Min(keys.len() as u16 + 1),
        Constraint::Length(2),
        Constraint::Length(1),
    ])
    .split(area);

    frame.render_widget(Paragraph::new(Line::from(progress_spans)), chunks[0]);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            app.core.group_names[group_idx],
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ))),
        chunks[2],
    );

    let items: Vec<ListItem> = keys
        .iter()
        .enumerate()
        .map(|(ki, &reg_idx)| {
            let entry = &REGISTRY[reg_idx];
            let options = WalkthroughCore::options_for_key(reg_idx);
            let selected = app.core.group_selections[group_idx][ki];
            let val_str = if selected < options.len() {
                options[selected]
            } else {
                "?"
            };
            let (marker, style) = if ki == app.core.group_cursor {
                (
                    "\u{276f} ",
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                )
            } else {
                ("  ", Style::default().fg(Color::Gray))
            };
            ListItem::new(Line::from(vec![
                Span::styled(marker, style),
                Span::styled(format!("{:<30}", entry.key), style),
                Span::styled(
                    format!("[{val_str}]"),
                    if ki == app.core.group_cursor {
                        Style::default().fg(Color::Yellow)
                    } else {
                        Style::default().fg(Color::DarkGray)
                    },
                ),
            ]))
        })
        .collect();
    let list = List::new(items);
    let mut state = ListState::default().with_selected(Some(app.core.group_cursor));
    frame.render_stateful_widget(list, chunks[4], &mut state);

    // Description pane
    if app.core.group_cursor < keys.len() {
        let reg_idx = keys[app.core.group_cursor];
        let entry = &REGISTRY[reg_idx];
        let options = WalkthroughCore::options_for_key(reg_idx);
        let valid = if options.len() > 1 {
            format!("  Valid: {}", options.join(", "))
        } else {
            String::new()
        };
        frame.render_widget(
            Paragraph::new(vec![
                Line::from(Span::styled(
                    format!("  {}", entry.description),
                    Style::default().fg(Color::DarkGray),
                )),
                Line::from(Span::styled(valid, Style::default().fg(Color::DarkGray))),
            ]),
            chunks[5],
        );
    }

    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            "\u{2191}\u{2193} navigate  \u{2192}/\u{2190} cycle  Enter next  Backspace back  Esc cancel",
            Style::default().fg(Color::DarkGray),
        ))),
        chunks[6],
    );
}

fn draw_init_alias(
    frame: &mut Frame,
    app: &InitWalkthroughApp,
    area: Rect,
    progress_spans: Vec<Span>,
) {
    let chunks = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Min(3),
        Constraint::Length(1),
    ])
    .split(area);

    frame.render_widget(Paragraph::new(Line::from(progress_spans)), chunks[0]);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            "Shell Alias",
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ))),
        chunks[2],
    );

    let desc = if app.shell_config_file.is_empty() {
        "Could not detect shell config file".to_string()
    } else {
        format!(
            "Install `xl` alias for `crosslink` in {}?",
            app.shell_config_file
        )
    };
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            desc,
            Style::default().fg(Color::DarkGray),
        ))),
        chunks[3],
    );

    let options = [
        ("Yes", "Add alias to shell config"),
        ("No", "Skip alias setup"),
    ];
    let items: Vec<ListItem> = options
        .iter()
        .enumerate()
        .map(|(i, (label, desc))| {
            let (marker, style) = if i == app.alias_selected {
                (
                    "\u{276f} ",
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                )
            } else {
                ("  ", Style::default().fg(Color::Gray))
            };
            ListItem::new(Line::from(vec![
                Span::styled(marker, style),
                Span::styled(*label, style),
                Span::raw("  "),
                Span::styled(*desc, Style::default().fg(Color::DarkGray)),
            ]))
        })
        .collect();
    let list = List::new(items);
    let mut state = ListState::default().with_selected(Some(app.alias_selected));
    frame.render_stateful_widget(list, chunks[5], &mut state);

    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            "\u{2191}\u{2193} select  Enter confirm  Backspace back  Esc cancel",
            Style::default().fg(Color::DarkGray),
        ))),
        chunks[6],
    );
}

fn draw_init_confirm(
    frame: &mut Frame,
    app: &InitWalkthroughApp,
    area: Rect,
    progress_spans: Vec<Span>,
) {
    let total_keys: usize = app.core.group_keys.iter().map(Vec::len).sum();
    let summary_height = total_keys as u16 + app.core.group_names.len() as u16 + 3;

    let chunks = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Min(summary_height),
        Constraint::Length(1),
    ])
    .split(area);

    frame.render_widget(Paragraph::new(Line::from(progress_spans)), chunks[0]);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            "Review your choices",
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ))),
        chunks[2],
    );

    let mut lines: Vec<Line> = Vec::new();
    for (gi, keys) in app.core.group_keys.iter().enumerate() {
        lines.push(Line::from(Span::styled(
            format!("  {}", app.core.group_names[gi]),
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )));
        for (ki, &reg_idx) in keys.iter().enumerate() {
            let entry = &REGISTRY[reg_idx];
            let options = WalkthroughCore::options_for_key(reg_idx);
            let selected = app.core.group_selections[gi][ki];
            let val_str = if selected < options.len() {
                options[selected]
            } else {
                "?"
            };
            lines.push(Line::from(vec![
                Span::styled("    \u{2713} ", Style::default().fg(Color::Green)),
                Span::styled(
                    format!("{}: ", entry.key),
                    Style::default().fg(Color::DarkGray),
                ),
                Span::styled(
                    val_str,
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
            ]));
        }
    }
    lines.push(Line::from(""));
    let alias_text = if app.alias_selected == 0 {
        format!(
            "    \u{2713} xl alias: will install ({})",
            app.shell_config_file
        )
    } else {
        "    \u{2713} xl alias: skip".to_string()
    };
    lines.push(Line::from(Span::styled(
        alias_text,
        Style::default().fg(Color::DarkGray),
    )));

    frame.render_widget(Paragraph::new(lines), chunks[4]);

    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            "Enter apply  Backspace go back  Esc cancel",
            Style::default().fg(Color::DarkGray),
        ))),
        chunks[5],
    );
}

/// Run the interactive TUI walkthrough using ratatui, returning user choices.
/// Falls back to defaults if stdin is not a TTY.
pub(super) fn run_tui_walkthrough(existing: Option<&serde_json::Value>) -> Result<TuiChoices> {
    if !std::io::stdin().is_terminal() {
        println!("Non-interactive environment detected, using defaults.");
        return Ok(TuiChoices::default());
    }

    let base = existing
        .cloned()
        .unwrap_or_else(|| serde_json::from_str(HOOK_CONFIG_JSON).unwrap_or_default());

    let mut app = InitWalkthroughApp::new(&base);

    const WALKTHROUGH_HEIGHT: u16 = 24;
    enable_raw_mode().context("Failed to enable raw mode")?;
    let stdout = io::stdout();
    let backend = ratatui::backend::CrosstermBackend::new(stdout);
    let mut terminal = ratatui::Terminal::with_options(
        backend,
        TerminalOptions {
            viewport: Viewport::Inline(WALKTHROUGH_HEIGHT),
        },
    )
    .context("Failed to create terminal")?;

    let result = (|| -> Result<()> {
        loop {
            terminal.draw(|f| draw_init_walkthrough(f, &app))?;

            if let Event::Key(key) = event::read().context("Failed to read terminal event")? {
                if key.kind != KeyEventKind::Press {
                    continue;
                }
                match key.code {
                    KeyCode::Up | KeyCode::Char('k') if !app.core.is_confirm_screen() => {
                        app.move_up();
                    }
                    KeyCode::Down | KeyCode::Char('j') if !app.core.is_confirm_screen() => {
                        app.move_down();
                    }
                    KeyCode::Right
                        if !app.core.is_preset_screen()
                            && !app.core.is_confirm_screen()
                            && !app.is_alias_screen() =>
                    {
                        app.core.cycle_value();
                    }
                    KeyCode::Left
                        if !app.core.is_preset_screen()
                            && !app.core.is_confirm_screen()
                            && !app.is_alias_screen() =>
                    {
                        // Cycle backwards
                        if let Some(gi) = app.core.current_group_idx() {
                            if app.core.group_cursor < app.core.group_keys[gi].len() {
                                let reg_idx = app.core.group_keys[gi][app.core.group_cursor];
                                let options = WalkthroughCore::options_for_key(reg_idx);
                                if !options.is_empty() {
                                    let current =
                                        app.core.group_selections[gi][app.core.group_cursor];
                                    app.core.group_selections[gi][app.core.group_cursor] =
                                        if current == 0 {
                                            options.len() - 1
                                        } else {
                                            current - 1
                                        };
                                }
                            }
                        }
                    }
                    KeyCode::Enter | KeyCode::Char(' ') => {
                        if !app.core.is_preset_screen()
                            && !app.core.is_confirm_screen()
                            && !app.is_alias_screen()
                        {
                            // On group screens, Enter advances to next key or next screen
                            if let Some(gi) = app.core.current_group_idx() {
                                if app.core.group_cursor + 1 < app.core.group_keys[gi].len() {
                                    app.core.group_cursor += 1;
                                } else {
                                    app.core.screen += 1;
                                    app.core.group_cursor = 0;
                                }
                            }
                        } else {
                            app.core.confirm();
                        }
                        if app.core.finished {
                            break;
                        }
                    }
                    KeyCode::Tab if !app.core.is_confirm_screen() => {
                        if app.core.is_preset_screen() {
                            app.core.confirm();
                        } else {
                            app.core.screen += 1;
                            app.core.group_cursor = 0;
                        }
                    }
                    KeyCode::Backspace => app.core.go_back(),
                    KeyCode::Esc | KeyCode::Char('q') => {
                        app.core.cancelled = true;
                        break;
                    }
                    _ => {}
                }
            }
        }
        Ok(())
    })();

    // Clear inline viewport
    {
        let area = terminal.get_frame().area();
        let backend = terminal.backend_mut();
        for row in area.y..area.y + area.height {
            execute!(
                backend,
                cursor::MoveTo(0, row),
                terminal::Clear(terminal::ClearType::CurrentLine)
            )
            .ok();
        }
        execute!(backend, cursor::MoveTo(0, area.y)).ok();
    }

    disable_raw_mode().ok();
    terminal.show_cursor().ok();

    result?;

    if app.core.cancelled {
        anyhow::bail!("Setup cancelled");
    }

    Ok(app.build_choices())
}

/// Apply TUI choices onto a config JSON value, preserving fields not covered by the TUI.
pub(super) fn apply_tui_choices(
    config: &mut serde_json::Value,
    choices: &TuiChoices,
) -> Result<()> {
    let obj = config
        .as_object_mut()
        .context("hook-config.json is not a JSON object")?;
    for (k, v) in &choices.values {
        obj.insert(k.clone(), v.clone());
    }
    Ok(())
}

/// Install the `xl` shell alias if requested by the user during init.
pub(super) fn setup_shell_alias(ui: &InitUI, choices: &TuiChoices) {
    if !choices.install_alias {
        return;
    }

    let shell_env = std::env::var("SHELL").unwrap_or_default();
    let home = std::env::var("HOME").unwrap_or_default();

    let (config_file, alias_line) = if shell_env.ends_with("fish") {
        (
            format!("{home}/.config/fish/config.fish"),
            "abbr -a xl crosslink",
        )
    } else if shell_env.ends_with("zsh") {
        (format!("{home}/.zshrc"), "alias xl='crosslink'")
    } else if shell_env.ends_with("bash") {
        (format!("{home}/.bashrc"), "alias xl='crosslink'")
    } else {
        ui.warn("Could not detect shell for alias installation");
        return;
    };

    let path = std::path::Path::new(&config_file);

    // Idempotent: check if already present
    if let Ok(content) = fs::read_to_string(path) {
        if content.lines().any(|line| line.trim() == alias_line) {
            ui.step_skip("xl alias already installed");
            return;
        }
    }

    // Append the alias
    ui.step_start("Installing xl alias");
    let line_to_append = format!("\n# crosslink shortcut\n{alias_line}\n");
    match fs::OpenOptions::new().append(true).open(path) {
        Ok(mut file) => {
            use std::io::Write;
            if let Err(e) = file.write_all(line_to_append.as_bytes()) {
                ui.warn(&format!("Failed to write alias: {e}"));
            } else {
                ui.step_ok(Some(&config_file));
                ui.detail(&format!(
                    "Run `source {config_file}` or open a new terminal to activate"
                ));
            }
        }
        Err(e) => {
            ui.warn(&format!("Could not open {config_file}: {e}"));
        }
    }
}