caretta 0.11.9

caretta agent
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
use crate::agent::bot::resolve_bot_token;
use crate::agent::cmd::{cmd_run, cmd_run_env, cmd_stdout, log};
use crate::agent::issue::preflight;
use crate::agent::launch::log_resolved_agent_launch;
use crate::agent::process::{emit_event, stop_requested};
use crate::agent::run::{run_agent_with_env, run_agent_with_env_in_dir};
use crate::agent::tracker::{
    DEFAULT_REVIEW_BOT_LOGIN, ReviewThread, build_code_review_prompt, build_pr_review_fix_prompt,
    build_pr_review_verification_prompt, build_review_followup_code_review_prompt,
    build_security_review_prompt, fetch_all_unresolved_review_threads,
    fetch_unresolved_review_threads, list_open_prs, parse_verification_verdict, pr_body, pr_diff,
    pr_head_branch, pr_review_decision, resolve_review_thread,
};
use crate::agent::types::{AgentEvent, Config};
use std::path::{Path, PathBuf};

pub fn run_code_review(cfg: &Config, only_pr: Option<u32>) {
    preflight(cfg);
    log("Starting code review...");

    // Resolve bot token so the review subprocess runs under the bot identity.
    let bot_token = cfg
        .effective_bot_credentials()
        .as_ref()
        .and_then(resolve_bot_token);

    if bot_token.is_none() {
        log(
            "WARNING: No bot credentials configured — reviews will run under your identity \
             (same-author approvals will fail). Set DEV_BOT_TOKEN or configure a GitHub App.",
        );
    }

    let extra_env: Vec<(String, String)> = bot_token
        .as_deref()
        .map(|t| vec![("GH_TOKEN".to_string(), t.to_string())])
        .unwrap_or_default();

    let mut prs = list_open_prs();
    if let Some(n) = only_pr {
        prs.retain(|pr| pr.number == n);
    }
    if prs.is_empty() {
        let msg = if only_pr.is_some() {
            "No open pull request matched the requested number for code review."
        } else {
            "No open PRs to review."
        };
        log(msg);
        emit_event(AgentEvent::Done);
        return;
    }

    log(&format!("Found {} open PR(s)", prs.len()));
    if cfg.dry_run {
        log_resolved_agent_launch(cfg, &[]);
    }

    for pr in &prs {
        log(&format!("Reviewing PR #{}: {}", pr.number, pr.title));

        if cfg.dry_run {
            log(&format!("[dry-run] Would review PR #{}", pr.number));
            continue;
        }

        let body = pr_body(pr.number);
        let diff = pr_diff(pr.number);
        let threads = fetch_unresolved_review_threads(pr.number, DEFAULT_REVIEW_BOT_LOGIN);
        let prompt = if threads.is_empty() {
            build_code_review_prompt(&cfg.project_name, pr.number, &pr.title, &body, &diff)
        } else {
            log(&format!(
                "PR #{} has {} unresolved bot-authored thread(s) — follow-up verification review (not a full audit).",
                pr.number,
                threads.len()
            ));
            build_review_followup_code_review_prompt(
                &cfg.project_name,
                pr.number,
                &pr.title,
                &body,
                &diff,
                &threads,
            )
        };
        run_agent_with_env(cfg, &prompt, &extra_env);
        if stop_requested() {
            log("Stop requested. Code review cancelled.");
            emit_event(AgentEvent::Done);
            return;
        }

        log(&format!("Completed review of PR #{}", pr.number));
    }

    log("All code reviews complete.");
    emit_event(AgentEvent::Done);
}

pub fn run_security_code_review(cfg: &Config) {
    use crate::agent::snapshot::generate_codebase_snapshot;
    preflight(cfg);
    log("Starting security code review...");

    let crate_tree = cmd_stdout("tree", &["-L", "2", "crates"]).unwrap_or_default();
    let snapshot = generate_codebase_snapshot(&cfg.root);
    let prompt =
        build_security_review_prompt(&cfg.project_name, &crate_tree, &snapshot, cfg.dry_run);
    run_agent_with_env(cfg, &prompt, &[]);
    emit_event(AgentEvent::Done);
}

/// RAII guard that removes a git worktree on drop, including on panic.
pub struct WorktreeGuard {
    pub path: PathBuf,
}

impl Drop for WorktreeGuard {
    fn drop(&mut self) {
        let path_str = self.path.to_string_lossy().to_string();
        if !cmd_run("git", &["worktree", "remove", "--force", &path_str]) {
            log(&format!(
                "WARNING: `git worktree remove` failed for {path_str}; falling back to fs cleanup"
            ));
            let _ = std::fs::remove_dir_all(&self.path);
            let _ = cmd_run("git", &["worktree", "prune"]);
        }
    }
}

/// Which unresolved threads to load for fix-comments (`run_pr_review_fix` vs
/// [`run_issue_pr_review_resume`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum PrReviewFixThreadScope {
    /// Bot / `[bot]` / `@caretta fix` marker (same filter as before #146-style tooling).
    #[default]
    ActionableBot,
    /// Every unresolved inline thread on the PR (for tracker `issue` pseudo-resume).
    AllInline,
}

fn review_threads_for_fix(pr_num: u32, scope: PrReviewFixThreadScope) -> Vec<ReviewThread> {
    match scope {
        PrReviewFixThreadScope::ActionableBot => {
            fetch_unresolved_review_threads(pr_num, DEFAULT_REVIEW_BOT_LOGIN)
        }
        PrReviewFixThreadScope::AllInline => fetch_all_unresolved_review_threads(pr_num),
    }
}

pub fn run_pr_review_fix(cfg: &Config, pr_num: u32) {
    run_pr_review_fix_scoped(cfg, pr_num, PrReviewFixThreadScope::ActionableBot, true);
}

/// Fix-comments path for [`crate::agent::issue::work_on_issue`] when an `agent/issue-*` PR
/// is already open: same worktree + verification flow as [`run_pr_review_fix`], but threads
/// are all unresolved inline comments (not restricted to the review bot). Never submits an
/// approving review — that remains for the bot `code-review` step.
pub(crate) fn run_issue_pr_review_resume(cfg: &Config, pr_num: u32) {
    run_pr_review_fix_scoped(cfg, pr_num, PrReviewFixThreadScope::AllInline, false);
}

fn run_pr_review_fix_scoped(
    cfg: &Config,
    pr_num: u32,
    scope: PrReviewFixThreadScope,
    try_approve_if_fully_resolved: bool,
) {
    preflight(cfg);
    log(&format!("Starting Fix Comments run for PR #{pr_num}..."));

    if cfg.dry_run {
        log(&format!(
            "[dry-run] Would run Fix Comments for PR #{pr_num}"
        ));
        emit_event(AgentEvent::Done);
        return;
    }

    let threads = review_threads_for_fix(pr_num, scope);
    if threads.is_empty() {
        let detail = match scope {
            PrReviewFixThreadScope::ActionableBot => {
                "No unresolved bot-authored review threads found"
            }
            PrReviewFixThreadScope::AllInline => "No unresolved inline review threads found",
        };
        log(&format!("{detail} for PR #{pr_num}."));
        emit_event(AgentEvent::Done);
        return;
    }

    let branch = pr_head_branch(pr_num);
    let title = list_open_prs()
        .into_iter()
        .find(|pr| pr.number == pr_num)
        .map(|pr| pr.title)
        .unwrap_or_else(|| format!("PR #{pr_num}"));
    let diff = pr_diff(pr_num);

    let worktree_path =
        std::env::temp_dir().join(format!("caretta-pr-{pr_num}-{}", std::process::id()));
    let worktree_str = worktree_path.to_string_lossy().to_string();
    let remote_ref = format!("origin/{branch}");

    let fetch_refspec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
    if !cmd_run("git", &["fetch", "origin", &fetch_refspec]) {
        log(&format!("Failed to fetch branch '{branch}' from origin."));
        emit_event(AgentEvent::Done);
        return;
    }

    if !cmd_run(
        "git",
        &[
            "worktree",
            "add",
            "--force",
            "-B",
            &branch,
            &worktree_str,
            &remote_ref,
        ],
    ) {
        log(&format!(
            "Failed to create worktree for PR #{pr_num} from {remote_ref}."
        ));
        emit_event(AgentEvent::Done);
        return;
    }

    let _guard = WorktreeGuard {
        path: worktree_path.clone(),
    };
    let prompt =
        build_pr_review_fix_prompt(&cfg.project_name, pr_num, &title, &branch, &diff, &threads);

    if !run_agent_with_env_in_dir(cfg, &prompt, &[], &worktree_path) {
        log(&format!("Fix Comments agent failed for PR #{pr_num}."));
        emit_event(AgentEvent::Done);
        return;
    }
    if stop_requested() {
        log("Stop requested. Fix Comments run cancelled.");
        emit_event(AgentEvent::Done);
        return;
    }

    let status =
        cmd_stdout("git", &["-C", &worktree_str, "status", "--porcelain"]).unwrap_or_default();
    if status.trim().is_empty() {
        log(&format!(
            "Fix Comments made no file changes for PR #{pr_num}; leaving review threads unresolved."
        ));
        emit_event(AgentEvent::Done);
        return;
    }

    let message = format!(
        "fix review comments on PR #{pr_num}\n\n{}",
        cfg.agent.co_author()
    );
    let committed = cmd_run("git", &["-C", &worktree_str, "add", "."])
        && cmd_run("git", &["-C", &worktree_str, "commit", "-m", &message]);
    if !committed {
        log(&format!(
            "Failed to commit Fix Comments changes for PR #{pr_num}."
        ));
        emit_event(AgentEvent::Done);
        return;
    }

    if !cmd_run("git", &["-C", &worktree_str, "push", "origin", &branch]) {
        log(&format!(
            "Failed to push Fix Comments changes for PR #{pr_num}."
        ));
        emit_event(AgentEvent::Done);
        return;
    }

    let verified_ids = run_verification_pass(cfg, pr_num, &threads, &worktree_path);
    let resolved = threads
        .iter()
        .filter(|thread| verified_ids.contains(&thread.id) && resolve_review_thread(&thread.id))
        .count();
    log(&format!(
        "Fix Comments complete for PR #{pr_num}: pushed changes and resolved {resolved}/{} thread(s).",
        threads.len()
    ));

    if resolved == threads.len() {
        if try_approve_if_fully_resolved {
            try_approve_pr(cfg, pr_num);
        } else {
            log(&format!(
                "PR #{pr_num}: all targeted threads resolved — leaving approval to the code-review flow (issue runner does not approve its own PR)."
            ));
        }
    } else {
        log(&format!(
            "Skipping auto-approve for PR #{pr_num}: {} thread(s) still unresolved.",
            threads.len() - resolved
        ));
    }
    emit_event(AgentEvent::Done);
}

/// Run the verification agent pass and return the set of thread IDs it
/// confirmed are addressed by the new code. On any failure (agent error,
/// missing/malformed verdict file, stop requested) returns an empty set so the
/// caller leaves all threads unresolved — better to require a human than to
/// rubber-stamp a wrong fix.
fn run_verification_pass(
    cfg: &Config,
    pr_num: u32,
    threads: &[crate::agent::tracker::ReviewThread],
    worktree_path: &Path,
) -> std::collections::HashSet<String> {
    use std::collections::HashSet;
    let empty = HashSet::new();

    let verdict_path = std::env::temp_dir().join(format!(
        "caretta-pr-{pr_num}-{}-verify.json",
        std::process::id()
    ));
    let _ = std::fs::remove_file(&verdict_path);
    let verdict_path_str = verdict_path.to_string_lossy().to_string();

    let post_fix_diff = pr_diff(pr_num);
    let prompt = build_pr_review_verification_prompt(
        &cfg.project_name,
        pr_num,
        &post_fix_diff,
        threads,
        &verdict_path_str,
    );

    log(&format!(
        "Running verification pass for PR #{pr_num} (verdict file: {verdict_path_str})."
    ));
    if !run_agent_with_env_in_dir(cfg, &prompt, &[], worktree_path) {
        log(&format!(
            "Verification agent failed for PR #{pr_num}; treating all threads as unverified."
        ));
        return empty;
    }
    if stop_requested() {
        log("Stop requested during verification pass; treating all threads as unverified.");
        return empty;
    }

    let json = match std::fs::read_to_string(&verdict_path) {
        Ok(s) => s,
        Err(err) => {
            log(&format!(
                "Verification verdict file missing for PR #{pr_num} ({err}); treating all threads as unverified."
            ));
            return empty;
        }
    };
    let _ = std::fs::remove_file(&verdict_path);

    let Some(verdict) = parse_verification_verdict(&json) else {
        log(&format!(
            "Verification verdict for PR #{pr_num} was not valid JSON; treating all threads as unverified."
        ));
        return empty;
    };

    if !verdict.unverified.is_empty() {
        for unv in &verdict.unverified {
            log(&format!(
                "Thread {id} unverified: {reason}",
                id = unv.id,
                reason = unv.reason
            ));
        }
    }
    verdict.verified.into_iter().collect()
}

/// Approve a PR if all bot-authored review threads are resolved and the
/// current `reviewDecision` is `CHANGES_REQUESTED`. Returns `true` when an
/// approval review was successfully submitted.
///
/// Uses the bot identity (`DEV_BOT_TOKEN` or App-minted token) so the approval
/// counts against `CHANGES_REQUESTED` left by the same bot. Without bot
/// credentials the call will fail (GitHub rejects self-approval).
pub fn try_approve_pr(cfg: &Config, pr_num: u32) -> bool {
    let unresolved = fetch_unresolved_review_threads(pr_num, DEFAULT_REVIEW_BOT_LOGIN);
    if !unresolved.is_empty() {
        log(&format!(
            "PR #{pr_num} still has {} unresolved bot-authored thread(s); not approving.",
            unresolved.len()
        ));
        return false;
    }

    let decision = pr_review_decision(pr_num).unwrap_or_default();
    if decision != "CHANGES_REQUESTED" {
        log(&format!(
            "PR #{pr_num} reviewDecision is {decision:?}; nothing to clear (no approval submitted)."
        ));
        return false;
    }

    let bot_token = cfg
        .effective_bot_credentials()
        .as_ref()
        .and_then(resolve_bot_token);
    let env: Vec<(String, String)> = bot_token
        .as_deref()
        .map(|t| vec![("GH_TOKEN".to_string(), t.to_string())])
        .unwrap_or_default();
    if env.is_empty() {
        log(
            "WARNING: No bot credentials configured; approval will run under your identity \
             and GitHub rejects self-approval. Set DEV_BOT_TOKEN or configure a GitHub App.",
        );
    }

    let pr_num_s = pr_num.to_string();
    let body =
        "All requested changes have been addressed. Approving via caretta code-review follow-up.";
    let ok = cmd_run_env(
        "gh",
        &["pr", "review", &pr_num_s, "--approve", "--body", body],
        &env,
    );
    if ok {
        log(&format!("Approved PR #{pr_num}."));
    } else {
        log(&format!(
            "WARNING: failed to submit approve review on PR #{pr_num}."
        ));
    }
    ok
}