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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
use anyhow::Result;
use serde::Serialize;
use tokio::sync::mpsc;

use std::borrow::Cow;

use crate::ai::adapter::{
    CommentSeverity, Context, ReviewAction, RevieweeOutput, RevieweeStatus, ReviewerOutput,
};
use crate::ai::orchestrator::{Orchestrator, OrchestratorCommand, RallyEvent, RallyState};
use crate::ai::prompt_loader::{PromptLoader, PromptSource};
use crate::config::Config;
use crate::github;

use crate::config::SENSITIVE_AI_KEYS;

/// Run AI Rally in headless mode (no TUI).
///
/// Progress logs are written to stderr. On completion, a JSON summary is written to stdout.
/// This is invoked when `--ai-rally --pr <number>` is specified.
/// Returns `true` if approved, `false` otherwise.
pub async fn run_headless_rally(
    repo: &str,
    pr_number: u32,
    config: &Config,
    working_dir: Option<&str>,
    accept_local_overrides: bool,
) -> Result<bool> {
    eprintln!("[Headless] Fetching PR #{} from {}...", pr_number, repo);

    let pr = github::fetch_pr(repo, pr_number).await?;
    let files = github::fetch_changed_files(repo, pr_number).await?;

    let mut file_patches: Vec<(String, String)> = files
        .iter()
        .filter_map(|f| f.patch.as_ref().map(|p| (f.filename.clone(), p.clone())))
        .collect();

    // Fallback: if some files are missing patches (large files), fetch full PR diff
    let has_missing_patches = files.iter().any(|f| f.patch.is_none());
    if has_missing_patches {
        eprintln!("[Headless] Some files missing patches, fetching full PR diff...");
        if let Ok(full_diff) = github::fetch_pr_diff(repo, pr_number).await {
            let parsed = crate::diff::parse_unified_diff(&full_diff);
            for (filename, patch) in &parsed {
                if !file_patches.iter().any(|(f, _)| f == filename) {
                    file_patches.push((filename.clone(), patch.clone()));
                }
            }
        }
    }

    let diff = file_patches
        .iter()
        .map(|(_, p)| p.as_str())
        .collect::<Vec<_>>()
        .join("\n");

    let context = Context {
        repo: repo.to_string(),
        pr_number,
        pr_title: pr.title.clone(),
        pr_body: pr.body.clone(),
        diff,
        working_dir: working_dir.map(|s| s.to_string()),
        head_sha: pr.head.sha.clone(),
        base_branch: pr.base.ref_name.clone(),
        external_comments: Vec::new(),
        local_mode: false,
        file_patches,
    };

    run_headless_with_context(repo, pr_number, config, context, accept_local_overrides).await
}

/// Run AI Rally in headless mode for local diff.
///
/// Progress logs are written to stderr. On completion, a JSON summary is written to stdout.
/// This is invoked when `--local --ai-rally` is specified.
/// Returns `true` if approved, `false` otherwise.
pub async fn run_headless_rally_local(
    repo: &str,
    config: &Config,
    working_dir: Option<&str>,
    accept_local_overrides: bool,
) -> Result<bool> {
    eprintln!("[Headless] Running local diff rally...");

    let wd = working_dir.map(|s| s.to_string()).or_else(|| {
        std::env::current_dir()
            .ok()
            .map(|p| p.to_string_lossy().to_string())
    });

    let dir = wd.as_deref().unwrap_or(".");
    let base_branch = detect_local_base_branch(Some(dir)).unwrap_or_else(|| "main".to_string());

    // Use `git diff HEAD` to capture working tree changes (staged + unstaged)
    let diff_output = tokio::process::Command::new("git")
        .args(["diff", "HEAD"])
        .current_dir(dir)
        .output()
        .await?;

    if !diff_output.status.success() {
        let stderr = String::from_utf8_lossy(&diff_output.stderr);
        anyhow::bail!(
            "git diff HEAD failed (exit {}): {}",
            diff_output.status,
            stderr.trim()
        );
    }

    let mut diff = String::from_utf8_lossy(&diff_output.stdout).to_string();

    // Include untracked files (mirrors TUI behavior in loader.rs)
    // Uses `git ls-files --others --exclude-standard` + `git diff --no-index`
    let untracked_diff = collect_untracked_diff(dir).await;
    if !untracked_diff.is_empty() {
        if !diff.is_empty() && !diff.ends_with('\n') {
            diff.push('\n');
        }
        diff.push_str(&untracked_diff);
    }

    // Fallback: if no uncommitted changes, try committed changes vs base branch
    if diff.trim().is_empty() {
        eprintln!(
            "[Headless] No uncommitted changes, trying diff against origin/{}...",
            base_branch
        );
        let fallback_output = tokio::process::Command::new("git")
            .args(["diff", &format!("origin/{}...HEAD", base_branch)])
            .current_dir(dir)
            .output()
            .await?;

        if fallback_output.status.success() {
            diff = String::from_utf8_lossy(&fallback_output.stdout).to_string();
        } else {
            let stderr = String::from_utf8_lossy(&fallback_output.stderr);
            eprintln!("[Headless] Fallback diff also failed: {}", stderr.trim());
        }
    }

    if diff.trim().is_empty() {
        anyhow::bail!(
            "No changes detected: both git diff HEAD and git diff origin/{}...HEAD returned empty",
            base_branch
        );
    }

    let head_sha = tokio::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(dir)
        .output()
        .await
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_default();

    let context = Context {
        repo: repo.to_string(),
        pr_number: 0,
        pr_title: "Local diff".to_string(),
        pr_body: None,
        diff,
        working_dir: wd,
        head_sha,
        base_branch,
        external_comments: Vec::new(),
        local_mode: true,
        file_patches: Vec::new(),
    };

    run_headless_with_context(repo, 0, config, context, accept_local_overrides).await
}

/// Collect sensitive local overrides from config and local prompt files.
///
/// Returns a list of override descriptions. If non-empty and `accept_local_overrides`
/// is false, the caller should refuse to proceed.
fn collect_sensitive_overrides(config: &Config) -> Vec<Cow<'static, str>> {
    let mut sensitive_overrides: Vec<Cow<'static, str>> = SENSITIVE_AI_KEYS
        .iter()
        .filter(|key| config.local_overrides.contains(**key))
        .map(|s| Cow::Borrowed(*s))
        .collect();

    let prompt_loader = PromptLoader::new(&config.ai, &config.project_root);
    for (filename, source) in prompt_loader.resolve_all_sources() {
        if let PromptSource::Local(path) = source {
            sensitive_overrides.push(Cow::Owned(format!(
                "local prompt: {} ({})",
                filename,
                path.display()
            )));
        }
    }

    sensitive_overrides
}

/// Core headless execution logic shared between PR and local modes.
async fn run_headless_with_context(
    repo: &str,
    pr_number: u32,
    config: &Config,
    context: Context,
    accept_local_overrides: bool,
) -> Result<bool> {
    // Check for sensitive local config overrides
    let sensitive_overrides = collect_sensitive_overrides(config);
    let prompt_loader = PromptLoader::new(&config.ai, &config.project_root);

    if !sensitive_overrides.is_empty() && !accept_local_overrides {
        eprintln!(
            "[Headless] WARNING: Local .octorus/ overrides detected that affect AI behavior:"
        );
        for key in &sensitive_overrides {
            eprintln!("  - {}", key);
        }
        eprintln!(
            "[Headless] Use --accept-local-overrides to explicitly allow these overrides."
        );
        anyhow::bail!(
            "Refusing to run AI Rally with local overrides: {}. \
             Use --accept-local-overrides to bypass this check.",
            sensitive_overrides
                .iter()
                .map(|s| s.as_ref())
                .collect::<Vec<&str>>()
                .join(", ")
        );
    }

    let (event_tx, mut event_rx) = mpsc::channel(100);
    let (cmd_tx, cmd_rx) = mpsc::channel(10);

    let local_mode = context.local_mode;

    let mut orchestrator = Orchestrator::new(
        repo,
        pr_number,
        config.ai.clone(),
        event_tx,
        Some(cmd_rx),
        prompt_loader,
    )?;
    orchestrator.set_context(context);

    // Spawn orchestrator in background
    let orchestrator_handle = tokio::spawn(async move { orchestrator.run().await });

    // Event loop: receive events and auto-respond to interactive requests
    let outcome = run_headless_event_loop(&mut event_rx, &cmd_tx, local_mode).await;

    // Wait for orchestrator to finish
    let _ = orchestrator_handle.await;

    // Existing stderr output (unchanged)
    match &outcome.result {
        HeadlessResult::Approved(_) => {
            eprintln!("\n[Headless] Rally completed: Approved");
        }
        HeadlessResult::NotApproved(reason) => {
            eprintln!("\n[Headless] Rally completed: {}", reason);
        }
        HeadlessResult::Error(msg) => {
            eprintln!("\n[Headless] Rally error: {}", msg);
        }
    }

    // JSON output to stdout
    let json_output = build_json_output(&outcome);
    write_json_stdout(&json_output);

    Ok(matches!(outcome.result, HeadlessResult::Approved(_)))
}

enum HeadlessResult {
    Approved(String),
    NotApproved(String),
    Error(String),
}

/// Internal outcome from the headless event loop, bundling result with collected data.
struct HeadlessOutcome {
    result: HeadlessResult,
    iterations: u32,
    last_review: Option<ReviewerOutput>,
    last_fix: Option<RevieweeOutput>,
}

/// Result kind for JSON output (serialized as snake_case).
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
enum HeadlessResultKind {
    Approved,
    NotApproved,
    Error,
}

/// JSON output structure written to stdout on headless completion.
#[derive(Debug, Serialize)]
struct HeadlessJsonOutput {
    result: HeadlessResultKind,
    iterations: u32,
    summary: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    last_review: Option<ReviewerOutput>,
    #[serde(skip_serializing_if = "Option::is_none")]
    last_fix: Option<RevieweeOutput>,
}

/// Event loop that processes RallyEvents and auto-responds to interactive requests.
///
/// Headless policy:
/// - Clarification: auto-skip (continue with best judgment)
/// - Permission: auto-deny (prevents dynamic tool expansion without human review)
/// - PostConfirmation: respect auto_post config; if auto_post=false, auto-approve
/// - AgentText: suppressed (prevents structured output JSON leakage)
/// - AgentThinking: suppressed (noise reduction)
async fn run_headless_event_loop(
    event_rx: &mut mpsc::Receiver<RallyEvent>,
    cmd_tx: &mpsc::Sender<OrchestratorCommand>,
    local_mode: bool,
) -> HeadlessOutcome {
    let mut last_error: Option<String> = None;
    let mut current_iteration: u32 = 0;
    let mut last_review: Option<ReviewerOutput> = None;
    let mut last_fix: Option<RevieweeOutput> = None;

    while let Some(event) = event_rx.recv().await {
        match event {
            RallyEvent::IterationStarted(n) => {
                current_iteration = n;
                eprintln!("\n=== Iteration {} ===", n);
            }
            RallyEvent::StateChanged(state) => match state {
                RallyState::ReviewerReviewing => {
                    eprintln!("[Reviewer] Reviewing...");
                }
                RallyState::RevieweeFix => {
                    eprintln!("[Reviewee] Fixing...");
                }
                RallyState::Completed => {
                    // Will be handled by Approved event
                }
                RallyState::Aborted => {
                    return HeadlessOutcome {
                        result: HeadlessResult::NotApproved(
                            last_error.unwrap_or_else(|| "Aborted".to_string()),
                        ),
                        iterations: current_iteration,
                        last_review,
                        last_fix,
                    };
                }
                RallyState::Error => {
                    return HeadlessOutcome {
                        result: HeadlessResult::Error(
                            last_error.unwrap_or_else(|| "Unknown error".to_string()),
                        ),
                        iterations: current_iteration,
                        last_review,
                        last_fix,
                    };
                }
                _ => {}
            },
            RallyEvent::ReviewCompleted(output) => {
                eprintln!("{}", format_review_output(&output));
                last_review = Some(output);
            }
            RallyEvent::FixCompleted(output) => {
                eprintln!("{}", format_fix_output(&output));
                last_fix = Some(output);
            }
            RallyEvent::Approved(summary) => {
                eprintln!("\n[Approved] {}", summary);
                return HeadlessOutcome {
                    result: HeadlessResult::Approved(summary),
                    iterations: current_iteration,
                    last_review,
                    last_fix,
                };
            }
            RallyEvent::Error(msg) => {
                eprintln!("\n[Error] {}", msg);
                last_error = Some(msg);
            }
            RallyEvent::Log(msg) => {
                eprintln!("  {}", msg);
            }
            RallyEvent::AgentToolUse(name, _input) => {
                eprintln!("  > {}", name);
            }
            RallyEvent::AgentToolResult(name, result) => {
                let truncated = truncate_str(&result, 200);
                eprintln!("  < {}: {}", name, truncated);
            }
            // Suppress AgentThinking, AgentText, and pause events (headless can't pause)
            RallyEvent::AgentThinking(_)
            | RallyEvent::AgentText(_)
            | RallyEvent::Paused
            | RallyEvent::Resumed => {}
            // Auto-skip clarification (headless can't interact)
            RallyEvent::ClarificationNeeded(question) => {
                eprintln!("  [Clarification needed] {}", question);
                eprintln!("  -> Auto-skipping (headless mode)");
                let _ = cmd_tx.send(OrchestratorCommand::SkipClarification).await;
            }
            // Deny permission by default in headless mode.
            // Auto-approving would allow dynamic tool expansion via prompt injection,
            // bypassing the allowedTools constraint. Deny-by-default is the safe choice
            // for non-interactive CI runs.
            RallyEvent::PermissionNeeded(action, reason) => {
                eprintln!("  [Permission needed] {}: {}", action, reason);
                eprintln!("  -> Auto-denying (headless mode, no human to confirm)");
                let _ = cmd_tx
                    .send(OrchestratorCommand::PermissionResponse(false))
                    .await;
            }
            // Post confirmation handling:
            // - local_mode: auto-deny (no PR to post to)
            // - otherwise: auto-approve (headless can't interact)
            RallyEvent::ReviewPostConfirmNeeded(info) => {
                eprintln!(
                    "  [Post review] {}: {} ({} comments)",
                    info.action, info.summary, info.comment_count
                );
                if local_mode {
                    eprintln!("  -> Skipping (local mode, no PR to post to)");
                    let _ = cmd_tx
                        .send(OrchestratorCommand::PostConfirmResponse(false))
                        .await;
                } else {
                    eprintln!("  -> Auto-approving post (headless mode)");
                    let _ = cmd_tx
                        .send(OrchestratorCommand::PostConfirmResponse(true))
                        .await;
                }
            }
            RallyEvent::FixPostConfirmNeeded(info) => {
                eprintln!(
                    "  [Post fix] {} (files: {})",
                    info.summary,
                    info.files_modified.join(", ")
                );
                if local_mode {
                    eprintln!("  -> Skipping (local mode, no PR to post to)");
                    let _ = cmd_tx
                        .send(OrchestratorCommand::PostConfirmResponse(false))
                        .await;
                } else {
                    eprintln!("  -> Auto-approving post (headless mode)");
                    let _ = cmd_tx
                        .send(OrchestratorCommand::PostConfirmResponse(true))
                        .await;
                }
            }
        }
    }

    // Channel closed - orchestrator finished without explicit terminal event
    HeadlessOutcome {
        result: HeadlessResult::NotApproved(
            last_error.unwrap_or_else(|| "Rally ended unexpectedly".to_string()),
        ),
        iterations: current_iteration,
        last_review,
        last_fix,
    }
}

/// Format ReviewerOutput as human-readable text (no JSON).
pub fn format_review_output(output: &ReviewerOutput) -> String {
    let mut lines = Vec::new();

    let action_str = match output.action {
        ReviewAction::Approve => "approve",
        ReviewAction::RequestChanges => "request_changes",
        ReviewAction::Comment => "comment",
    };
    lines.push(format!("[Review] Action: {}", action_str));
    lines.push(format!("  Summary: {}", output.summary));

    if !output.comments.is_empty() {
        lines.push(format!("  Comments ({}):", output.comments.len()));
        for comment in &output.comments {
            let severity = match comment.severity {
                CommentSeverity::Critical => "critical",
                CommentSeverity::Major => "major",
                CommentSeverity::Minor => "minor",
                CommentSeverity::Suggestion => "suggestion",
            };
            let location = format!("{}:{}", comment.path, comment.line);
            lines.push(format!(
                "    - {} [{}] {}",
                location, severity, comment.body
            ));
        }
    }

    if !output.blocking_issues.is_empty() {
        lines.push("  Blocking issues:".to_string());
        for issue in &output.blocking_issues {
            lines.push(format!("    - {}", issue));
        }
    }

    lines.join("\n")
}

/// Format RevieweeOutput as human-readable text (no JSON).
pub fn format_fix_output(output: &RevieweeOutput) -> String {
    let mut lines = Vec::new();

    let status_str = match output.status {
        RevieweeStatus::Completed => "completed",
        RevieweeStatus::NeedsClarification => "needs_clarification",
        RevieweeStatus::NeedsPermission => "needs_permission",
        RevieweeStatus::Error => "error",
    };
    lines.push(format!("[Fix] Status: {}", status_str));
    lines.push(format!("  Summary: {}", output.summary));

    if !output.files_modified.is_empty() {
        lines.push("  Files modified:".to_string());
        for file in &output.files_modified {
            lines.push(format!("    - {}", file));
        }
    }

    if let Some(error) = &output.error_details {
        lines.push(format!("  Error: {}", error));
    }

    lines.join("\n")
}

fn truncate_str(s: &str, max_chars: usize) -> String {
    let char_count = s.chars().count();
    if char_count <= max_chars {
        return s.to_string();
    }
    // Find byte position at the max_chars-th character boundary
    let byte_end = s
        .char_indices()
        .nth(max_chars)
        .map(|(i, _)| i)
        .unwrap_or(s.len());
    format!("{}...", &s[..byte_end])
}

/// Build JSON output from headless outcome (pure function for testability).
fn build_json_output(outcome: &HeadlessOutcome) -> HeadlessJsonOutput {
    let (result_kind, summary) = match &outcome.result {
        HeadlessResult::Approved(summary) => (HeadlessResultKind::Approved, summary.clone()),
        HeadlessResult::NotApproved(reason) => (HeadlessResultKind::NotApproved, reason.clone()),
        HeadlessResult::Error(msg) => (HeadlessResultKind::Error, msg.clone()),
    };
    HeadlessJsonOutput {
        result: result_kind,
        iterations: outcome.iterations,
        summary,
        last_review: outcome.last_review.clone(),
        last_fix: outcome.last_fix.clone(),
    }
}

/// Write JSON output to stdout with flush guarantee and broken pipe safety.
fn write_json_stdout(output: &HeadlessJsonOutput) {
    use std::io::Write;
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    match serde_json::to_writer(&mut handle, output) {
        Ok(()) => {
            let _ = writeln!(handle);
            let _ = handle.flush();
        }
        Err(e) => {
            eprintln!("[Headless] JSON serialization failed: {}", e);
        }
    }
}

/// Write error JSON to stdout for early failures (before event loop starts).
pub fn write_error_json(error: &str) {
    let output = HeadlessJsonOutput {
        result: HeadlessResultKind::Error,
        iterations: 0,
        summary: error.to_string(),
        last_review: None,
        last_fix: None,
    };
    write_json_stdout(&output);
}

/// Collect diff output for untracked files (mirrors loader.rs behavior).
///
/// Uses `git ls-files --others --exclude-standard` to discover untracked files,
/// then `git diff --no-index -- /dev/null <file>` to generate unified diffs.
async fn collect_untracked_diff(dir: &str) -> String {
    // List untracked files (respecting .gitignore)
    let ls_output = tokio::process::Command::new("git")
        .args(["ls-files", "--others", "--exclude-standard"])
        .current_dir(dir)
        .output()
        .await;

    let untracked_files: Vec<String> = match ls_output {
        Ok(output) if output.status.success() => String::from_utf8_lossy(&output.stdout)
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| l.to_string())
            .collect(),
        _ => return String::new(),
    };

    if untracked_files.is_empty() {
        return String::new();
    }

    eprintln!(
        "[Headless] Including {} untracked file(s) in diff",
        untracked_files.len()
    );

    let mut parts = Vec::new();
    for filename in &untracked_files {
        let diff_output = tokio::process::Command::new("git")
            .args([
                "diff",
                "--no-ext-diff",
                "--no-color",
                "--no-index",
                "--",
                "/dev/null",
                filename,
            ])
            .current_dir(dir)
            .output()
            .await;

        if let Ok(output) = diff_output {
            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
            if !stdout.trim().is_empty() {
                parts.push(stdout);
            }
        }
    }

    parts.join("\n")
}

/// Detect base branch for local diff (same logic as app.rs).
fn detect_local_base_branch(working_dir: Option<&str>) -> Option<String> {
    let dir = working_dir.unwrap_or(".");
    let output = std::process::Command::new("git")
        .args(["symbolic-ref", "refs/remotes/origin/HEAD"])
        .current_dir(dir)
        .output()
        .ok()?;

    if output.status.success() {
        let ref_str = String::from_utf8_lossy(&output.stdout);
        ref_str
            .trim()
            .strip_prefix("refs/remotes/origin/")
            .map(|s| s.to_string())
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ai::adapter::{CommentSeverity, ReviewAction, ReviewComment, RevieweeStatus};

    #[test]
    fn test_format_review_output_approve() {
        let output = ReviewerOutput {
            action: ReviewAction::Approve,
            summary: "All looks good".to_string(),
            comments: vec![],
            blocking_issues: vec![],
        };

        let text = format_review_output(&output);
        assert!(text.contains("[Review] Action: approve"));
        assert!(text.contains("Summary: All looks good"));
        assert!(!text.contains("{"));
        assert!(!text.contains("}"));
    }

    #[test]
    fn test_format_review_output_request_changes() {
        let output = ReviewerOutput {
            action: ReviewAction::RequestChanges,
            summary: "Found 2 issues".to_string(),
            comments: vec![
                ReviewComment {
                    path: "src/main.rs".to_string(),
                    line: 42,
                    body: "Variable should be constant".to_string(),
                    severity: CommentSeverity::Major,
                },
                ReviewComment {
                    path: "src/lib.rs".to_string(),
                    line: 10,
                    body: "Consider renaming".to_string(),
                    severity: CommentSeverity::Minor,
                },
            ],
            blocking_issues: vec!["Error handling missing".to_string()],
        };

        let text = format_review_output(&output);
        assert!(text.contains("[Review] Action: request_changes"));
        assert!(text.contains("Comments (2):"));
        assert!(text.contains("src/main.rs:42 [major]"));
        assert!(text.contains("src/lib.rs:10 [minor]"));
        assert!(text.contains("Blocking issues:"));
        assert!(text.contains("Error handling missing"));
        // No JSON artifacts
        assert!(!text.contains("\"action\""));
        assert!(!text.contains("\"summary\""));
    }

    #[test]
    fn test_format_review_output_suggestion_severity() {
        let output = ReviewerOutput {
            action: ReviewAction::Comment,
            summary: "General feedback".to_string(),
            comments: vec![ReviewComment {
                path: "README.md".to_string(),
                line: 1,
                body: "Update docs".to_string(),
                severity: CommentSeverity::Suggestion,
            }],
            blocking_issues: vec![],
        };

        let text = format_review_output(&output);
        assert!(text.contains("README.md:1 [suggestion] Update docs"));
    }

    #[test]
    fn test_format_fix_output_completed() {
        let output = RevieweeOutput {
            status: RevieweeStatus::Completed,
            summary: "Fixed all issues".to_string(),
            files_modified: vec!["src/main.rs".to_string(), "src/lib.rs".to_string()],
            question: None,
            permission_request: None,
            error_details: None,
        };

        let text = format_fix_output(&output);
        assert!(text.contains("[Fix] Status: completed"));
        assert!(text.contains("Summary: Fixed all issues"));
        assert!(text.contains("Files modified:"));
        assert!(text.contains("- src/main.rs"));
        assert!(text.contains("- src/lib.rs"));
        // No JSON artifacts
        assert!(!text.contains("\"status\""));
        assert!(!text.contains("\"files_modified\""));
    }

    #[test]
    fn test_format_fix_output_error() {
        let output = RevieweeOutput {
            status: RevieweeStatus::Error,
            summary: "Build failed".to_string(),
            files_modified: vec![],
            question: None,
            permission_request: None,
            error_details: Some("cargo build exited with code 1".to_string()),
        };

        let text = format_fix_output(&output);
        assert!(text.contains("[Fix] Status: error"));
        assert!(text.contains("Error: cargo build exited with code 1"));
    }

    #[test]
    fn test_truncate_str_short() {
        assert_eq!(truncate_str("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_str_long() {
        let long = "a".repeat(300);
        let result = truncate_str(&long, 200);
        assert!(result.ends_with("..."));
        // 200 ASCII chars + "..."
        assert_eq!(result.chars().count(), 203);
    }

    #[test]
    fn test_truncate_str_multibyte() {
        // Each Japanese char is 3 bytes in UTF-8
        let s = "あいうえおかきくけこ"; // 10 chars, 30 bytes
        let result = truncate_str(s, 5);
        assert_eq!(result, "あいうえお...");
        // Must not panic on multi-byte boundary
    }

    #[test]
    fn test_truncate_str_multibyte_mixed() {
        // Mixed ASCII and multibyte: "aあbいc" = 5 chars, 9 bytes
        let s = "aあbいc";
        assert_eq!(truncate_str(s, 3), "aあb...");
        assert_eq!(truncate_str(s, 5), "aあbいc");
        assert_eq!(truncate_str(s, 6), "aあbいc"); // longer than string
    }

    #[test]
    fn test_truncate_str_emoji() {
        // Emoji can be 4 bytes in UTF-8
        let s = "🎉🎊🎈🎁🎂";
        let result = truncate_str(s, 3);
        assert_eq!(result, "🎉🎊🎈...");
        assert_eq!(truncate_str(s, 5), "🎉🎊🎈🎁🎂");
    }

    #[test]
    fn test_truncate_str_exact_boundary() {
        let s = "abcde";
        assert_eq!(truncate_str(s, 5), "abcde");
        assert_eq!(truncate_str(s, 4), "abcd...");
    }

    #[test]
    fn test_truncate_str_empty() {
        assert_eq!(truncate_str("", 10), "");
        assert_eq!(truncate_str("", 0), "");
    }

    #[test]
    fn test_truncate_str_zero_max() {
        assert_eq!(truncate_str("hello", 0), "...");
    }

    #[test]
    fn test_json_output_approved() {
        let outcome = HeadlessOutcome {
            result: HeadlessResult::Approved("All good, no issues found".to_string()),
            iterations: 2,
            last_review: Some(ReviewerOutput {
                action: ReviewAction::Approve,
                summary: "All good".to_string(),
                comments: vec![],
                blocking_issues: vec![],
            }),
            last_fix: Some(RevieweeOutput {
                status: RevieweeStatus::Completed,
                summary: "Fixed".to_string(),
                files_modified: vec!["src/main.rs".to_string()],
                question: None,
                permission_request: None,
                error_details: None,
            }),
        };
        insta::assert_json_snapshot!(build_json_output(&outcome), @r#"
        {
          "result": "approved",
          "iterations": 2,
          "summary": "All good, no issues found",
          "last_review": {
            "action": "approve",
            "summary": "All good",
            "comments": [],
            "blocking_issues": []
          },
          "last_fix": {
            "status": "completed",
            "summary": "Fixed",
            "files_modified": [
              "src/main.rs"
            ]
          }
        }
        "#);
    }

    #[test]
    fn test_json_output_not_approved() {
        let outcome = HeadlessOutcome {
            result: HeadlessResult::NotApproved("Max iterations reached".to_string()),
            iterations: 3,
            last_review: Some(ReviewerOutput {
                action: ReviewAction::RequestChanges,
                summary: "Still has issues".to_string(),
                comments: vec![ReviewComment {
                    path: "src/lib.rs".to_string(),
                    line: 10,
                    body: "Fix this".to_string(),
                    severity: CommentSeverity::Major,
                }],
                blocking_issues: vec!["Error handling".to_string()],
            }),
            last_fix: Some(RevieweeOutput {
                status: RevieweeStatus::Completed,
                summary: "Attempted fix".to_string(),
                files_modified: vec!["src/lib.rs".to_string()],
                question: None,
                permission_request: None,
                error_details: None,
            }),
        };
        insta::assert_json_snapshot!(build_json_output(&outcome), @r#"
        {
          "result": "not_approved",
          "iterations": 3,
          "summary": "Max iterations reached",
          "last_review": {
            "action": "request_changes",
            "summary": "Still has issues",
            "comments": [
              {
                "path": "src/lib.rs",
                "line": 10,
                "body": "Fix this",
                "severity": "major"
              }
            ],
            "blocking_issues": [
              "Error handling"
            ]
          },
          "last_fix": {
            "status": "completed",
            "summary": "Attempted fix",
            "files_modified": [
              "src/lib.rs"
            ]
          }
        }
        "#);
    }

    #[test]
    fn test_json_output_error_no_review() {
        let outcome = HeadlessOutcome {
            result: HeadlessResult::Error("Agent crashed".to_string()),
            iterations: 0,
            last_review: None,
            last_fix: None,
        };
        let output = build_json_output(&outcome);
        // None fields should be omitted via skip_serializing_if
        let json = serde_json::to_value(&output).unwrap();
        assert!(!json.as_object().unwrap().contains_key("last_review"));
        assert!(!json.as_object().unwrap().contains_key("last_fix"));
        insta::assert_json_snapshot!(output, @r#"
        {
          "result": "error",
          "iterations": 0,
          "summary": "Agent crashed"
        }
        "#);
    }

    #[test]
    fn test_collect_sensitive_overrides_empty_when_no_local_overrides() {
        let config = Config::default();
        let overrides = collect_sensitive_overrides(&config);
        assert!(overrides.is_empty());
    }

    #[test]
    fn test_collect_sensitive_overrides_detects_ai_config_keys() {
        let mut config = Config::default();
        config
            .local_overrides
            .insert("ai.reviewer".to_string());
        config
            .local_overrides
            .insert("ai.reviewee_additional_tools".to_string());

        let overrides = collect_sensitive_overrides(&config);
        assert_eq!(overrides.len(), 2);
        assert!(overrides.iter().any(|o| o.as_ref() == "ai.reviewer"));
        assert!(overrides
            .iter()
            .any(|o| o.as_ref() == "ai.reviewee_additional_tools"));
    }

    #[test]
    fn test_collect_sensitive_overrides_ignores_non_sensitive_keys() {
        let mut config = Config::default();
        // Non-sensitive keys should not appear
        config
            .local_overrides
            .insert("diff.theme".to_string());
        config
            .local_overrides
            .insert("keybindings.move_down".to_string());

        let overrides = collect_sensitive_overrides(&config);
        assert!(overrides.is_empty());
    }

    #[test]
    fn test_collect_sensitive_overrides_detects_local_prompt_files() {
        let dir = tempfile::tempdir().unwrap();
        let project_root = dir.path().join("project");
        let prompts_dir = project_root.join(".octorus/prompts");
        std::fs::create_dir_all(&prompts_dir).unwrap();
        std::fs::write(prompts_dir.join("reviewer.md"), "custom prompt").unwrap();

        let mut config = Config::default();
        config.project_root = project_root;

        let overrides = collect_sensitive_overrides(&config);
        assert_eq!(overrides.len(), 1);
        assert!(overrides[0].as_ref().contains("local prompt: reviewer.md"));
    }

    #[test]
    fn test_collect_sensitive_overrides_combines_config_and_prompt_overrides() {
        let dir = tempfile::tempdir().unwrap();
        let project_root = dir.path().join("project");
        let prompts_dir = project_root.join(".octorus/prompts");
        std::fs::create_dir_all(&prompts_dir).unwrap();
        std::fs::write(prompts_dir.join("reviewee.md"), "custom").unwrap();

        let mut config = Config::default();
        config.project_root = project_root;
        config
            .local_overrides
            .insert("ai.auto_post".to_string());

        let overrides = collect_sensitive_overrides(&config);
        assert_eq!(overrides.len(), 2);
        assert!(overrides.iter().any(|o| o.as_ref() == "ai.auto_post"));
        assert!(overrides
            .iter()
            .any(|o| o.as_ref().contains("local prompt: reviewee.md")));
    }
}