octorus 0.5.5

A TUI tool for GitHub PR review, designed for Helix editor users
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
use anyhow::Result;
use clap::{Parser, Subcommand};
use crossterm::{
    execute,
    terminal::{disable_raw_mode, LeaveAlternateScreen},
};
use notify::{Config, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::io;
use std::panic;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

// Use modules from the library crate
use octorus::app::RefreshRequest;
use octorus::{app, cache, config, github, headless, loader, syntax};

// init is only used by the binary, not needed for benchmarks
mod init;

#[derive(Parser, Debug)]
#[command(name = "or")]
#[command(about = "TUI for GitHub PR review, designed for Helix editor users")]
#[command(version)]
struct Args {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Repository name (e.g., "owner/repo"). Auto-detected from current directory if omitted.
    #[arg(short, long)]
    repo: Option<String>,

    /// Pull request number. Shows PR list if omitted.
    #[arg(short, long, conflicts_with = "local")]
    pr: Option<u32>,

    /// Start AI Rally mode directly
    #[arg(long, default_value = "false")]
    ai_rally: bool,

    /// Show local git diff against current HEAD (no GitHub PR fetch)
    #[arg(long, default_value = "false", conflicts_with = "pr")]
    local: bool,

    /// Auto-focus changed file when local diff updates (for local mode)
    #[arg(long, default_value = "false")]
    auto_focus: bool,

    /// Working directory for AI agents (default: current directory)
    #[arg(long)]
    working_dir: Option<String>,

    /// Accept local .octorus/ overrides for AI settings in headless mode.
    /// Without this flag, headless AI Rally will refuse to run if the local config
    /// overrides security-sensitive keys (ai.reviewer, ai.reviewee, ai.*_additional_tools,
    /// ai.auto_post, ai.prompt_dir) or local prompt files are detected in .octorus/prompts/.
    #[arg(long, default_value = "false")]
    accept_local_overrides: bool,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Initialize configuration files and prompt templates
    Init {
        /// Force overwrite existing files
        #[arg(long, default_value = "false")]
        force: bool,
        /// Create local .octorus/ config in project root
        #[arg(long, default_value = "false")]
        local: bool,
    },
    /// Remove AI Rally session data
    Clean,
}

/// Restore terminal to normal state
fn restore_terminal() {
    octorus::ui::cleanup_keyboard_enhancement();
    let _ = disable_raw_mode();
    let _ = execute!(io::stdout(), LeaveAlternateScreen);
}

/// Set up panic hook to restore terminal on panic
fn setup_panic_hook() {
    let original_hook = panic::take_hook();
    panic::set_hook(Box::new(move |panic_info| {
        restore_terminal();
        original_hook(panic_info);
    }));
}

#[tokio::main]
async fn main() -> Result<()> {
    // Set up panic hook before anything else
    setup_panic_hook();

    // OR_DEBUG=1 でファイルログを有効化(TUI の画面を壊さないよう stderr ではなくファイルに出力)
    if std::env::var("OR_DEBUG").ok().as_deref() == Some("1") {
        let log_dir = cache::cache_dir();
        if std::fs::create_dir_all(&log_dir).is_ok() {
            if let Ok(log_file) = std::fs::File::options()
                .create(true)
                .append(true)
                .open(log_dir.join("debug.log"))
            {
                use tracing_subscriber::EnvFilter;
                tracing_subscriber::fmt()
                    .with_writer(std::sync::Mutex::new(log_file))
                    .with_env_filter(EnvFilter::new("octorus=debug,or=debug"))
                    .init();
                tracing::info!("Debug logging enabled");
            }
        }
    }

    let args = Args::parse();

    // Handle subcommands
    if let Some(command) = args.command {
        return match command {
            Commands::Init { force, local } => init::run_init(force, local),
            Commands::Clean => {
                cache::cleanup_rally_sessions();
                let rally_dir = cache::cache_dir().join("rally");
                println!("Rally sessions cleaned: {}", rally_dir.display());
                Ok(())
            }
        };
    }

    let repo = if args.local {
        args.repo.clone().unwrap_or_else(|| "local".to_string())
    } else {
        // Detect or use provided repo
        match args.repo.clone() {
            Some(r) => r,
            None => match github::detect_repo().await {
                Ok(r) => r,
                Err(e) => {
                    eprintln!("Error: {}", e);
                    std::process::exit(1);
                }
            },
        }
    };

    // Pre-initialize syntax highlighting in background to avoid delay on first diff view
    std::thread::spawn(|| {
        let _ = syntax::syntax_set();
        let _ = syntax::theme_set();
    });

    let config = if let Some(ref dir) = args.working_dir {
        config::Config::load_for_dir(Path::new(dir))?
    } else {
        config::Config::load()?
    };

    // Headless mode: --ai-rally with --pr or --local bypasses TUI entirely
    if args.ai_rally && args.pr.is_some() {
        let pr = args.pr.unwrap();
        let working_dir = resolve_working_dir(&args);
        match headless::run_headless_rally(&repo, pr, &config, working_dir.as_deref(), args.accept_local_overrides).await {
            Ok(approved) => std::process::exit(if approved { 0 } else { 1 }),
            Err(e) => {
                headless::write_error_json(&e.to_string());
                eprintln!("Error: {}", e);
                std::process::exit(1);
            }
        }
    }
    if args.local && args.ai_rally {
        let working_dir = resolve_working_dir(&args);
        match headless::run_headless_rally_local(&repo, &config, working_dir.as_deref(), args.accept_local_overrides).await {
            Ok(approved) => std::process::exit(if approved { 0 } else { 1 }),
            Err(e) => {
                headless::write_error_json(&e.to_string());
                eprintln!("Error: {}", e);
                std::process::exit(1);
            }
        }
    }

    if args.local {
        run_with_local_diff(&repo, &config, &args).await
    } else if let Some(pr) = args.pr {
        run_with_pr(&repo, pr, &config, &args).await
    } else {
        run_with_pr_list(&repo, config, &args).await
    }
}

async fn run_with_local_diff(repo: &str, config: &config::Config, args: &Args) -> Result<()> {
    let (retry_tx, mut retry_rx) = mpsc::channel::<RefreshRequest>(1);
    let (mut app, tx) = app::App::new_loading(repo, 0, config.clone());
    let working_dir = args.working_dir.clone();
    let refresh_pending = Arc::new(AtomicBool::new(false));

    app.set_retry_sender(retry_tx.clone());
    setup_local_watch(retry_tx, working_dir.clone(), refresh_pending.clone());
    app.set_local_mode(true);
    app.set_local_auto_focus(args.auto_focus);
    setup_working_dir(&mut app, args);

    if args.ai_rally {
        app.set_start_ai_rally_on_load(true);
    }

    let cancel_token = CancellationToken::new();
    let token_clone = cancel_token.clone();
    let repo = repo.to_string();

    loader::fetch_local_diff(repo.clone(), working_dir.clone(), tx.clone()).await;

    tokio::spawn(async move {
        tokio::select! {
            _ = token_clone.cancelled() => {}
            _ = async {
                while let Some(request) = retry_rx.recv().await {
                    match request {
                        RefreshRequest::LocalRefresh => {
                            refresh_pending.store(false, Ordering::Release);

                            loop {
                                let tx_retry = tx.clone();
                                loader::fetch_local_diff(repo.clone(), working_dir.clone(), tx_retry).await;

                                if !refresh_pending.swap(false, Ordering::AcqRel) {
                                    break;
                                }
                            }
                        }
                        RefreshRequest::PrRefresh { .. } => {
                            // ローカルモードでは PrRefresh を無視する。
                            // pr_number == 0 の擬似値で API 呼び出しすると無効なリクエストになるため、
                            // LocalRefresh として処理する。
                            let tx_retry = tx.clone();
                            loader::fetch_local_diff(repo.clone(), working_dir.clone(), tx_retry).await;
                        }
                    }
                }
            } => {}
        }
    });

    let result = app.run().await;
    cancel_token.cancel();

    if let Err(ref e) = result {
        restore_terminal();
        eprintln!("Error: {:#}", e);
    }

    let exit_code = if result.is_ok() { 0 } else { 1 };
    std::process::exit(exit_code);
}

fn setup_local_watch(
    refresh_tx: mpsc::Sender<RefreshRequest>,
    working_dir: Option<String>,
    refresh_pending: Arc<AtomicBool>,
) {
    let watch_dir = working_dir.unwrap_or_else(|| {
        std::env::current_dir()
            .map(|path| path.to_string_lossy().to_string())
            .unwrap_or_else(|_| ".".to_string())
    });

    std::thread::spawn({
        let refresh_tx = refresh_tx.clone();
        move || {
            let callback = move |result: notify::Result<notify::Event>| {
                let Ok(event) = result else {
                    return;
                };

                let should_refresh = should_refresh_local_change(&event.paths, &event.kind);

                if should_refresh && !refresh_pending.swap(true, Ordering::AcqRel) {
                    let _ = refresh_tx.try_send(RefreshRequest::LocalRefresh);
                }
            };

            let Ok(mut watcher) = RecommendedWatcher::new(callback, Config::default()) else {
                return;
            };

            let _ = watcher.watch(Path::new(&watch_dir), RecursiveMode::Recursive);

            loop {
                std::thread::sleep(Duration::from_secs(60));
            }
        }
    });
}

fn should_refresh_local_change(paths: &[PathBuf], kind: &EventKind) -> bool {
    !matches!(kind, EventKind::Access(_))
        && paths
            .iter()
            .any(|path| !is_git_file(path) && !is_octorus_config_file(path))
}

fn is_git_file(path: &Path) -> bool {
    path.components()
        .any(|component| component.as_os_str() == ".git")
}

fn is_octorus_config_file(path: &Path) -> bool {
    path.components()
        .any(|component| component.as_os_str() == ".octorus")
}

/// Run the app with a specific PR number (existing flow)
async fn run_with_pr(repo: &str, pr: u32, config: &config::Config, args: &Args) -> Result<()> {
    // リトライ用のチャンネル
    let (retry_tx, mut retry_rx) = mpsc::channel::<RefreshRequest>(1);
    let refresh_pending = Arc::new(AtomicBool::new(false));

    // 常に Loading 状態で開始し、バックグラウンドで API 取得
    let (mut app, tx) = app::App::new_loading(repo, pr, config.clone());

    app.set_retry_sender(retry_tx);
    setup_working_dir(&mut app, args);

    // Set flag to start AI Rally mode when --ai-rally is passed
    if args.ai_rally {
        app.set_start_ai_rally_on_load(true);
    }

    // Cancellation token for graceful shutdown
    let cancel_token = CancellationToken::new();
    let token_clone = cancel_token.clone();

    // バックグラウンドでAPI取得
    let repo_clone = repo.to_string();
    let pr_number = pr;
    let working_dir = args.working_dir.clone();

    tokio::spawn(async move {
        tokio::select! {
            _ = token_clone.cancelled() => {}
            _ = async {
                loader::fetch_pr_data(repo_clone.clone(), pr_number, loader::FetchMode::Fresh, tx.clone()).await;

                while let Some(request) = retry_rx.recv().await {
                    match request {
                        RefreshRequest::PrRefresh { pr_number } => {
                            let tx_retry = tx.clone();
                            loader::fetch_pr_data(repo_clone.clone(), pr_number, loader::FetchMode::Fresh, tx_retry)
                                .await;
                        }
                        RefreshRequest::LocalRefresh => {
                            refresh_pending.store(false, Ordering::Release);
                            loop {
                                let tx_retry = tx.clone();
                                loader::fetch_local_diff(repo_clone.clone(), working_dir.clone(), tx_retry).await;
                                if !refresh_pending.swap(false, Ordering::AcqRel) {
                                    break;
                                }
                            }
                        }
                    }
                }
            } => {}
        }
    });

    // Run the app and ensure terminal is restored on error
    let result = app.run().await;

    // Signal background tasks to stop
    cancel_token.cancel();

    if let Err(ref e) = result {
        restore_terminal();
        eprintln!("Error: {:#}", e);
    }

    // spawn_blocking タスク(プリフェッチ等)が巨大ファイル処理中の場合、
    // tokio ランタイムの drop が完了を待ち続けるため、即座にプロセスを終了する。
    // これにより Drop ベースのクリーンアップはスキップされるが、バックグラウンドタスクは
    // cancel_token.cancel() で明示的に停止済みであり、残るのは spawn_blocking の
    // tree-sitter パース処理のみ。OS がプロセス終了時にリソースを回収するため問題なし。
    let exit_code = if result.is_ok() { 0 } else { 1 };
    std::process::exit(exit_code);
}

/// Run the app with PR list (new flow)
async fn run_with_pr_list(repo: &str, config: config::Config, args: &Args) -> Result<()> {
    // リトライ用のチャンネル(PR リスト画面から Local モードへの切替に対応)
    let (retry_tx, mut retry_rx) = mpsc::channel::<RefreshRequest>(1);
    let refresh_pending = Arc::new(AtomicBool::new(false));

    let mut app = app::App::new_pr_list(repo, config);
    app.set_retry_sender(retry_tx);
    setup_working_dir(&mut app, args);

    // Set pending AI Rally flag if --ai-rally was passed
    if args.ai_rally {
        app.set_pending_ai_rally(true);
    }

    // Start loading PR list
    let (pr_list_tx, rx) = mpsc::channel(2);
    app.set_pr_list_receiver(rx);

    let repo_clone = repo.to_string();
    let state_filter = app.pr_list_state_filter;

    tokio::spawn(async move {
        let result = github::fetch_pr_list(&repo_clone, state_filter, 30).await;
        let _ = pr_list_tx.send(result.map_err(|e| e.to_string())).await;
    });

    // データ取得用チャンネル(Local モード切替時に使用)
    let (data_tx, data_rx) = mpsc::channel(2);
    app.set_data_receiver(0, data_rx);

    // Cancellation token for graceful shutdown
    let cancel_token = CancellationToken::new();
    let token_clone = cancel_token.clone();

    // リトライループ(Local/PR リフレッシュ対応)
    let repo_for_retry = repo.to_string();
    let working_dir = args.working_dir.clone();

    tokio::spawn(async move {
        tokio::select! {
            _ = token_clone.cancelled() => {}
            _ = async {
                while let Some(request) = retry_rx.recv().await {
                    match request {
                        RefreshRequest::PrRefresh { pr_number } => {
                            let tx_retry = data_tx.clone();
                            loader::fetch_pr_data(repo_for_retry.clone(), pr_number, loader::FetchMode::Fresh, tx_retry)
                                .await;
                        }
                        RefreshRequest::LocalRefresh => {
                            refresh_pending.store(false, Ordering::Release);
                            loop {
                                let tx_retry = data_tx.clone();
                                loader::fetch_local_diff(repo_for_retry.clone(), working_dir.clone(), tx_retry).await;
                                if !refresh_pending.swap(false, Ordering::AcqRel) {
                                    break;
                                }
                            }
                        }
                    }
                }
            } => {}
        }
    });

    // Run the app
    let result = app.run().await;

    // Signal background tasks to stop
    cancel_token.cancel();

    if let Err(ref e) = result {
        restore_terminal();
        eprintln!("Error: {:#}", e);
    }

    // run_with_pr と同様、spawn_blocking タスクの完了待ちによるハングを防止するため
    // 即座にプロセスを終了する。バックグラウンドタスクやサブプロセスの明示的な停止は
    // app.run() 内で完了済み。
    let exit_code = if result.is_ok() { 0 } else { 1 };
    std::process::exit(exit_code);
}

/// Resolve working directory for headless mode
fn resolve_working_dir(args: &Args) -> Option<String> {
    if let Some(dir) = args.working_dir.clone() {
        Some(dir)
    } else {
        std::env::current_dir()
            .ok()
            .map(|p| p.to_string_lossy().to_string())
    }
}

/// Set up working directory for AI agents
fn setup_working_dir(app: &mut app::App, args: &Args) {
    if let Some(dir) = args.working_dir.clone() {
        app.set_working_dir(Some(dir));
    } else {
        // Use current directory as default.
        // Note: current_dir() can fail in edge cases (e.g., if the current directory
        // has been deleted, or on some restricted environments). When --ai-rally is
        // used without --working-dir, we need a valid directory for the AI agents.
        match std::env::current_dir() {
            Ok(cwd) => {
                app.set_working_dir(Some(cwd.to_string_lossy().to_string()));
            }
            Err(e) => {
                if args.ai_rally {
                    eprintln!(
                        "Warning: Failed to get current directory: {}. AI Rally may not work correctly without --working-dir.",
                        e
                    );
                }
                // Continue without setting working_dir; it's optional for non-AI-Rally usage
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use notify::event::{AccessKind, AccessMode, CreateKind};
    use std::path::PathBuf;

    #[test]
    fn test_should_refresh_local_change_ignores_access_events() {
        let paths = vec![PathBuf::from("src/main.rs")];
        let kind = EventKind::Access(AccessKind::Close(AccessMode::Write));

        assert!(!should_refresh_local_change(&paths, &kind));
    }

    #[test]
    fn test_should_refresh_local_change_ignores_git_paths() {
        let paths = vec![PathBuf::from(".git/HEAD"), PathBuf::from(".git/index.lock")];
        let kind = EventKind::Create(CreateKind::File);

        assert!(!should_refresh_local_change(&paths, &kind));
    }

    #[test]
    fn test_should_refresh_local_change_refreshes_subdir_change() {
        let paths = vec![
            PathBuf::from(".git/HEAD"),
            PathBuf::from("src/subdir/changed.rs"),
        ];
        let kind = EventKind::Create(CreateKind::File);

        assert!(should_refresh_local_change(&paths, &kind));
    }

    #[test]
    fn test_is_git_file_identifies_git_path() {
        assert!(is_git_file(std::path::Path::new(".git/refs/heads/main")));
        assert!(!is_git_file(std::path::Path::new("src/main.rs")));
    }

    #[test]
    fn test_should_refresh_local_change_ignores_octorus_paths() {
        let paths = vec![
            PathBuf::from(".octorus/config.toml"),
            PathBuf::from(".octorus/prompts/reviewer.md"),
        ];
        let kind = EventKind::Create(CreateKind::File);

        assert!(!should_refresh_local_change(&paths, &kind));
    }

    #[test]
    fn test_is_octorus_config_file() {
        assert!(is_octorus_config_file(std::path::Path::new(
            ".octorus/config.toml"
        )));
        assert!(is_octorus_config_file(std::path::Path::new(
            ".octorus/prompts/reviewer.md"
        )));
        assert!(!is_octorus_config_file(std::path::Path::new("src/main.rs")));
    }
}