1use std::{fmt::Write as _, path::PathBuf, sync::Arc};
2
3use anyhow::{Context, Result};
4use rusqlite::Connection;
5use tokio::sync::Mutex;
6use tokio_util::sync::CancellationToken;
7use tracing::{debug, info, warn};
8
9use crate::{
10 agents::{
11 self, AgentContext, AgentInvocation, AgentRole, Complexity, GraphContextNode,
12 PlannerGraphOutput, Severity, invoke_agent, parse_fixer_output, parse_planner_graph_output,
13 parse_review_output,
14 },
15 config::Config,
16 db::{self, AgentRun, ReviewFinding, Run, RunStatus},
17 git::{self, RebaseOutcome},
18 github::{self, GhClient},
19 issues::{IssueOrigin, IssueProvider, PipelineIssue},
20 process::{self, CommandRunner},
21};
22
23#[derive(Debug)]
25pub struct PipelineOutcome {
26 pub run_id: String,
27 pub pr_number: u32,
28 pub worktree_path: PathBuf,
30 pub target_dir: PathBuf,
32}
33
34pub struct PipelineExecutor<R: CommandRunner> {
36 pub runner: Arc<R>,
37 pub github: Arc<GhClient<R>>,
38 pub issues: Arc<dyn IssueProvider>,
39 pub db: Arc<Mutex<Connection>>,
40 pub config: Config,
41 pub cancel_token: CancellationToken,
42 pub repo_dir: PathBuf,
43}
44
45impl<R: CommandRunner + 'static> PipelineExecutor<R> {
46 pub async fn run_issue(&self, issue: &PipelineIssue, auto_merge: bool) -> Result<()> {
48 self.run_issue_with_complexity(issue, auto_merge, None).await
49 }
50
51 pub async fn run_issue_with_complexity(
53 &self,
54 issue: &PipelineIssue,
55 auto_merge: bool,
56 complexity: Option<Complexity>,
57 ) -> Result<()> {
58 let outcome = self.run_issue_pipeline(issue, auto_merge, complexity).await?;
59 self.finalize_merge(&outcome, issue).await
60 }
61
62 pub async fn run_issue_pipeline(
68 &self,
69 issue: &PipelineIssue,
70 auto_merge: bool,
71 complexity: Option<Complexity>,
72 ) -> Result<PipelineOutcome> {
73 let run_id = generate_run_id();
74
75 let (target_dir, is_multi_repo) = self.resolve_target_dir(issue.target_repo.as_ref())?;
77
78 let base_branch = git::default_branch(&target_dir).await?;
79
80 let mut run = new_run(&run_id, issue, auto_merge);
81 if let Some(ref c) = complexity {
82 run.complexity = c.to_string();
83 }
84 {
85 let conn = self.db.lock().await;
86 db::runs::insert_run(&conn, &run)?;
87 }
88
89 self.issues
90 .transition(issue.number, &self.config.labels.ready, &self.config.labels.cooking)
91 .await?;
92
93 let worktree = git::create_worktree(&target_dir, issue.number, &base_branch).await?;
94 self.record_worktree(&run_id, &worktree).await?;
95
96 git::empty_commit(
98 &worktree.path,
99 &format!("chore: start oven pipeline for issue #{}", issue.number),
100 )
101 .await?;
102
103 info!(
104 run_id = %run_id,
105 issue = issue.number,
106 branch = %worktree.branch,
107 target_repo = ?issue.target_repo,
108 "starting pipeline"
109 );
110
111 let pr_number = self.create_pr(&run_id, issue, &worktree.branch, &target_dir).await?;
112
113 let ctx = AgentContext {
114 issue_number: issue.number,
115 issue_title: issue.title.clone(),
116 issue_body: issue.body.clone(),
117 branch: worktree.branch.clone(),
118 pr_number: Some(pr_number),
119 test_command: self.config.project.test.clone(),
120 lint_command: self.config.project.lint.clone(),
121 review_findings: None,
122 cycle: 1,
123 target_repo: if is_multi_repo { issue.target_repo.clone() } else { None },
124 issue_source: issue.source.as_str().to_string(),
125 base_branch: base_branch.clone(),
126 };
127
128 let result = self.run_steps(&run_id, &ctx, &worktree.path, auto_merge, &target_dir).await;
129
130 if let Err(ref e) = result {
131 self.finalize_run(&run_id, issue, pr_number, &result, &target_dir).await?;
135 return Err(anyhow::anyhow!("{e:#}"));
136 }
137
138 self.update_status(&run_id, RunStatus::AwaitingMerge).await?;
140
141 Ok(PipelineOutcome { run_id, pr_number, worktree_path: worktree.path, target_dir })
142 }
143
144 pub async fn finalize_merge(
149 &self,
150 outcome: &PipelineOutcome,
151 issue: &PipelineIssue,
152 ) -> Result<()> {
153 self.finalize_run(&outcome.run_id, issue, outcome.pr_number, &Ok(()), &outcome.target_dir)
154 .await?;
155 if let Err(e) = git::remove_worktree(&outcome.target_dir, &outcome.worktree_path).await {
156 warn!(
157 run_id = %outcome.run_id,
158 error = %e,
159 "failed to clean up worktree after merge"
160 );
161 }
162 Ok(())
163 }
164
165 pub async fn plan_issues(
172 &self,
173 issues: &[PipelineIssue],
174 graph_context: &[GraphContextNode],
175 ) -> Option<PlannerGraphOutput> {
176 let prompt = match agents::planner::build_prompt(issues, graph_context) {
177 Ok(p) => p,
178 Err(e) => {
179 warn!(error = %e, "planner prompt build failed");
180 return None;
181 }
182 };
183 let invocation = AgentInvocation {
184 role: AgentRole::Planner,
185 prompt,
186 working_dir: self.repo_dir.clone(),
187 max_turns: Some(self.config.pipeline.turn_limit),
188 model: self.config.models.model_for(AgentRole::Planner.as_str()).map(String::from),
189 };
190
191 match invoke_agent(self.runner.as_ref(), &invocation).await {
192 Ok(result) => {
193 debug!(output = %result.output, "raw planner output");
194 let parsed = parse_planner_graph_output(&result.output);
195 if parsed.is_none() {
196 warn!(output = %result.output, "planner returned unparseable output, falling back to all-parallel");
197 }
198 parsed
199 }
200 Err(e) => {
201 warn!(error = %e, "planner agent failed, falling back to all-parallel");
202 None
203 }
204 }
205 }
206
207 pub(crate) fn resolve_target_dir(
212 &self,
213 target_repo: Option<&String>,
214 ) -> Result<(PathBuf, bool)> {
215 if !self.config.multi_repo.enabled {
216 return Ok((self.repo_dir.clone(), false));
217 }
218 match target_repo {
219 Some(name) => {
220 let path = self.config.resolve_repo(name)?;
221 Ok((path, true))
222 }
223 None => Ok((self.repo_dir.clone(), false)),
224 }
225 }
226
227 pub fn reconstruct_outcome(
232 &self,
233 issue: &PipelineIssue,
234 run_id: &str,
235 pr_number: u32,
236 ) -> Result<PipelineOutcome> {
237 let (target_dir, _) = self.resolve_target_dir(issue.target_repo.as_ref())?;
238 let worktree_path =
239 target_dir.join(".oven").join("worktrees").join(format!("issue-{}", issue.number));
240 Ok(PipelineOutcome { run_id: run_id.to_string(), pr_number, worktree_path, target_dir })
241 }
242
243 async fn record_worktree(&self, run_id: &str, worktree: &git::Worktree) -> Result<()> {
244 let conn = self.db.lock().await;
245 db::runs::update_run_worktree(
246 &conn,
247 run_id,
248 &worktree.branch,
249 &worktree.path.to_string_lossy(),
250 )?;
251 drop(conn);
252 Ok(())
253 }
254
255 async fn create_pr(
256 &self,
257 run_id: &str,
258 issue: &PipelineIssue,
259 branch: &str,
260 repo_dir: &std::path::Path,
261 ) -> Result<u32> {
262 let (pr_title, pr_body) = match issue.source {
263 IssueOrigin::Github => (
264 format!("fix(#{}): {}", issue.number, issue.title),
265 format!(
266 "Resolves #{}\n\nAutomated by [oven](https://github.com/clayharmon/oven-cli).",
267 issue.number
268 ),
269 ),
270 IssueOrigin::Local => (
271 format!("fix: {}", issue.title),
272 format!(
273 "From local issue #{}\n\nAutomated by [oven](https://github.com/clayharmon/oven-cli).",
274 issue.number
275 ),
276 ),
277 };
278
279 git::push_branch(repo_dir, branch).await?;
280 let pr_number =
281 self.github.create_draft_pr_in(&pr_title, branch, &pr_body, repo_dir).await?;
282
283 {
284 let conn = self.db.lock().await;
285 db::runs::update_run_pr(&conn, run_id, pr_number)?;
286 }
287
288 info!(run_id = %run_id, pr = pr_number, "draft PR created");
289 Ok(pr_number)
290 }
291
292 async fn finalize_run(
293 &self,
294 run_id: &str,
295 issue: &PipelineIssue,
296 pr_number: u32,
297 result: &Result<()>,
298 target_dir: &std::path::Path,
299 ) -> Result<()> {
300 let (final_status, error_msg) = match result {
301 Ok(()) => {
302 self.issues
303 .transition(
304 issue.number,
305 &self.config.labels.cooking,
306 &self.config.labels.complete,
307 )
308 .await?;
309
310 let should_close =
314 issue.source == IssueOrigin::Local || issue.target_repo.is_some();
315
316 if should_close {
317 let comment = issue.target_repo.as_ref().map_or_else(
318 || format!("Implemented in #{pr_number}"),
319 |repo_name| format!("Implemented in {repo_name}#{pr_number}"),
320 );
321 if let Err(e) = self.issues.close(issue.number, Some(&comment)).await {
322 warn!(
323 run_id = %run_id,
324 error = %e,
325 "failed to close issue"
326 );
327 }
328 }
329
330 (RunStatus::Complete, None)
331 }
332 Err(e) => {
333 warn!(run_id = %run_id, error = %e, "pipeline failed");
334 github::safe_comment(
335 &self.github,
336 pr_number,
337 &format_pipeline_failure(e),
338 target_dir,
339 )
340 .await;
341 let _ = self
342 .issues
343 .transition(
344 issue.number,
345 &self.config.labels.cooking,
346 &self.config.labels.failed,
347 )
348 .await;
349 (RunStatus::Failed, Some(format!("{e:#}")))
350 }
351 };
352
353 let conn = self.db.lock().await;
354 db::runs::finish_run(&conn, run_id, final_status, error_msg.as_deref())
355 }
356
357 async fn run_steps(
358 &self,
359 run_id: &str,
360 ctx: &AgentContext,
361 worktree_path: &std::path::Path,
362 auto_merge: bool,
363 target_dir: &std::path::Path,
364 ) -> Result<()> {
365 self.check_cancelled()?;
366
367 self.update_status(run_id, RunStatus::Implementing).await?;
369 let impl_prompt = agents::implementer::build_prompt(ctx)?;
370 let impl_result =
371 self.run_agent(run_id, AgentRole::Implementer, &impl_prompt, worktree_path, 1).await?;
372
373 git::push_branch(worktree_path, &ctx.branch).await?;
374
375 if let Some(pr_number) = ctx.pr_number {
377 let body = build_pr_body(&impl_result.output, ctx);
378 if let Err(e) =
379 self.github.edit_pr_in(pr_number, &pr_title(ctx), &body, target_dir).await
380 {
381 warn!(run_id = %run_id, error = %e, "failed to update PR description");
382 }
383 if let Err(e) = self.github.mark_pr_ready_in(pr_number, target_dir).await {
384 warn!(run_id = %run_id, error = %e, "failed to mark PR ready");
385 }
386 }
387
388 if let Some(pr_number) = ctx.pr_number {
390 let summary = extract_impl_summary(&impl_result.output);
391 github::safe_comment(
392 &self.github,
393 pr_number,
394 &format_impl_comment(&summary),
395 target_dir,
396 )
397 .await;
398 }
399
400 self.run_review_fix_loop(run_id, ctx, worktree_path, target_dir).await?;
402
403 self.check_cancelled()?;
405 info!(run_id = %run_id, base = %ctx.base_branch, "rebasing onto base branch");
406 let rebase_outcome =
407 self.rebase_with_agent_fallback(run_id, ctx, worktree_path, target_dir).await?;
408
409 if let Some(pr_number) = ctx.pr_number {
410 github::safe_comment(
411 &self.github,
412 pr_number,
413 &format_rebase_comment(&rebase_outcome),
414 target_dir,
415 )
416 .await;
417 }
418
419 if let RebaseOutcome::Failed(ref msg) = rebase_outcome {
420 anyhow::bail!("rebase failed: {msg}");
421 }
422
423 git::force_push_branch(worktree_path, &ctx.branch).await?;
424
425 if auto_merge {
427 self.check_cancelled()?;
428 let pr_number = ctx.pr_number.context("no PR number for merge step")?;
429 self.update_status(run_id, RunStatus::Merging).await?;
430
431 self.github.merge_pr_in(pr_number, target_dir).await?;
432 info!(run_id = %run_id, pr = pr_number, "PR merged");
433
434 if ctx.target_repo.is_none() && ctx.issue_source == "github" {
437 if let Err(e) = self
438 .github
439 .close_issue(ctx.issue_number, Some(&format!("Implemented in #{pr_number}")))
440 .await
441 {
442 warn!(run_id = %run_id, error = %e, "failed to close issue after merge");
443 }
444 }
445
446 github::safe_comment(&self.github, pr_number, &format_merge_comment(), target_dir)
447 .await;
448 } else if let Some(pr_number) = ctx.pr_number {
449 github::safe_comment(&self.github, pr_number, &format_ready_comment(), target_dir)
450 .await;
451 }
452
453 Ok(())
454 }
455
456 async fn run_review_fix_loop(
457 &self,
458 run_id: &str,
459 ctx: &AgentContext,
460 worktree_path: &std::path::Path,
461 target_dir: &std::path::Path,
462 ) -> Result<()> {
463 let mut pre_fix_ref: Option<String> = None;
464
465 for cycle in 1..=3 {
466 self.check_cancelled()?;
467
468 self.update_status(run_id, RunStatus::Reviewing).await?;
469
470 let (prior_addressed, prior_disputes, prior_unresolved) =
471 self.gather_prior_findings(run_id, cycle).await?;
472
473 let review_prompt = agents::reviewer::build_prompt(
474 ctx,
475 &prior_addressed,
476 &prior_disputes,
477 &prior_unresolved,
478 pre_fix_ref.as_deref(),
479 )?;
480
481 let review_result = match self
483 .run_agent(run_id, AgentRole::Reviewer, &review_prompt, worktree_path, cycle)
484 .await
485 {
486 Ok(result) => result,
487 Err(e) => {
488 warn!(run_id = %run_id, cycle, error = %e, "reviewer agent failed, skipping review");
489 if let Some(pr_number) = ctx.pr_number {
490 github::safe_comment(
491 &self.github,
492 pr_number,
493 &format_review_skipped_comment(cycle, &e),
494 target_dir,
495 )
496 .await;
497 }
498 return Ok(());
499 }
500 };
501
502 let review_output = parse_review_output(&review_result.output);
503 self.store_findings(run_id, &review_output.findings).await?;
504
505 let actionable: Vec<_> =
506 review_output.findings.iter().filter(|f| f.severity != Severity::Info).collect();
507
508 if let Some(pr_number) = ctx.pr_number {
510 github::safe_comment(
511 &self.github,
512 pr_number,
513 &format_review_comment(cycle, &actionable),
514 target_dir,
515 )
516 .await;
517 }
518
519 if actionable.is_empty() {
520 info!(run_id = %run_id, cycle, "review clean");
521 return Ok(());
522 }
523
524 info!(run_id = %run_id, cycle, findings = actionable.len(), "review found issues");
525
526 if cycle == 3 {
527 if let Some(pr_number) = ctx.pr_number {
528 let comment = format_unresolved_comment(&actionable);
529 github::safe_comment(&self.github, pr_number, &comment, target_dir).await;
530 } else {
531 warn!(run_id = %run_id, "no PR number, cannot post unresolved findings");
532 }
533 return Ok(());
534 }
535
536 pre_fix_ref = Some(git::head_sha(worktree_path).await?);
538
539 self.run_fix_step(run_id, ctx, worktree_path, target_dir, cycle).await?;
540 }
541
542 Ok(())
543 }
544
545 async fn gather_prior_findings(
547 &self,
548 run_id: &str,
549 cycle: u32,
550 ) -> Result<(Vec<ReviewFinding>, Vec<ReviewFinding>, Vec<ReviewFinding>)> {
551 if cycle <= 1 {
552 return Ok((Vec::new(), Vec::new(), Vec::new()));
553 }
554
555 let conn = self.db.lock().await;
556 let all_resolved = db::agent_runs::get_resolved_findings(&conn, run_id)?;
557 let all_unresolved = db::agent_runs::get_unresolved_findings(&conn, run_id)?;
558 drop(conn);
559
560 let (mut addressed, disputed): (Vec<_>, Vec<_>) = all_resolved.into_iter().partition(|f| {
561 f.dispute_reason.as_deref().is_some_and(|r| r.starts_with("ADDRESSED: "))
562 });
563
564 for f in &mut addressed {
566 if let Some(ref mut reason) = f.dispute_reason {
567 if let Some(stripped) = reason.strip_prefix("ADDRESSED: ") {
568 *reason = stripped.to_string();
569 }
570 }
571 }
572
573 Ok((addressed, disputed, all_unresolved))
574 }
575
576 async fn run_fix_step(
586 &self,
587 run_id: &str,
588 ctx: &AgentContext,
589 worktree_path: &std::path::Path,
590 target_dir: &std::path::Path,
591 cycle: u32,
592 ) -> Result<()> {
593 self.check_cancelled()?;
594 self.update_status(run_id, RunStatus::Fixing).await?;
595
596 let actionable = self.filter_actionable_findings(run_id).await?;
597
598 if actionable.is_empty() {
599 info!(run_id = %run_id, cycle, "no actionable findings for fixer, skipping");
600 if let Some(pr_number) = ctx.pr_number {
601 github::safe_comment(
602 &self.github,
603 pr_number,
604 &format!(
605 "### Fix skipped (cycle {cycle})\n\n\
606 No actionable findings (all findings lacked file paths).\
607 {COMMENT_FOOTER}"
608 ),
609 target_dir,
610 )
611 .await;
612 }
613 return Ok(());
614 }
615
616 let pre_fix_head = git::head_sha(worktree_path).await?;
618
619 let fix_prompt = agents::fixer::build_prompt(ctx, &actionable)?;
620
621 let fix_result =
623 match self.run_agent(run_id, AgentRole::Fixer, &fix_prompt, worktree_path, cycle).await
624 {
625 Ok(result) => result,
626 Err(e) => {
627 warn!(run_id = %run_id, cycle, error = %e, "fixer agent failed, skipping fix");
628 if let Some(pr_number) = ctx.pr_number {
629 github::safe_comment(
630 &self.github,
631 pr_number,
632 &format_fix_skipped_comment(cycle, &e),
633 target_dir,
634 )
635 .await;
636 }
637 return Ok(());
638 }
639 };
640
641 let fixer_output = parse_fixer_output(&fix_result.output);
643 let fixer_did_nothing =
644 fixer_output.addressed.is_empty() && fixer_output.disputed.is_empty();
645
646 let new_commits = if fixer_did_nothing {
647 git::commit_count_since(worktree_path, &pre_fix_head).await.unwrap_or(0)
648 } else {
649 0
650 };
651
652 if fixer_did_nothing {
653 if new_commits > 0 {
654 warn!(
657 run_id = %run_id, cycle, commits = new_commits,
658 "fixer output unparseable but commits exist, inferring addressed from git"
659 );
660 self.infer_addressed_from_git(run_id, &actionable, worktree_path, &pre_fix_head)
661 .await?;
662 } else {
663 warn!(
665 run_id = %run_id, cycle,
666 "fixer produced no output and no commits, marking findings not actionable"
667 );
668 let conn = self.db.lock().await;
669 for f in &actionable {
670 db::agent_runs::resolve_finding(
671 &conn,
672 f.id,
673 "ADDRESSED: fixer could not act on this finding (no commits, no output)",
674 )?;
675 }
676 drop(conn);
677 }
678 } else {
679 self.process_fixer_results(run_id, &actionable, &fixer_output).await?;
680 }
681
682 if let Some(pr_number) = ctx.pr_number {
684 let comment = if fixer_did_nothing {
685 format_fixer_recovery_comment(cycle, new_commits)
686 } else {
687 format_fix_comment(cycle, &fixer_output)
688 };
689 github::safe_comment(&self.github, pr_number, &comment, target_dir).await;
690 }
691
692 git::push_branch(worktree_path, &ctx.branch).await?;
693 Ok(())
694 }
695
696 async fn process_fixer_results(
704 &self,
705 run_id: &str,
706 findings_sent_to_fixer: &[ReviewFinding],
707 fixer_output: &agents::FixerOutput,
708 ) -> Result<()> {
709 if fixer_output.disputed.is_empty() && fixer_output.addressed.is_empty() {
710 return Ok(());
711 }
712
713 let conn = self.db.lock().await;
714
715 for dispute in &fixer_output.disputed {
716 let idx = dispute.finding.saturating_sub(1) as usize;
717 if let Some(finding) = findings_sent_to_fixer.get(idx) {
718 db::agent_runs::resolve_finding(&conn, finding.id, &dispute.reason)?;
719 info!(
720 run_id = %run_id,
721 finding_id = finding.id,
722 reason = %dispute.reason,
723 "finding disputed by fixer, marked resolved"
724 );
725 }
726 }
727
728 for action in &fixer_output.addressed {
729 let idx = action.finding.saturating_sub(1) as usize;
730 if let Some(finding) = findings_sent_to_fixer.get(idx) {
731 let reason = format!("ADDRESSED: {}", action.action);
732 db::agent_runs::resolve_finding(&conn, finding.id, &reason)?;
733 info!(
734 run_id = %run_id,
735 finding_id = finding.id,
736 action = %action.action,
737 "finding addressed by fixer, marked resolved"
738 );
739 }
740 }
741
742 drop(conn);
743 Ok(())
744 }
745
746 async fn filter_actionable_findings(&self, run_id: &str) -> Result<Vec<ReviewFinding>> {
751 let conn = self.db.lock().await;
752 let unresolved = db::agent_runs::get_unresolved_findings(&conn, run_id)?;
753
754 let (actionable, non_actionable): (Vec<_>, Vec<_>) =
755 unresolved.into_iter().partition(|f| f.file_path.is_some());
756
757 if !non_actionable.is_empty() {
758 warn!(
759 run_id = %run_id,
760 count = non_actionable.len(),
761 "auto-resolving non-actionable findings (no file_path)"
762 );
763 for f in &non_actionable {
764 db::agent_runs::resolve_finding(
765 &conn,
766 f.id,
767 "ADDRESSED: auto-resolved -- finding has no file path, not actionable by fixer",
768 )?;
769 }
770 }
771
772 drop(conn);
773 Ok(actionable)
774 }
775
776 async fn infer_addressed_from_git(
781 &self,
782 run_id: &str,
783 findings: &[ReviewFinding],
784 worktree_path: &std::path::Path,
785 pre_fix_head: &str,
786 ) -> Result<()> {
787 let changed_files =
788 git::changed_files_since(worktree_path, pre_fix_head).await.unwrap_or_default();
789
790 let conn = self.db.lock().await;
791 for f in findings {
792 let was_touched =
793 f.file_path.as_ref().is_some_and(|fp| changed_files.iter().any(|cf| cf == fp));
794
795 let reason = if was_touched {
796 "ADDRESSED: inferred from git -- fixer modified this file (no structured output)"
797 } else {
798 "ADDRESSED: inferred from git -- file not modified (no structured output)"
799 };
800
801 db::agent_runs::resolve_finding(&conn, f.id, reason)?;
802 info!(
803 run_id = %run_id,
804 finding_id = f.id,
805 file = ?f.file_path,
806 touched = was_touched,
807 "finding resolved via git inference"
808 );
809 }
810 drop(conn);
811 Ok(())
812 }
813
814 async fn store_findings(&self, run_id: &str, findings: &[agents::Finding]) -> Result<()> {
815 let conn = self.db.lock().await;
816 let agent_runs = db::agent_runs::get_agent_runs_for_run(&conn, run_id)?;
817 let reviewer_run_id = agent_runs
818 .iter()
819 .rev()
820 .find_map(|ar| if ar.agent == "reviewer" { Some(ar.id) } else { None });
821 if let Some(ar_id) = reviewer_run_id {
822 for finding in findings {
823 let db_finding = ReviewFinding {
824 id: 0,
825 agent_run_id: ar_id,
826 severity: finding.severity.to_string(),
827 category: finding.category.clone(),
828 file_path: finding.file_path.clone(),
829 line_number: finding.line_number,
830 message: finding.message.clone(),
831 resolved: false,
832 dispute_reason: None,
833 };
834 db::agent_runs::insert_finding(&conn, &db_finding)?;
835 }
836 }
837 drop(conn);
838 Ok(())
839 }
840
841 async fn rebase_with_agent_fallback(
845 &self,
846 run_id: &str,
847 ctx: &AgentContext,
848 worktree_path: &std::path::Path,
849 target_dir: &std::path::Path,
850 ) -> Result<RebaseOutcome> {
851 const MAX_REBASE_ROUNDS: u32 = 5;
852
853 let outcome = git::start_rebase(worktree_path, &ctx.base_branch).await;
854
855 let mut conflicting_files = match outcome {
856 RebaseOutcome::RebaseConflicts(files) => files,
857 other => return Ok(other),
858 };
859
860 for round in 1..=MAX_REBASE_ROUNDS {
861 self.check_cancelled()?;
862 info!(
863 run_id = %run_id,
864 round,
865 files = ?conflicting_files,
866 "rebase conflicts, attempting agent resolution"
867 );
868
869 if let Some(pr_number) = ctx.pr_number {
870 github::safe_comment(
871 &self.github,
872 pr_number,
873 &format_rebase_conflict_comment(round, &conflicting_files),
874 target_dir,
875 )
876 .await;
877 }
878
879 let conflict_prompt = format!(
880 "You are resolving rebase conflicts. The following files have unresolved \
881 conflict markers (<<<<<<< / ======= / >>>>>>> markers):\n\n{}\n\n\
882 Open each file, find the conflict markers, and resolve them by choosing \
883 the correct code. Remove all conflict markers. Do NOT add new features \
884 or refactor -- just resolve the conflicts so the code compiles and tests pass.\n\n\
885 After resolving, run any test/lint commands if available:\n\
886 - Test: {}\n\
887 - Lint: {}",
888 conflicting_files.iter().map(|f| format!("- {f}")).collect::<Vec<_>>().join("\n"),
889 ctx.test_command.as_deref().unwrap_or("(none)"),
890 ctx.lint_command.as_deref().unwrap_or("(none)"),
891 );
892
893 if let Err(e) = self
894 .run_agent(run_id, AgentRole::Implementer, &conflict_prompt, worktree_path, 1)
895 .await
896 {
897 warn!(run_id = %run_id, error = %e, "conflict resolution agent failed");
898 git::abort_rebase(worktree_path).await;
899 return Ok(RebaseOutcome::Failed(format!(
900 "agent conflict resolution failed: {e:#}"
901 )));
902 }
903
904 let remaining = git::conflicting_files(worktree_path).await;
906 if !remaining.is_empty() {
907 warn!(
908 run_id = %run_id,
909 remaining = ?remaining,
910 "agent did not resolve all conflicts"
911 );
912 git::abort_rebase(worktree_path).await;
913 return Ok(RebaseOutcome::Failed(format!(
914 "agent could not resolve conflicts in: {}",
915 remaining.join(", ")
916 )));
917 }
918
919 match git::rebase_continue(worktree_path, &conflicting_files).await {
921 Ok(None) => {
922 info!(run_id = %run_id, "agent resolved rebase conflicts");
923 return Ok(RebaseOutcome::AgentResolved);
924 }
925 Ok(Some(new_conflicts)) => {
926 conflicting_files = new_conflicts;
928 }
929 Err(e) => {
930 git::abort_rebase(worktree_path).await;
931 return Ok(RebaseOutcome::Failed(format!("rebase --continue failed: {e:#}")));
932 }
933 }
934 }
935
936 git::abort_rebase(worktree_path).await;
938 Ok(RebaseOutcome::Failed(format!(
939 "rebase conflicts persisted after {MAX_REBASE_ROUNDS} resolution rounds"
940 )))
941 }
942
943 async fn run_agent(
944 &self,
945 run_id: &str,
946 role: AgentRole,
947 prompt: &str,
948 working_dir: &std::path::Path,
949 cycle: u32,
950 ) -> Result<crate::process::AgentResult> {
951 let agent_run_id = self.record_agent_start(run_id, role, cycle).await?;
952
953 info!(run_id = %run_id, agent = %role, cycle, "agent starting");
954
955 let invocation = AgentInvocation {
956 role,
957 prompt: prompt.to_string(),
958 working_dir: working_dir.to_path_buf(),
959 max_turns: Some(self.config.pipeline.turn_limit),
960 model: self.config.models.model_for(role.as_str()).map(String::from),
961 };
962
963 let result = process::run_with_retry(self.runner.as_ref(), &invocation).await;
964
965 match &result {
966 Ok(agent_result) => {
967 self.record_agent_success(run_id, agent_run_id, agent_result).await?;
968 }
969 Err(e) => {
970 let conn = self.db.lock().await;
971 db::agent_runs::finish_agent_run(
972 &conn,
973 agent_run_id,
974 "failed",
975 0.0,
976 0,
977 None,
978 Some(&format!("{e:#}")),
979 None,
980 )?;
981 }
982 }
983
984 result
985 }
986
987 async fn record_agent_start(&self, run_id: &str, role: AgentRole, cycle: u32) -> Result<i64> {
988 let agent_run = AgentRun {
989 id: 0,
990 run_id: run_id.to_string(),
991 agent: role.to_string(),
992 cycle,
993 status: "running".to_string(),
994 cost_usd: 0.0,
995 turns: 0,
996 started_at: chrono::Utc::now().to_rfc3339(),
997 finished_at: None,
998 output_summary: None,
999 error_message: None,
1000 raw_output: None,
1001 };
1002 let conn = self.db.lock().await;
1003 db::agent_runs::insert_agent_run(&conn, &agent_run)
1004 }
1005
1006 async fn record_agent_success(
1007 &self,
1008 run_id: &str,
1009 agent_run_id: i64,
1010 agent_result: &crate::process::AgentResult,
1011 ) -> Result<()> {
1012 let conn = self.db.lock().await;
1013 db::agent_runs::finish_agent_run(
1014 &conn,
1015 agent_run_id,
1016 "complete",
1017 agent_result.cost_usd,
1018 agent_result.turns,
1019 Some(&truncate(&agent_result.output, 500)),
1020 None,
1021 Some(&agent_result.output),
1022 )?;
1023
1024 let new_cost = db::runs::increment_run_cost(&conn, run_id, agent_result.cost_usd)?;
1025 drop(conn);
1026
1027 if new_cost > self.config.pipeline.cost_budget {
1028 anyhow::bail!(
1029 "cost budget exceeded: ${:.2} > ${:.2}",
1030 new_cost,
1031 self.config.pipeline.cost_budget
1032 );
1033 }
1034 Ok(())
1035 }
1036
1037 async fn update_status(&self, run_id: &str, status: RunStatus) -> Result<()> {
1038 let conn = self.db.lock().await;
1039 db::runs::update_run_status(&conn, run_id, status)
1040 }
1041
1042 fn check_cancelled(&self) -> Result<()> {
1043 if self.cancel_token.is_cancelled() {
1044 anyhow::bail!("pipeline cancelled");
1045 }
1046 Ok(())
1047 }
1048}
1049
1050const COMMENT_FOOTER: &str =
1051 "\n---\nAutomated by [oven](https://github.com/clayharmon/oven-cli) \u{1F35E}";
1052
1053fn format_unresolved_comment(actionable: &[&agents::Finding]) -> String {
1054 let mut comment = String::from(
1055 "### Unresolved review findings\n\n\
1056 The review-fix loop ran 2 cycles but these findings remain unresolved.\n",
1057 );
1058
1059 for severity in &[Severity::Critical, Severity::Warning] {
1061 let group: Vec<_> = actionable.iter().filter(|f| &f.severity == severity).collect();
1062 if group.is_empty() {
1063 continue;
1064 }
1065 let heading = match severity {
1066 Severity::Critical => "Critical",
1067 Severity::Warning => "Warning",
1068 Severity::Info => unreachable!("loop only iterates Critical and Warning"),
1069 };
1070 let _ = writeln!(comment, "\n#### {heading}\n");
1071 for f in group {
1072 let loc = match (&f.file_path, f.line_number) {
1073 (Some(path), Some(line)) => format!(" in `{path}:{line}`"),
1074 (Some(path), None) => format!(" in `{path}`"),
1075 _ => String::new(),
1076 };
1077 let _ = writeln!(comment, "- **{}**{} -- {}", f.category, loc, f.message);
1078 }
1079 }
1080
1081 comment.push_str(COMMENT_FOOTER);
1082 comment
1083}
1084
1085fn format_impl_comment(summary: &str) -> String {
1086 format!("### Implementation complete\n\n{summary}{COMMENT_FOOTER}")
1087}
1088
1089fn format_review_comment(cycle: u32, actionable: &[&agents::Finding]) -> String {
1090 if actionable.is_empty() {
1091 return format!(
1092 "### Review complete (cycle {cycle})\n\n\
1093 Clean review, no actionable findings.{COMMENT_FOOTER}"
1094 );
1095 }
1096
1097 let mut comment = format!(
1098 "### Review complete (cycle {cycle})\n\n\
1099 **{count} finding{s}:**\n",
1100 count = actionable.len(),
1101 s = if actionable.len() == 1 { "" } else { "s" },
1102 );
1103
1104 for f in actionable {
1105 let loc = match (&f.file_path, f.line_number) {
1106 (Some(path), Some(line)) => format!(" in `{path}:{line}`"),
1107 (Some(path), None) => format!(" in `{path}`"),
1108 _ => String::new(),
1109 };
1110 let _ = writeln!(
1111 comment,
1112 "- [{sev}] **{cat}**{loc} -- {msg}",
1113 sev = f.severity,
1114 cat = f.category,
1115 msg = f.message,
1116 );
1117 }
1118
1119 comment.push_str(COMMENT_FOOTER);
1120 comment
1121}
1122
1123fn format_fix_comment(cycle: u32, fixer: &agents::FixerOutput) -> String {
1124 let addressed = fixer.addressed.len();
1125 let disputed = fixer.disputed.len();
1126 format!(
1127 "### Fix complete (cycle {cycle})\n\n\
1128 **Addressed:** {addressed} finding{a_s}\n\
1129 **Disputed:** {disputed} finding{d_s}{COMMENT_FOOTER}",
1130 a_s = if addressed == 1 { "" } else { "s" },
1131 d_s = if disputed == 1 { "" } else { "s" },
1132 )
1133}
1134
1135fn format_rebase_conflict_comment(round: u32, conflicting_files: &[String]) -> String {
1136 format!(
1137 "### Resolving rebase conflicts (round {round})\n\n\
1138 Attempting agent-assisted resolution for {} conflicting file{}: \
1139 {}{COMMENT_FOOTER}",
1140 conflicting_files.len(),
1141 if conflicting_files.len() == 1 { "" } else { "s" },
1142 conflicting_files.iter().map(|f| format!("`{f}`")).collect::<Vec<_>>().join(", "),
1143 )
1144}
1145
1146fn format_fixer_recovery_comment(cycle: u32, new_commits: u32) -> String {
1147 if new_commits > 0 {
1148 format!(
1149 "### Fix complete (cycle {cycle})\n\n\
1150 Fixer made {new_commits} commit{s} but did not produce structured output. \
1151 Addressed findings inferred from changed files.{COMMENT_FOOTER}",
1152 s = if new_commits == 1 { "" } else { "s" },
1153 )
1154 } else {
1155 format!(
1156 "### Fix complete (cycle {cycle})\n\n\
1157 Fixer could not act on the findings (no code changes made). \
1158 Findings marked as not actionable.{COMMENT_FOOTER}"
1159 )
1160 }
1161}
1162
1163fn format_review_skipped_comment(cycle: u32, error: &anyhow::Error) -> String {
1164 format!(
1165 "### Review skipped (cycle {cycle})\n\n\
1166 Reviewer agent encountered an error. Continuing without review.\n\n\
1167 **Error:** {error:#}{COMMENT_FOOTER}"
1168 )
1169}
1170
1171fn format_fix_skipped_comment(cycle: u32, error: &anyhow::Error) -> String {
1172 format!(
1173 "### Fix skipped (cycle {cycle})\n\n\
1174 Fixer agent encountered an error. Continuing to next cycle.\n\n\
1175 **Error:** {error:#}{COMMENT_FOOTER}"
1176 )
1177}
1178
1179fn format_rebase_comment(outcome: &RebaseOutcome) -> String {
1180 match outcome {
1181 RebaseOutcome::Clean => {
1182 format!("### Rebase\n\nRebased onto base branch cleanly.{COMMENT_FOOTER}")
1183 }
1184 RebaseOutcome::AgentResolved => {
1185 format!(
1186 "### Rebase\n\n\
1187 Rebase had conflicts. Agent resolved them.{COMMENT_FOOTER}"
1188 )
1189 }
1190 RebaseOutcome::RebaseConflicts(_) => {
1191 format!(
1192 "### Rebase\n\n\
1193 Rebase conflicts present (awaiting resolution).{COMMENT_FOOTER}"
1194 )
1195 }
1196 RebaseOutcome::Failed(msg) => {
1197 format!(
1198 "### Rebase failed\n\n\
1199 Could not rebase onto the base branch.\n\n\
1200 **Error:** {msg}{COMMENT_FOOTER}"
1201 )
1202 }
1203 }
1204}
1205
1206fn format_ready_comment() -> String {
1207 format!(
1208 "### Ready for review\n\nPipeline complete. This PR is ready for manual review.{COMMENT_FOOTER}"
1209 )
1210}
1211
1212fn format_merge_comment() -> String {
1213 format!("### Merged\n\nPipeline complete. PR has been merged.{COMMENT_FOOTER}")
1214}
1215
1216fn format_pipeline_failure(e: &anyhow::Error) -> String {
1217 format!(
1218 "## Pipeline failed\n\n\
1219 **Error:** {e:#}\n\n\
1220 The pipeline hit an unrecoverable error. Check the run logs for detail, \
1221 or re-run the pipeline.\
1222 {COMMENT_FOOTER}"
1223 )
1224}
1225
1226fn pr_title(ctx: &AgentContext) -> String {
1231 let prefix = infer_commit_type(&ctx.issue_title);
1232 if ctx.issue_source == "github" {
1233 format!("{prefix}(#{}): {}", ctx.issue_number, ctx.issue_title)
1234 } else {
1235 format!("{prefix}: {}", ctx.issue_title)
1236 }
1237}
1238
1239fn infer_commit_type(title: &str) -> &'static str {
1241 let lower = title.to_lowercase();
1242 if lower.starts_with("feat") || lower.contains("add ") || lower.contains("implement ") {
1243 "feat"
1244 } else if lower.starts_with("refactor") {
1245 "refactor"
1246 } else if lower.starts_with("docs") || lower.starts_with("document") {
1247 "docs"
1248 } else if lower.starts_with("test") || lower.starts_with("add test") {
1249 "test"
1250 } else if lower.starts_with("chore") {
1251 "chore"
1252 } else {
1253 "fix"
1254 }
1255}
1256
1257fn build_pr_body(impl_output: &str, ctx: &AgentContext) -> String {
1259 let issue_ref = if ctx.issue_source == "github" {
1260 format!("Resolves #{}", ctx.issue_number)
1261 } else {
1262 format!("From local issue #{}", ctx.issue_number)
1263 };
1264
1265 let summary = extract_impl_summary(impl_output);
1266
1267 let mut body = String::new();
1268 let _ = writeln!(body, "{issue_ref}\n");
1269 let _ = write!(body, "{summary}");
1270 body.push_str(COMMENT_FOOTER);
1271 body
1272}
1273
1274fn extract_impl_summary(output: &str) -> String {
1280 let idx = output.find("## PR Template").or_else(|| output.find("## Changes Made"));
1282
1283 if let Some(idx) = idx {
1284 let summary = output[idx..].trim();
1285 let summary = summary.strip_prefix("## PR Template").map_or(summary, |s| s.trim_start());
1287 if summary.len() <= 4000 {
1288 return summary.to_string();
1289 }
1290 return truncate(summary, 4000);
1291 }
1292 String::from("*No implementation summary available. See commit history for details.*")
1295}
1296
1297fn new_run(run_id: &str, issue: &PipelineIssue, auto_merge: bool) -> Run {
1298 Run {
1299 id: run_id.to_string(),
1300 issue_number: issue.number,
1301 status: RunStatus::Pending,
1302 pr_number: None,
1303 branch: None,
1304 worktree_path: None,
1305 cost_usd: 0.0,
1306 auto_merge,
1307 started_at: chrono::Utc::now().to_rfc3339(),
1308 finished_at: None,
1309 error_message: None,
1310 complexity: "full".to_string(),
1311 issue_source: issue.source.to_string(),
1312 }
1313}
1314
1315pub fn generate_run_id() -> String {
1317 uuid::Uuid::new_v4().to_string()[..8].to_string()
1318}
1319
1320pub(crate) fn truncate(s: &str, max_len: usize) -> String {
1325 if s.len() <= max_len {
1326 return s.to_string();
1327 }
1328 let target = max_len.saturating_sub(3);
1329 let mut end = target;
1330 while end > 0 && !s.is_char_boundary(end) {
1331 end -= 1;
1332 }
1333 format!("{}...", &s[..end])
1334}
1335
1336#[cfg(test)]
1337mod tests {
1338 use proptest::prelude::*;
1339
1340 use super::*;
1341
1342 proptest! {
1343 #[test]
1344 fn run_ids_always_8_hex_chars(_seed in any::<u64>()) {
1345 let id = generate_run_id();
1346 prop_assert_eq!(id.len(), 8);
1347 prop_assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
1348 }
1349 }
1350
1351 #[test]
1352 fn run_id_is_8_hex_chars() {
1353 let id = generate_run_id();
1354 assert_eq!(id.len(), 8);
1355 assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
1356 }
1357
1358 #[test]
1359 fn run_ids_are_unique() {
1360 let ids: Vec<_> = (0..100).map(|_| generate_run_id()).collect();
1361 let unique: std::collections::HashSet<_> = ids.iter().collect();
1362 assert_eq!(ids.len(), unique.len());
1363 }
1364
1365 #[test]
1366 fn truncate_short_string() {
1367 assert_eq!(truncate("hello", 10), "hello");
1368 }
1369
1370 #[test]
1371 fn truncate_long_string() {
1372 let long = "a".repeat(100);
1373 let result = truncate(&long, 10);
1374 assert_eq!(result.len(), 10); assert!(result.ends_with("..."));
1376 }
1377
1378 #[test]
1379 fn truncate_multibyte_does_not_panic() {
1380 let s = "πππ";
1383 let result = truncate(s, 8);
1384 assert!(result.ends_with("..."));
1385 assert!(result.starts_with("π"));
1386 assert!(result.len() <= 8);
1387 }
1388
1389 #[test]
1390 fn truncate_cjk_boundary() {
1391 let s = "δ½ ε₯½δΈηζ΅θ―"; let result = truncate(s, 10);
1395 assert!(result.ends_with("..."));
1396 assert!(result.starts_with("δ½ ε₯½"));
1397 assert!(result.len() <= 10);
1398 }
1399
1400 #[test]
1401 fn extract_impl_summary_finds_changes_made() {
1402 let output = "Some preamble text\n\n## Changes Made\n- src/foo.rs: added bar\n\n## Tests Added\n- tests/foo.rs: bar test\n";
1403 let summary = extract_impl_summary(output);
1404 assert!(summary.starts_with("## Changes Made"));
1405 assert!(summary.contains("added bar"));
1406 assert!(summary.contains("## Tests Added"));
1407 }
1408
1409 #[test]
1410 fn extract_impl_summary_prefers_pr_template() {
1411 let output = "Preamble\n\n## PR Template\n## Summary\n- Added auth flow\n\n## Testing\n- Unit tests pass\n";
1412 let summary = extract_impl_summary(output);
1413 assert!(!summary.contains("## PR Template"));
1415 assert!(summary.starts_with("## Summary"));
1416 assert!(summary.contains("Added auth flow"));
1417 }
1418
1419 #[test]
1420 fn extract_impl_summary_fallback_on_no_heading() {
1421 let output = "just some raw agent output with no structure";
1422 let summary = extract_impl_summary(output);
1423 assert_eq!(
1424 summary,
1425 "*No implementation summary available. See commit history for details.*"
1426 );
1427 }
1428
1429 #[test]
1430 fn extract_impl_summary_empty_output() {
1431 let placeholder = "*No implementation summary available. See commit history for details.*";
1432 assert_eq!(extract_impl_summary(""), placeholder);
1433 assert_eq!(extract_impl_summary(" "), placeholder);
1434 }
1435
1436 #[test]
1437 fn build_pr_body_github_issue() {
1438 let ctx = AgentContext {
1439 issue_number: 42,
1440 issue_title: "fix the thing".to_string(),
1441 issue_body: String::new(),
1442 branch: "oven/issue-42".to_string(),
1443 pr_number: Some(10),
1444 test_command: None,
1445 lint_command: None,
1446 review_findings: None,
1447 cycle: 1,
1448 target_repo: None,
1449 issue_source: "github".to_string(),
1450 base_branch: "main".to_string(),
1451 };
1452 let body = build_pr_body("## Changes Made\n- added stuff", &ctx);
1453 assert!(body.contains("Resolves #42"));
1454 assert!(body.contains("## Changes Made"));
1455 assert!(body.contains("Automated by [oven]"));
1456 }
1457
1458 #[test]
1459 fn build_pr_body_local_issue() {
1460 let ctx = AgentContext {
1461 issue_number: 7,
1462 issue_title: "local thing".to_string(),
1463 issue_body: String::new(),
1464 branch: "oven/issue-7".to_string(),
1465 pr_number: Some(10),
1466 test_command: None,
1467 lint_command: None,
1468 review_findings: None,
1469 cycle: 1,
1470 target_repo: None,
1471 issue_source: "local".to_string(),
1472 base_branch: "main".to_string(),
1473 };
1474 let body = build_pr_body("## Changes Made\n- did local stuff", &ctx);
1475 assert!(body.contains("From local issue #7"));
1476 assert!(body.contains("## Changes Made"));
1477 }
1478
1479 #[test]
1480 fn pr_title_github() {
1481 let ctx = AgentContext {
1482 issue_number: 42,
1483 issue_title: "fix the thing".to_string(),
1484 issue_body: String::new(),
1485 branch: String::new(),
1486 pr_number: None,
1487 test_command: None,
1488 lint_command: None,
1489 review_findings: None,
1490 cycle: 1,
1491 target_repo: None,
1492 issue_source: "github".to_string(),
1493 base_branch: "main".to_string(),
1494 };
1495 assert_eq!(pr_title(&ctx), "fix(#42): fix the thing");
1496 }
1497
1498 #[test]
1499 fn pr_title_local() {
1500 let ctx = AgentContext {
1501 issue_number: 7,
1502 issue_title: "local thing".to_string(),
1503 issue_body: String::new(),
1504 branch: String::new(),
1505 pr_number: None,
1506 test_command: None,
1507 lint_command: None,
1508 review_findings: None,
1509 cycle: 1,
1510 target_repo: None,
1511 issue_source: "local".to_string(),
1512 base_branch: "main".to_string(),
1513 };
1514 assert_eq!(pr_title(&ctx), "fix: local thing");
1515 }
1516
1517 #[test]
1518 fn infer_commit_type_feat() {
1519 assert_eq!(infer_commit_type("Add dark mode support"), "feat");
1520 assert_eq!(infer_commit_type("Implement caching layer"), "feat");
1521 assert_eq!(infer_commit_type("Feature: new dashboard"), "feat");
1522 }
1523
1524 #[test]
1525 fn infer_commit_type_refactor() {
1526 assert_eq!(infer_commit_type("Refactor auth middleware"), "refactor");
1527 }
1528
1529 #[test]
1530 fn infer_commit_type_docs() {
1531 assert_eq!(infer_commit_type("Document the API endpoints"), "docs");
1532 assert_eq!(infer_commit_type("Docs: update README"), "docs");
1533 }
1534
1535 #[test]
1536 fn infer_commit_type_defaults_to_fix() {
1537 assert_eq!(infer_commit_type("Null pointer in config parser"), "fix");
1538 assert_eq!(infer_commit_type("Crash on empty input"), "fix");
1539 }
1540
1541 #[test]
1542 fn pr_title_feat_github() {
1543 let ctx = AgentContext {
1544 issue_number: 10,
1545 issue_title: "Add dark mode".to_string(),
1546 issue_body: String::new(),
1547 branch: String::new(),
1548 pr_number: None,
1549 test_command: None,
1550 lint_command: None,
1551 review_findings: None,
1552 cycle: 1,
1553 target_repo: None,
1554 issue_source: "github".to_string(),
1555 base_branch: "main".to_string(),
1556 };
1557 assert_eq!(pr_title(&ctx), "feat(#10): Add dark mode");
1558 }
1559
1560 #[test]
1561 fn format_unresolved_comment_groups_by_severity() {
1562 let findings = [
1563 agents::Finding {
1564 severity: Severity::Critical,
1565 category: "bug".to_string(),
1566 file_path: Some("src/main.rs".to_string()),
1567 line_number: Some(42),
1568 message: "null pointer".to_string(),
1569 },
1570 agents::Finding {
1571 severity: Severity::Warning,
1572 category: "style".to_string(),
1573 file_path: None,
1574 line_number: None,
1575 message: "missing docs".to_string(),
1576 },
1577 ];
1578 let refs: Vec<_> = findings.iter().collect();
1579 let comment = format_unresolved_comment(&refs);
1580 assert!(comment.contains("#### Critical"));
1581 assert!(comment.contains("#### Warning"));
1582 assert!(comment.contains("**bug** in `src/main.rs:42` -- null pointer"));
1583 assert!(comment.contains("**style** -- missing docs"));
1584 assert!(comment.contains("Automated by [oven]"));
1585 }
1586
1587 #[test]
1588 fn format_unresolved_comment_skips_empty_severity_groups() {
1589 let findings = [agents::Finding {
1590 severity: Severity::Warning,
1591 category: "testing".to_string(),
1592 file_path: Some("src/lib.rs".to_string()),
1593 line_number: None,
1594 message: "missing edge case test".to_string(),
1595 }];
1596 let refs: Vec<_> = findings.iter().collect();
1597 let comment = format_unresolved_comment(&refs);
1598 assert!(!comment.contains("#### Critical"));
1599 assert!(comment.contains("#### Warning"));
1600 }
1601
1602 #[test]
1603 fn format_pipeline_failure_includes_error() {
1604 let err = anyhow::anyhow!("cost budget exceeded: $12.50 > $10.00");
1605 let comment = format_pipeline_failure(&err);
1606 assert!(comment.contains("## Pipeline failed"));
1607 assert!(comment.contains("cost budget exceeded"));
1608 assert!(comment.contains("Automated by [oven]"));
1609 }
1610
1611 #[test]
1612 fn format_impl_comment_includes_summary() {
1613 let comment = format_impl_comment("Added login endpoint with tests");
1614 assert!(comment.contains("### Implementation complete"));
1615 assert!(comment.contains("Added login endpoint with tests"));
1616 assert!(comment.contains("Automated by [oven]"));
1617 }
1618
1619 #[test]
1620 fn format_review_comment_clean() {
1621 let comment = format_review_comment(1, &[]);
1622 assert!(comment.contains("### Review complete (cycle 1)"));
1623 assert!(comment.contains("Clean review"));
1624 }
1625
1626 #[test]
1627 fn format_review_comment_with_findings() {
1628 let findings = [agents::Finding {
1629 severity: Severity::Critical,
1630 category: "bug".to_string(),
1631 file_path: Some("src/main.rs".to_string()),
1632 line_number: Some(42),
1633 message: "null pointer".to_string(),
1634 }];
1635 let refs: Vec<_> = findings.iter().collect();
1636 let comment = format_review_comment(1, &refs);
1637 assert!(comment.contains("### Review complete (cycle 1)"));
1638 assert!(comment.contains("1 finding"));
1639 assert!(comment.contains("[critical]"));
1640 assert!(comment.contains("`src/main.rs:42`"));
1641 }
1642
1643 #[test]
1644 fn format_fix_comment_counts() {
1645 let fixer = agents::FixerOutput {
1646 addressed: vec![
1647 agents::FixerAction { finding: 1, action: "fixed it".to_string() },
1648 agents::FixerAction { finding: 2, action: "also fixed".to_string() },
1649 ],
1650 disputed: vec![agents::FixerDispute { finding: 3, reason: "not a bug".to_string() }],
1651 };
1652 let comment = format_fix_comment(1, &fixer);
1653 assert!(comment.contains("### Fix complete (cycle 1)"));
1654 assert!(comment.contains("Addressed:** 2 findings"));
1655 assert!(comment.contains("Disputed:** 1 finding\n"));
1656 }
1657
1658 #[test]
1659 fn format_rebase_comment_variants() {
1660 let clean = format_rebase_comment(&RebaseOutcome::Clean);
1661 assert!(clean.contains("Rebased onto base branch cleanly"));
1662
1663 let agent = format_rebase_comment(&RebaseOutcome::AgentResolved);
1664 assert!(agent.contains("Agent resolved them"));
1665
1666 let conflicts =
1667 format_rebase_comment(&RebaseOutcome::RebaseConflicts(vec!["foo.rs".into()]));
1668 assert!(conflicts.contains("awaiting resolution"));
1669
1670 let failed = format_rebase_comment(&RebaseOutcome::Failed("conflict in foo.rs".into()));
1671 assert!(failed.contains("Rebase failed"));
1672 assert!(failed.contains("conflict in foo.rs"));
1673 }
1674
1675 #[test]
1676 fn format_ready_comment_content() {
1677 let comment = format_ready_comment();
1678 assert!(comment.contains("### Ready for review"));
1679 assert!(comment.contains("manual review"));
1680 }
1681
1682 #[test]
1683 fn format_merge_comment_content() {
1684 let comment = format_merge_comment();
1685 assert!(comment.contains("### Merged"));
1686 }
1687}