nitpicker 0.2.2

Multi-reviewer code review using LLMs with parallel agents and debate mode
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
use clap::{Args as ClapArgs, Parser, Subcommand};
use eyre::Result;
use std::path::{Path, PathBuf};
use tracing_subscriber::EnvFilter;

mod agent;
mod compact;
mod config;
mod debate;
mod gemini_proxy;
mod llm;
mod openrouter;
mod pr;
mod prompts;
mod provider;
mod review;
mod session;
mod tools;

/// Flags shared between the default review mode and the ask subcommand.
#[derive(Debug, ClapArgs)]
struct CommonArgs {
    #[arg(long, default_value = ".")]
    repo: PathBuf,

    #[arg(long)]
    config: Option<PathBuf>,

    #[arg(long, short)]
    verbose: bool,
}

#[derive(Debug, Parser)]
#[command(name = "nitpicker")]
struct Args {
    #[command(subcommand)]
    command: Option<Command>,

    #[command(flatten)]
    common: CommonArgs,

    #[arg(
        long,
        help = "Additional review instructions appended to the diff context (use `ask` for fully custom prompts)"
    )]
    prompt: Option<String>,

    #[arg(long = "gemini-oauth")]
    gemini_oauth: bool,

    /// Analyze existing code instead of reviewing changes
    #[arg(long, value_name = "PATH", num_args = 0..=1, default_missing_value = "")]
    analyze: Option<PathBuf>,

    /// Disable actor-critic debate and use parallel aggregation instead
    #[arg(long)]
    no_debate: bool,

    /// Maximum debate rounds
    #[arg(long, default_value = "5")]
    rounds: usize,

    /// Maximum tool-use turns per agent or debate turn
    #[arg(long, value_parser = parse_positive_usize)]
    max_turns: Option<usize>,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Generate a nitpicker config template
    Init {
        /// Write to ~/.nitpicker/config.toml instead of ./nitpicker.toml
        #[arg(long)]
        global: bool,
    },
    /// Ask multiple LLM agents a free-form question about the codebase
    Ask {
        #[command(flatten)]
        common: CommonArgs,
        /// Question or topic to discuss
        topic: String,
        /// Disable actor-critic debate and use parallel aggregation instead
        #[arg(long)]
        no_debate: bool,
        /// Maximum debate rounds
        #[arg(long, default_value = "5")]
        rounds: usize,
        /// Maximum tool-use turns per agent or debate turn
        #[arg(long, value_parser = parse_positive_usize)]
        max_turns: Option<usize>,
    },
    /// Review a GitHub PR (current branch's PR or a remote PR by URL)
    Pr(pr::PrArgs),
}

const INIT_TEMPLATE: &str = r#"[defaults]
debate = true
max_turns = 70
log_trajectories = false

[aggregator]
model = "claude-sonnet-4-6"
provider = "anthropic"

[[reviewer]]
name = "claude"
model = "claude-sonnet-4-6"
provider = "anthropic"

[[reviewer]]
name = "gemini"
model = "gemini-3-flash-preview"
provider = "gemini"
auth = "oauth"
"#;

#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();

    let verbose = args.common.verbose
        || matches!(&args.command, Some(Command::Ask { common, .. }) if common.verbose)
        || matches!(&args.command, Some(Command::Pr(a)) if a.common.verbose);
    let default_level = if verbose { "info" } else { "warn" };
    let filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_level));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_target(false)
        .with_thread_ids(false)
        .with_thread_names(false)
        .with_file(false)
        .with_line_number(false)
        .with_level(true)
        .with_ansi(true)
        .compact()
        .init();

    match args.command {
        Some(Command::Init { global }) => {
            let path = init_config_path(global)?;
            if path.exists() {
                eyre::bail!("{} already exists", path.display());
            }
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&path, INIT_TEMPLATE)?;
            println!("Created {}", path.display());
            return Ok(());
        }
        Some(Command::Ask {
            common,
            topic,
            no_debate,
            rounds,
            max_turns,
        }) => {
            let repo = common.repo.canonicalize()?;
            if !repo.join(".git").is_dir() {
                eyre::bail!("--repo must point to a git repository (missing .git)");
            }
            let mut config = load_config(common.config.as_deref(), &repo)?;
            openrouter::resolve_free_models(&mut config).await?;
            let max_turns = config.max_turns(max_turns)?;

            if !no_debate && config.default_debate() {
                let report = debate::run_debate(
                    &repo,
                    &topic,
                    &config,
                    rounds,
                    max_turns,
                    common.verbose,
                    debate::DebateMode::Topic,
                )
                .await?;
                println!("{report}");
                return Ok(());
            }

            let report = review::run_review(
                &repo,
                &topic,
                &config,
                max_turns,
                common.verbose,
                review::TaskMode::Ask,
            )
            .await?;
            println!("{report}");
            return Ok(());
        }
        Some(Command::Pr(pr_args)) => {
            let mut config = load_config(pr_args.common.config.as_deref(), &pr_args.common.repo)?;
            openrouter::resolve_free_models(&mut config).await?;
            return pr::run_pr(pr_args, config).await;
        }
        None => {}
    }

    if args.gemini_oauth {
        println!("Starting Gemini OAuth authentication flow...");
        let proxy_client = gemini_proxy::GeminiProxyClient::new().await?;
        match proxy_client.check_auth_status()? {
            gemini_proxy::AuthStatus::Valid => {
                println!("✓ Authentication successful! Token is valid.");
            }
            gemini_proxy::AuthStatus::ExpiredButRefreshable => {
                println!("âš  Token expired but can be refreshed on next use.");
            }
            _ => {
                println!("✗ Authentication failed.");
                std::process::exit(1);
            }
        }
        return Ok(());
    }

    let repo = args.common.repo.canonicalize()?;
    if !repo.join(".git").is_dir() {
        eyre::bail!("--repo must point to a git repository (missing .git)");
    }

    let mut config = load_config(args.common.config.as_deref(), &repo)?;
    openrouter::resolve_free_models(&mut config).await?;
    let max_turns = config.max_turns(args.max_turns)?;

    let prompt = if let Some(path) = args.analyze {
        let path_opt = if path.as_os_str().is_empty() {
            None
        } else {
            Some(path.as_path())
        };
        build_analysis_prompt(path_opt, args.prompt.as_deref())
    } else {
        let base = detect_diff_context(&repo)?;
        match args.prompt {
            Some(p) => format!("{base}\n\nAdditional instructions: {p}"),
            None => base,
        }
    };

    if !args.no_debate && config.default_debate() {
        let report = debate::run_debate(
            &repo,
            &prompt,
            &config,
            args.rounds,
            max_turns,
            args.common.verbose,
            debate::DebateMode::Review,
        )
        .await?;
        println!("{report}");
        Ok(())
    } else {
        let report = review::run_review(
            &repo,
            &prompt,
            &config,
            max_turns,
            args.common.verbose,
            review::TaskMode::Review,
        )
        .await?;
        println!("{report}");
        Ok(())
    }
}

fn load_config(explicit_path: Option<&Path>, repo: &Path) -> Result<config::Config> {
    if let Some(path) = explicit_path {
        let content = std::fs::read_to_string(path)
            .map_err(|e| eyre::eyre!("failed to read config {:?}: {e}", path))?;
        return toml::from_str(&content).map_err(|e| eyre::eyre!("invalid config: {e}"));
    }

    let repo_config = repo.join("nitpicker.toml");
    if repo_config.exists() {
        let content = std::fs::read_to_string(&repo_config)
            .map_err(|e| eyre::eyre!("failed to read config {:?}: {e}", repo_config))?;
        return toml::from_str(&content).map_err(|e| eyre::eyre!("invalid config: {e}"));
    }

    if let Some(home) = dirs::home_dir() {
        let global_config = home.join(".nitpicker").join("config.toml");
        if global_config.exists() {
            let content = std::fs::read_to_string(&global_config)
                .map_err(|e| eyre::eyre!("failed to read config {:?}: {e}", global_config))?;
            return toml::from_str(&content).map_err(|e| eyre::eyre!("invalid config: {e}"));
        }
    }

    eyre::bail!(
        "no config found. create one with:\n  \
         nitpicker init\n\n\
         or at global location:\n  \
         ~/.nitpicker/config.toml"
    )
}

fn init_config_path(global: bool) -> Result<PathBuf> {
    if global {
        let home =
            dirs::home_dir().ok_or_else(|| eyre::eyre!("failed to resolve home directory"))?;
        Ok(home.join(".nitpicker").join("config.toml"))
    } else {
        Ok(Path::new("nitpicker.toml").to_path_buf())
    }
}

pub(crate) fn parse_positive_usize(value: &str) -> Result<usize, String> {
    let parsed = value
        .parse::<usize>()
        .map_err(|_| format!("invalid positive integer: {value}"))?;

    if parsed == 0 {
        return Err("value must be greater than 0".to_string());
    }

    Ok(parsed)
}

fn build_analysis_prompt(path: Option<&Path>, custom_prompt: Option<&str>) -> String {
    let target = match path {
        Some(p) => format!("`{}`", p.display()),
        None => "the entire repository".to_string(),
    };
    let base = format!(
        "Analyze the following code for issues and improvement opportunities:\n\
         - Target: {}\n\
         - Focus: correctness, security, performance, maintainability",
        target
    );
    match custom_prompt {
        Some(p) if !p.trim().is_empty() => {
            format!("{}\n\nAdditional instructions: {}", base, p)
        }
        _ => base,
    }
}

pub(crate) struct BaseBranch {
    pub(crate) name: String,
    pub(crate) revision: String,
}

pub fn detect_diff_context(repo: &Path) -> Result<String> {
    let branch = run_git(repo, &["rev-parse", "--abbrev-ref", "HEAD"])?;
    let branch = branch.trim();

    if branch == "HEAD" {
        eyre::bail!("detached HEAD state: checkout a branch before running nitpicker");
    }

    let base = detect_base_branch(repo);

    let has_uncommitted = !run_git(repo, &["status", "--porcelain"])
        .unwrap_or_default()
        .trim()
        .is_empty();

    let has_branch_commits = match base.as_ref() {
        Some(base) if branch != base.name => !run_git(
            repo,
            &["log", &format!("{}..HEAD", base.revision), "--oneline"],
        )?
        .trim()
        .is_empty(),
        _ => false,
    };

    if !has_uncommitted && !has_branch_commits {
        if let Some(base) = base.as_ref() {
            eyre::bail!(
                "no changes to review: no uncommitted changes and no branch commits vs {}",
                base.name
            );
        }
        eyre::bail!(
            "no changes to review: no uncommitted changes and no detectable base branch commits"
        );
    }

    let mut parts = Vec::new();
    if has_uncommitted {
        parts.push("- uncommitted changes (`git diff HEAD`)".to_string());
    }
    if has_branch_commits {
        let base = base
            .as_ref()
            .ok_or_else(|| eyre::eyre!("base branch required when branch commits are present"))?;
        parts.push(format!(
            "- commits on this branch vs {} (`git log {}..HEAD`, `git diff {}...HEAD`)",
            base.name, base.revision, base.revision
        ));
    }

    Ok(format!(
        "Review the following changes:\n{}",
        parts.join("\n")
    ))
}

pub(crate) fn detect_base_branch(repo: &Path) -> Option<BaseBranch> {
    run_git(repo, &["symbolic-ref", "refs/remotes/origin/HEAD"])
        .ok()
        .and_then(|s| {
            s.trim()
                .strip_prefix("refs/remotes/origin/")
                .map(str::to_string)
        })
        .and_then(|branch| resolve_base_branch(repo, &branch))
        .or_else(|| {
            ["main", "master"]
                .into_iter()
                .find_map(|branch| resolve_base_branch(repo, branch))
        })
}

fn resolve_base_branch(repo: &Path, branch: &str) -> Option<BaseBranch> {
    let local = format!("refs/heads/{branch}");
    if run_git(repo, &["rev-parse", "--verify", &local]).is_ok() {
        return Some(BaseBranch {
            name: branch.to_string(),
            revision: branch.to_string(),
        });
    }

    let remote = format!("refs/remotes/origin/{branch}");
    if run_git(repo, &["rev-parse", "--verify", &remote]).is_ok() {
        return Some(BaseBranch {
            name: branch.to_string(),
            revision: format!("origin/{branch}"),
        });
    }

    None
}

fn run_git(repo: &Path, args: &[&str]) -> Result<String> {
    let output = std::process::Command::new("git")
        .args(args)
        .current_dir(repo)
        .output()?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eyre::bail!("git {}: {}", args.join(" "), stderr.trim());
    }
    Ok(String::from_utf8(output.stdout)?)
}