nitpicker 0.11.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
use eyre::{Result, WrapErr};
use nitpicker_agent::AgentBuilder;
use nitpicker_agent::agent::AgentResult;
use nitpicker_agent::config::{Config, ReviewerConfig};
use nitpicker_agent::provider::build_reviewer_client;
use nitpicker_agent::session::now_unix_ms;
use nitpicker_agent::tools::{GlobTool, GrepTool, ReadFileTool, Tool};
use rig_core::completion::ToolDefinition;
use rig_core::message::ToolName;
use serde::Serialize;
use serde_json::{Value, json};
use std::collections::{HashMap, VecDeque};
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};

const CODER_SYSTEM_PROMPT: &str = include_str!("../prompts/build/coder.md");
pub(crate) const DEFAULT_MAX_TURNS: usize = 200;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);
const MAX_TIMEOUT: Duration = Duration::from_secs(600);
const MAX_STREAM_BYTES: usize = 20_000;
/// Share of a clipped stream kept from its start; the rest comes from the end.
const HEAD_STREAM_BYTES: usize = 8_000;
// credentials stay out of the child: whatever a command prints goes to the model provider
const ENV_ALLOWLIST: &[&str] = &[
    "PATH",
    "HOME",
    "USER",
    "LOGNAME",
    "SHELL",
    "TMPDIR",
    "LANG",
    "LC_ALL",
    "CARGO_HOME",
    "RUSTUP_HOME",
];

pub(crate) struct BuildArgs<'a> {
    pub(crate) repo: &'a Path,
    pub(crate) task: &'a str,
    pub(crate) coder: Option<&'a str>,
    pub(crate) max_turns: usize,
    pub(crate) trajectory_dir: Option<&'a Path>,
}

#[derive(Serialize)]
struct Usage {
    model: String,
    turns: usize,
    tool_calls: usize,
    input_tokens: u64,
    cached_input_tokens: u64,
    output_tokens: u64,
}

impl Usage {
    fn new(model: &str, result: &AgentResult) -> Self {
        Self {
            model: model.to_string(),
            turns: result.turns,
            tool_calls: result.tool_calls,
            input_tokens: result.usage.input_tokens,
            cached_input_tokens: result.usage.cached_input_tokens,
            output_tokens: result.usage.output_tokens,
        }
    }
}

pub(crate) async fn run_build(config: &Config, args: BuildArgs<'_>) -> Result<String> {
    if let Some(dir) = args.trajectory_dir {
        std::fs::create_dir_all(dir)
            .wrap_err_with(|| format!("failed to create {}", dir.display()))?;
    }
    let coder = select_reviewer(config, args.coder)?;
    let gemini_proxy = crate::proxy::GeminiProxy::start_for([coder], None).await;
    let context = crate::context::build_context(args.repo).await;
    eprintln!("coder: {} ({})", coder.name, coder.model);
    let bash_log = args
        .trajectory_dir
        .map(|dir| Arc::new(dir.join("bash.jsonl")));
    let result = agent(config, coder, gemini_proxy.url().as_deref(), &context, args.max_turns)?
        .run(args.task, &coder_tools(bash_log), args.repo)
        .await?;
    let usage = Usage::new(&coder.model, &result);
    eprintln!(
        "done: {} turns, {} tool calls, {} input ({} cached) / {} output tokens",
        usage.turns,
        usage.tool_calls,
        usage.input_tokens,
        usage.cached_input_tokens,
        usage.output_tokens
    );
    if let Some(dir) = args.trajectory_dir {
        let written = serde_json::to_vec_pretty(&usage)
            .map_err(eyre::Report::from)
            .and_then(|json| Ok(std::fs::write(dir.join("usage.json"), json)?));
        if let Err(err) = written {
            tracing::warn!(error = %err, "failed to write usage.json");
        }
    }
    Ok(result.text)
}

fn agent(
    config: &Config,
    reviewer: &ReviewerConfig,
    proxy_url: Option<&str>,
    context: &str,
    max_turns: usize,
) -> Result<AgentBuilder> {
    let client = build_reviewer_client(reviewer, proxy_url)?;
    let mut builder = AgentBuilder::new("coder", &reviewer.model, CODER_SYSTEM_PROMPT, client)
        .max_turns(max_turns);
    if let Some(threshold) = config.reviewer_compact_threshold(reviewer) {
        builder = builder.compact_threshold(threshold);
    }
    if let Some(max_tokens) = reviewer.max_tokens.and_then(NonZeroU64::new) {
        builder = builder.max_tokens(max_tokens);
    }
    if !context.is_empty() {
        builder = builder.project_context(context);
    }
    Ok(builder)
}

fn select_reviewer<'a>(config: &'a Config, name: Option<&str>) -> Result<&'a ReviewerConfig> {
    match name {
        None => config
            .reviewer
            .first()
            .ok_or_else(|| eyre::eyre!("config must have at least one reviewer")),
        Some(name) => config
            .reviewer
            .iter()
            .find(|reviewer| reviewer.name == name)
            .ok_or_else(|| {
                let known: Vec<&str> = config.reviewer.iter().map(|r| r.name.as_str()).collect();
                eyre::eyre!(
                    "no reviewer named '{name}'; configured: {}",
                    known.join(", ")
                )
            }),
    }
}

fn coder_tools(bash_log: Option<Arc<PathBuf>>) -> HashMap<String, Arc<dyn Tool>> {
    let tools: [Arc<dyn Tool>; 4] = [
        Arc::new(BashTool { log: bash_log }),
        Arc::new(ReadFileTool),
        Arc::new(GlobTool),
        Arc::new(GrepTool),
    ];
    tools.into_iter().map(|tool| (tool.name(), tool)).collect()
}

struct BashTool {
    log: Option<Arc<PathBuf>>,
}

impl Tool for BashTool {
    fn name(&self) -> String {
        "bash".to_string()
    }

    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: ToolName::new("bash").unwrap(),
            annotations: Default::default(),
            description: "Run a bash command in the repository root. Returns the exit code, stdout, and stderr (each clipped to 20,000 bytes: the first 8,000 and the last 12,000, with a marker in between). No stdin; killed on timeout.".to_string(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "command": {"type": "string", "description": "Command passed to `bash -c`"},
                    "timeout_secs": {"type": "integer", "minimum": 1, "maximum": MAX_TIMEOUT.as_secs(), "description": "Default 120"}
                },
                "required": ["command"],
                "additionalProperties": false
            }),
        }
    }

    fn call(
        &self,
        args: Value,
        work_dir: PathBuf,
    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
        let log = self.log.clone();
        Box::pin(async move {
            let command = args
                .get("command")
                .and_then(Value::as_str)
                .ok_or_else(|| eyre::eyre!("missing command"))?
                .to_string();
            let timeout = match args.get("timeout_secs").and_then(Value::as_u64) {
                Some(secs) => Duration::from_secs(secs).min(MAX_TIMEOUT),
                None => DEFAULT_TIMEOUT,
            };
            let result = run_bash(&command, &work_dir, timeout).await;
            if let Some(log) = log {
                append_bash_log(&log, &command, &result).await;
            }
            result
        })
    }

    fn exclusive(&self) -> bool {
        true
    }
}

async fn append_bash_log(log: &Path, command: &str, result: &Result<String>) {
    let entry = match result {
        Ok(output) => json!({"ts_unix_ms": now_unix_ms(), "command": command, "output": output}),
        Err(err) => {
            json!({"ts_unix_ms": now_unix_ms(), "command": command, "error": format!("{err:#}")})
        }
    };
    let mut line = entry.to_string();
    line.push('\n');
    let written = async {
        let mut file = tokio::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(log)
            .await?;
        file.write_all(line.as_bytes()).await?;
        file.flush().await
    };
    if let Err(err) = written.await {
        tracing::warn!(error = %err, "failed to write bash log");
    }
}

async fn run_bash(command: &str, work_dir: &Path, timeout: Duration) -> Result<String> {
    let mut cmd = tokio::process::Command::new("bash");
    cmd.arg("-c")
        .arg(command)
        .current_dir(work_dir)
        .env_clear()
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    for key in ENV_ALLOWLIST {
        if let Ok(value) = std::env::var(key) {
            cmd.env(key, value);
        }
    }
    #[cfg(unix)]
    cmd.process_group(0);
    let mut child = cmd.spawn().wrap_err("failed to spawn bash")?;
    let pid = child.id();
    let stdout = child.stdout.take().expect("stdout is piped");
    let stderr = child.stderr.take().expect("stderr is piped");
    // drain both pipes while the command runs, keeping only the clipped head and tail, so a
    // runaway command can't exhaust memory before the timeout fires
    let finished = async {
        let (stdout, stderr, status) = tokio::join!(drain(stdout), drain(stderr), child.wait());
        Ok::<_, std::io::Error>((stdout?, stderr?, status?))
    };
    match tokio::time::timeout(timeout, finished).await {
        Ok(output) => {
            let (stdout, stderr, status) = output.wrap_err("failed to wait for bash")?;
            let code = match status.code() {
                Some(code) => code.to_string(),
                None => "killed by signal".to_string(),
            };
            Ok(format!(
                "exit code: {code}\n--- stdout ---\n{}\n--- stderr ---\n{}",
                stdout.render(),
                stderr.render()
            ))
        }
        Err(_) => {
            kill_group(pid);
            eyre::bail!(
                "command timed out after {}s and was killed",
                timeout.as_secs()
            )
        }
    }
}

fn kill_group(pid: Option<u32>) {
    #[cfg(unix)]
    if let Some(pid) = pid.and_then(|pid| i32::try_from(pid).ok()) {
        // SAFETY: plain syscall on the process group this function's child leads
        unsafe {
            libc::kill(-pid, libc::SIGKILL);
        }
    }
    #[cfg(not(unix))]
    let _ = pid;
}

async fn drain(mut reader: impl AsyncRead + Unpin) -> std::io::Result<Clipped> {
    let mut clipped = Clipped::default();
    let mut buf = [0u8; 8192];
    loop {
        match reader.read(&mut buf).await? {
            0 => return Ok(clipped),
            n => clipped.push(&buf[..n]),
        }
    }
}

/// A stream's first and last bytes, plus how many there were. Each side keeps a few bytes of
/// slack so a char straddling the cut is still whole when rendering trims to a boundary.
#[derive(Default)]
struct Clipped {
    head: Vec<u8>,
    tail: VecDeque<u8>,
    total: usize,
}

const TAIL_STREAM_BYTES: usize = MAX_STREAM_BYTES - HEAD_STREAM_BYTES;
const UTF8_SLACK: usize = 3;

impl Clipped {
    fn push(&mut self, mut bytes: &[u8]) {
        self.total += bytes.len();
        let room = (HEAD_STREAM_BYTES + UTF8_SLACK).saturating_sub(self.head.len());
        let (head, rest) = bytes.split_at(room.min(bytes.len()));
        self.head.extend_from_slice(head);
        bytes = rest;
        self.tail.extend(bytes);
        let excess = self.tail.len().saturating_sub(TAIL_STREAM_BYTES + UTF8_SLACK);
        self.tail.drain(..excess);
    }

    fn render(&self) -> String {
        if self.total <= MAX_STREAM_BYTES {
            let mut bytes = self.head.clone();
            bytes.extend(&self.tail);
            return String::from_utf8_lossy(&bytes).into_owned();
        }
        let head = String::from_utf8_lossy(&self.head);
        let head = &head[..head.floor_char_boundary(HEAD_STREAM_BYTES)];
        let tail = String::from_utf8_lossy(&self.tail.iter().copied().collect::<Vec<u8>>()).into_owned();
        let tail = &tail[tail.ceil_char_boundary(tail.len().saturating_sub(TAIL_STREAM_BYTES))..];
        format!(
            "{head}\n... {} bytes omitted ...\n{tail}",
            self.total - head.len() - tail.len()
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn bash_reports_nonzero_exit_as_output() {
        let dir = tempfile::tempdir().unwrap();
        let out = run_bash(
            "echo hi; echo oops >&2; exit 3",
            dir.path(),
            DEFAULT_TIMEOUT,
        )
        .await
        .unwrap();
        assert_eq!(
            out,
            "exit code: 3\n--- stdout ---\nhi\n\n--- stderr ---\noops\n"
        );
    }

    #[tokio::test]
    async fn bash_timeout_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let started = std::time::Instant::now();
        let err = run_bash("sleep 30", dir.path(), Duration::from_millis(200)).await;
        assert!(err.is_err());
        assert!(started.elapsed() < Duration::from_secs(5));
    }

    #[tokio::test]
    async fn bash_log_records_command_and_output() {
        let dir = tempfile::tempdir().unwrap();
        let log = Arc::new(dir.path().join("bash.jsonl"));
        let tool = BashTool {
            log: Some(Arc::clone(&log)),
        };
        tool.call(json!({"command": "echo hi"}), dir.path().to_path_buf())
            .await
            .unwrap();
        let line: Value =
            serde_json::from_str(std::fs::read_to_string(log.as_ref()).unwrap().trim()).unwrap();
        assert_eq!(line["command"], "echo hi");
        assert_eq!(
            line["output"],
            "exit code: 0\n--- stdout ---\nhi\n\n--- stderr ---\n"
        );
    }

    fn clip(bytes: &[u8]) -> String {
        let mut clipped = Clipped::default();
        for chunk in bytes.chunks(7) {
            clipped.push(chunk);
        }
        clipped.render()
    }

    #[test]
    fn clip_keeps_head_and_tail_on_char_boundaries() {
        let head = format!("{}é", "a".repeat(HEAD_STREAM_BYTES - 1));
        let tail_len = MAX_STREAM_BYTES - HEAD_STREAM_BYTES;
        let tail = format!("é{}", "c".repeat(tail_len - 1));
        let text = format!("{head}{}{tail}", "b".repeat(1000));
        let out = clip(text.as_bytes());
        let omitted = text.len() - (HEAD_STREAM_BYTES - 1) - (tail_len - 1);
        assert_eq!(
            out,
            format!(
                "{}\n... {omitted} bytes omitted ...\n{}",
                "a".repeat(HEAD_STREAM_BYTES - 1),
                "c".repeat(tail_len - 1)
            )
        );
    }

    #[tokio::test]
    async fn bash_clips_large_output_while_streaming() {
        let dir = tempfile::tempdir().unwrap();
        let out = run_bash("yes | head -c 5000000", dir.path(), DEFAULT_TIMEOUT)
            .await
            .unwrap();
        assert!(out.len() < MAX_STREAM_BYTES + 200);
        assert!(out.contains(&format!("... {} bytes omitted ...", 5_000_000 - MAX_STREAM_BYTES)));
    }

    #[test]
    fn clip_leaves_short_output_untouched() {
        let text = "x".repeat(MAX_STREAM_BYTES);
        assert_eq!(clip(text.as_bytes()), text);
    }
}