example.rs

   1use crate::{AgentAppState, ToolMetrics};
   2use agent::{ThreadEvent, ThreadStore};
   3use anyhow::{Context as _, Result, anyhow};
   4use assistant_tool::ToolWorkingSet;
   5use client::proto::LspWorkProgress;
   6use futures::channel::mpsc;
   7use futures::{FutureExt, StreamExt as _, select_biased};
   8use gpui::{App, AppContext as _, AsyncApp, Entity, Task};
   9use handlebars::Handlebars;
  10use language::{Buffer, DiagnosticSeverity, OffsetRangeExt};
  11use language_model::{
  12    LanguageModel, LanguageModelCompletionEvent, LanguageModelRequest, LanguageModelRequestMessage,
  13    MessageContent, Role, StopReason, TokenUsage,
  14};
  15use project::{Project, ProjectPath};
  16use serde::{Deserialize, Serialize};
  17use std::cell::RefCell;
  18use std::fmt::Write as _;
  19use std::fs::File;
  20use std::io::Write as _;
  21use std::rc::Rc;
  22use std::sync::{Arc, Mutex};
  23use std::time::Duration;
  24use std::{
  25    fs,
  26    path::{Path, PathBuf},
  27};
  28use unindent::Unindent as _;
  29use util::ResultExt as _;
  30use util::command::new_smol_command;
  31use util::markdown::MarkdownString;
  32use util::serde::default_true;
  33
  34pub const EXAMPLES_DIR: &str = "./crates/eval/examples";
  35pub const REPOS_DIR: &str = "./crates/eval/repos";
  36pub const WORKTREES_DIR: &str = "./crates/eval/worktrees";
  37
  38const THREAD_EVENT_TIMEOUT: Duration = Duration::from_secs(60 * 2);
  39
  40const ZED_REPO_URL: &str = "https://github.com/zed-industries/zed.git";
  41
  42#[derive(Clone, Debug, Deserialize)]
  43pub struct ExampleBase {
  44    pub url: String,
  45    pub revision: String,
  46    pub language_extension: Option<String>,
  47    pub insert_id: Option<String>,
  48    #[serde(default = "default_true")]
  49    pub require_lsp: bool,
  50    #[serde(default)]
  51    pub allow_preexisting_diagnostics: bool,
  52}
  53
  54impl ExampleBase {
  55    pub fn repo_name(&self) -> String {
  56        self.url
  57            .split('/')
  58            .next_back()
  59            .unwrap_or(&"")
  60            .trim_end_matches(".git")
  61            .into()
  62    }
  63}
  64
  65#[derive(Clone, Debug)]
  66pub struct Example {
  67    pub name: String,
  68    /// Content of `base.toml`
  69    pub base: ExampleBase,
  70    /// Content of `prompt.md`
  71    pub prompt: String,
  72    /// Content of `diff_criteria.md`
  73    pub diff_criteria: String,
  74    /// Content of `thread_criteria.md`, if that file exists (it's optional)
  75    pub thread_criteria: Option<String>,
  76    /// Path to the directory containing the requests and responses for the agentic loop
  77    pub run_directory_path: PathBuf,
  78    /// Prefix used for logging that identifies this example
  79    pub log_prefix: String,
  80}
  81
  82#[derive(Debug, Serialize, Deserialize, Clone)]
  83pub struct RunOutput {
  84    pub repository_diff: String,
  85    pub ran_diagnostics_check: bool,
  86    pub diagnostics_before: Option<String>,
  87    pub diagnostics_after: Option<String>,
  88    pub response_count: usize,
  89    pub token_usage: TokenUsage,
  90    pub tool_metrics: ToolMetrics,
  91    pub last_request: LanguageModelRequest,
  92}
  93
  94#[derive(Debug, Clone, Serialize, Deserialize)]
  95pub struct JudgeDiffInput {
  96    pub repository_diff: String,
  97    pub ran_diagnostics_check: bool,
  98    #[serde(skip_serializing_if = "Option::is_none")]
  99    pub diagnostics_before: Option<String>,
 100    #[serde(skip_serializing_if = "Option::is_none")]
 101    pub diagnostics_after: Option<String>,
 102    pub criteria: String,
 103}
 104
 105#[derive(Debug, Clone, Serialize, Deserialize)]
 106pub struct JudgeThreadInput {
 107    pub messages: String,
 108    pub criteria: String,
 109}
 110
 111#[derive(Debug, Clone, Serialize, Deserialize)]
 112pub struct JudgeResponse {
 113    pub analysis: String,
 114    pub score: u32,
 115}
 116
 117#[derive(Debug, Clone, Serialize, Deserialize)]
 118pub struct JudgeOutput {
 119    pub thread: Option<JudgeResponse>,
 120    pub diff: JudgeResponse,
 121}
 122
 123impl Example {
 124    /// Load an example from a directory containing base.toml, prompt.md, and criteria.md
 125    pub fn load_from_directory(dir_path: &Path, run_dir: &Path) -> Result<Self> {
 126        let name = Self::name_from_path(dir_path);
 127        let base_path = dir_path.join("base.toml");
 128        let prompt_path = dir_path.join("prompt.md");
 129        let diff_criteria_path = dir_path.join("diff_criteria.md");
 130        let thread_criteria_path = dir_path.join("thread_criteria.md");
 131        let thread_criteria = if thread_criteria_path.exists() {
 132            Some(fs::read_to_string(thread_criteria_path.clone())?)
 133        } else {
 134            None
 135        };
 136
 137        Ok(Example {
 138            name: name.clone(),
 139            base: toml::from_str(&fs::read_to_string(&base_path)?)?,
 140            prompt: fs::read_to_string(prompt_path.clone())?,
 141            thread_criteria,
 142            diff_criteria: fs::read_to_string(diff_criteria_path.clone())?,
 143            run_directory_path: run_dir.to_path_buf(),
 144            log_prefix: name,
 145        })
 146    }
 147
 148    pub fn set_repetition_number(&mut self, repetition_number: u32) {
 149        if repetition_number > 0 {
 150            self.name = format!("{}-{}", self.name, repetition_number);
 151        }
 152    }
 153
 154    pub fn example_output_directory(&self) -> PathBuf {
 155        self.run_directory_path.join(&self.name)
 156    }
 157
 158    pub fn set_log_prefix_style(&mut self, color: &str, name_width: usize) {
 159        self.log_prefix = format!(
 160            "{}{:<width$}\x1b[0m | ",
 161            color,
 162            self.name,
 163            width = name_width
 164        );
 165    }
 166
 167    pub fn name_from_path(path: &Path) -> String {
 168        path.file_name().unwrap().to_string_lossy().to_string()
 169    }
 170
 171    pub fn worktree_path(&self) -> PathBuf {
 172        Path::new(WORKTREES_DIR)
 173            .canonicalize()
 174            .context(format!("No such directory {WORKTREES_DIR}"))
 175            .unwrap()
 176            .join(&self.name)
 177            .join(self.base.repo_name())
 178    }
 179
 180    /// Set up the example by checking out the specified Git revision
 181    pub async fn setup(&mut self) -> Result<()> {
 182        let repo_path = repo_path_for_url(&self.base.url);
 183
 184        let revision_exists = run_git(
 185            &repo_path,
 186            &["rev-parse", &format!("{}^{{commit}}", self.base.revision)],
 187        )
 188        .await
 189        .is_ok();
 190
 191        if !revision_exists {
 192            println!(
 193                "{}Fetching revision {}",
 194                self.log_prefix, &self.base.revision
 195            );
 196            run_git(
 197                &repo_path,
 198                &["fetch", "--depth", "1", "origin", &self.base.revision],
 199            )
 200            .await?;
 201        }
 202
 203        let worktree_path = self.worktree_path();
 204
 205        if worktree_path.is_dir() {
 206            println!("{}Resetting existing worktree", self.log_prefix);
 207
 208            // TODO: consider including "-x" to remove ignored files. The downside of this is that
 209            // it will also remove build artifacts, and so prevent incremental reuse there.
 210            run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
 211            run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
 212            run_git(&worktree_path, &["checkout", &self.base.revision]).await?;
 213        } else {
 214            println!("{}Creating worktree", self.log_prefix);
 215
 216            let worktree_path_string = worktree_path.to_string_lossy().to_string();
 217
 218            run_git(
 219                &repo_path,
 220                &[
 221                    "worktree",
 222                    "add",
 223                    "-f",
 224                    &worktree_path_string,
 225                    &self.base.revision,
 226                ],
 227            )
 228            .await?;
 229        }
 230
 231        if self.base.url == ZED_REPO_URL {
 232            std::fs::write(worktree_path.join(".rules"), std::fs::read(".rules")?)?;
 233        }
 234
 235        std::fs::create_dir_all(self.example_output_directory())?;
 236
 237        Ok(())
 238    }
 239
 240    pub fn run(
 241        &self,
 242        model: Arc<dyn LanguageModel>,
 243        app_state: Arc<AgentAppState>,
 244        cx: &mut App,
 245    ) -> Task<Result<RunOutput>> {
 246        let project = Project::local(
 247            app_state.client.clone(),
 248            app_state.node_runtime.clone(),
 249            app_state.user_store.clone(),
 250            app_state.languages.clone(),
 251            app_state.fs.clone(),
 252            None,
 253            cx,
 254        );
 255
 256        let worktree_path = self.worktree_path();
 257        let worktree = project.update(cx, |project, cx| {
 258            project.create_worktree(&worktree_path, true, cx)
 259        });
 260
 261        let tools = cx.new(|_| ToolWorkingSet::default());
 262        let thread_store =
 263            ThreadStore::load(project.clone(), tools, app_state.prompt_builder.clone(), cx);
 264        let this = self.clone();
 265
 266        cx.spawn(async move |cx| {
 267            let worktree = worktree.await?;
 268
 269            // Wait for worktree scan to finish before choosing a file to open.
 270            worktree
 271                .update(cx, |worktree, _cx| {
 272                    worktree.as_local().unwrap().scan_complete()
 273                })?
 274                .await;
 275
 276            let lsp = if this.base.require_lsp {
 277                let language_extension = this.base.language_extension.as_deref().context(
 278                    "language_extension field is required in base.toml when `require_lsp == true`",
 279                )?;
 280
 281                // Open a file that matches the language to cause LSP to start.
 282                let language_file = worktree.read_with(cx, |worktree, _cx| {
 283                    worktree
 284                        .files(false, 0)
 285                        .find_map(|e| {
 286                            if e.path.clone().extension().and_then(|ext| ext.to_str())
 287                                == Some(language_extension)
 288                            {
 289                                Some(ProjectPath {
 290                                    worktree_id: worktree.id(),
 291                                    path: e.path.clone(),
 292                                })
 293                            } else {
 294                                None
 295                            }
 296                        })
 297                        .context("Failed to find a file for example language")
 298                })??;
 299
 300                let open_language_file_buffer_task = project.update(cx, |project, cx| {
 301                    project.open_buffer(language_file.clone(), cx)
 302                })?;
 303
 304                let language_file_buffer = open_language_file_buffer_task.await?;
 305
 306                let lsp_open_handle = project.update(cx, |project, cx| {
 307                    project.register_buffer_with_language_servers(&language_file_buffer, cx)
 308                })?;
 309
 310                wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
 311
 312                Some((lsp_open_handle, language_file_buffer))
 313            } else {
 314                None
 315            };
 316
 317            let diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
 318            if diagnostics_before.is_some() && !this.base.allow_preexisting_diagnostics {
 319                return Err(anyhow!("Example has pre-existing diagnostics. If you want to run this example regardless, set `allow_preexisting_diagnostics` to `true` in `base.toml`"));
 320            }
 321
 322            if std::env::var("ZED_EVAL_SETUP_ONLY").is_ok() {
 323                return Err(anyhow!("Setup only mode"));
 324            }
 325
 326            let thread_store = thread_store.await?;
 327            let thread =
 328                thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx))?;
 329            let last_request = Rc::new(RefCell::new(None));
 330
 331            thread.update(cx, |thread, _cx| {
 332                let mut request_count = 0;
 333                let example_dir_path = this.example_output_directory();
 334
 335                let last_request = Rc::clone(&last_request);
 336                thread.set_request_callback(move |request, response_events| {
 337                    *last_request.borrow_mut() = Some(request.clone());
 338
 339                    request_count += 1;
 340                    let messages_file_path = example_dir_path.join(format!("{request_count}.messages.md"));
 341                    let last_messages_file_path = example_dir_path.join("last.messages.md");
 342                    let request_markdown = RequestMarkdown::new(request);
 343                    let response_events_markdown = response_events_to_markdown(response_events);
 344
 345                    let messages = format!("{}\n\n{}", request_markdown.messages, response_events_markdown);
 346                    fs::write(messages_file_path, messages.clone()).expect("failed to write messages file");
 347                    fs::write(last_messages_file_path, messages).expect("failed to write last messages file");
 348
 349                    if request_count == 1 {
 350                        let tools_file_path = example_dir_path.join("tools.md");
 351                        fs::write(tools_file_path, request_markdown.tools).expect("failed to write tools file");
 352                    }
 353                });
 354            })?;
 355
 356            let tool_metrics = Arc::new(Mutex::new(ToolMetrics::default()));
 357
 358            let (thread_event_tx, mut thread_event_rx) = mpsc::unbounded();
 359
 360            let subscription = cx.subscribe(&thread, move |_thread, event: &ThreadEvent, _cx| {
 361                thread_event_tx.unbounded_send(event.clone()).log_err();
 362            });
 363
 364            let event_handler_task = cx.spawn({
 365                let log_prefix = this.log_prefix.clone();
 366                let tool_metrics = tool_metrics.clone();
 367                let thread = thread.downgrade();
 368                async move |cx| {
 369                    loop {
 370                        let event = select_biased! {
 371                            event = thread_event_rx.next() => event,
 372                            _ = cx.background_executor().timer(THREAD_EVENT_TIMEOUT).fuse() => {
 373                                return Err(anyhow!("Agentic loop stalled - waited {:?} without any events", THREAD_EVENT_TIMEOUT));
 374                            }
 375                        };
 376                        let Some(event) = event else {
 377                            return Err(anyhow!("ThreadEvent channel ended early"));
 378                        };
 379
 380                        match event {
 381                            ThreadEvent::Stopped(reason) => match reason {
 382                                Ok(StopReason::EndTurn) => {
 383                                    return Ok(());
 384                                }
 385                                Ok(StopReason::MaxTokens) => {
 386                                    return Err(anyhow!("Exceeded maximum tokens"));
 387                                }
 388                                Ok(StopReason::ToolUse) => {
 389                                    if std::env::var("ZED_EVAL_DEBUG").is_ok() {
 390                                        println!("{}StopReason: Tool use", log_prefix);
 391                                    }
 392                                }
 393                                Err(error) => {
 394                                    return Err(anyhow!(error.clone()));
 395                                }
 396                            },
 397                            ThreadEvent::ShowError(thread_error) => {
 398                                break Err(anyhow!(thread_error.clone()));
 399                            }
 400                            ThreadEvent::StreamedAssistantText(_, _)| ThreadEvent::StreamedAssistantThinking(_, _) | ThreadEvent::UsePendingTools { .. } => {
 401                            }
 402                            ThreadEvent::ToolFinished {
 403                                tool_use_id,
 404                                pending_tool_use,
 405                                ..
 406                            } => {
 407                                thread.update(cx, |thread, _cx| {
 408                                    if let Some(tool_use) = pending_tool_use {
 409                                        let mut tool_metrics = tool_metrics.lock().unwrap();
 410                                        if let Some(tool_result) = thread.tool_result(&tool_use_id) {
 411                                            let message = if tool_result.is_error {
 412                                                format!("TOOL FAILED: {}", tool_use.name)
 413                                            } else {
 414                                                format!("TOOL FINISHED: {}", tool_use.name)
 415                                            };
 416                                            println!("{log_prefix}{message}");
 417                                            tool_metrics.insert(tool_result.tool_name.clone(), !tool_result.is_error);
 418                                        } else {
 419                                            let message = format!("TOOL FINISHED WITHOUT RESULT: {}", tool_use.name);
 420                                            println!("{log_prefix}{message}");
 421                                            tool_metrics.insert(tool_use.name.clone(), true);
 422                                        }
 423                                    }
 424                                })?;
 425                            }
 426                            ThreadEvent::ToolConfirmationNeeded => {
 427                                panic!("{}Bug: Tool confirmation should not be required in eval", log_prefix);
 428                            },
 429                            ThreadEvent::StreamedCompletion |
 430                            ThreadEvent::MessageAdded(_) |
 431                            ThreadEvent::MessageEdited(_) |
 432                            ThreadEvent::MessageDeleted(_) |
 433                            ThreadEvent::SummaryChanged |
 434                            ThreadEvent::SummaryGenerated |
 435                            ThreadEvent::CheckpointChanged |
 436                            ThreadEvent::UsageUpdated(_) => {
 437                                if std::env::var("ZED_EVAL_DEBUG").is_ok() {
 438                                    println!("{}Event: {:#?}", log_prefix, event);
 439                                }
 440                            }
 441                        }
 442                    }
 443                }
 444            });
 445
 446            thread.update(cx, |thread, cx| {
 447                let context = vec![];
 448                thread.insert_user_message(this.prompt.clone(), context, None, cx);
 449                thread.send_to_model(model, cx);
 450            })?;
 451
 452            event_handler_task.await?;
 453
 454            println!("{}Stopped", this.log_prefix);
 455
 456            if let Some((_, language_file_buffer)) = lsp.as_ref() {
 457                wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
 458            }
 459
 460            println!("{}Getting repository diff", this.log_prefix);
 461            let repository_diff = this.repository_diff().await?;
 462
 463            let example_output_dir = this.example_output_directory();
 464            let repository_diff_path = example_output_dir.join("patch.diff");
 465            let mut repository_diff_output_file = File::create(&repository_diff_path)?;
 466            writeln!(&mut repository_diff_output_file, "{}", &repository_diff).log_err();
 467
 468            println!("{}Getting diagnostics", this.log_prefix);
 469            let diagnostics_after = cx
 470                .update(move |cx| {
 471                    cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
 472                })?
 473                .await?;
 474            println!("{}Got diagnostics", this.log_prefix);
 475
 476            let Some(last_request) = last_request.borrow_mut().take() else {
 477                return Err(anyhow!("No requests ran."));
 478            };
 479
 480            drop(subscription);
 481            drop(lsp);
 482
 483            if let Some(diagnostics_before) = &diagnostics_before {
 484                fs::write(example_output_dir.join("diagnostics_before.txt"), diagnostics_before)?;
 485            }
 486
 487            if let Some(diagnostics_after) = &diagnostics_after {
 488                fs::write(example_output_dir.join("diagnostics_after.txt"), diagnostics_after)?;
 489            }
 490
 491
 492            thread.update(cx, |thread, _cx| {
 493                let response_count = thread
 494                    .messages()
 495                    .filter(|message| message.role == language_model::Role::Assistant)
 496                    .count();
 497                RunOutput {
 498                    repository_diff,
 499                    ran_diagnostics_check: this.base.require_lsp,
 500                    diagnostics_before,
 501                    diagnostics_after,
 502                    response_count,
 503                    token_usage: thread.cumulative_token_usage(),
 504                    tool_metrics: tool_metrics.lock().unwrap().clone(),
 505                    last_request,
 506                }
 507            })
 508        })
 509    }
 510
 511    async fn judge_diff(
 512        &self,
 513        model: Arc<dyn LanguageModel>,
 514        run_output: &RunOutput,
 515        judge_number: u32,
 516        cx: &AsyncApp,
 517    ) -> Result<(String, JudgeResponse)> {
 518        let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
 519        let judge_diff_prompt_name = "judge_diff_prompt";
 520        let mut hbs = Handlebars::new();
 521        hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)?;
 522
 523        let diff_prompt = hbs.render(
 524            judge_diff_prompt_name,
 525            &JudgeDiffInput {
 526                repository_diff: run_output.repository_diff.clone(),
 527                ran_diagnostics_check: run_output.ran_diagnostics_check,
 528                diagnostics_before: run_output.diagnostics_before.clone(),
 529                diagnostics_after: run_output.diagnostics_after.clone(),
 530                criteria: self.diff_criteria.clone(),
 531            },
 532        )?;
 533
 534        let request = LanguageModelRequest {
 535            thread_id: None,
 536            prompt_id: None,
 537            messages: vec![LanguageModelRequestMessage {
 538                role: Role::User,
 539                content: vec![MessageContent::Text(diff_prompt)],
 540                cache: false,
 541            }],
 542            temperature: None,
 543            tools: Vec::new(),
 544            stop: Vec::new(),
 545        };
 546
 547        let diff_response = send_language_model_request(model, request, cx).await?;
 548        let diff_output = JudgeResponse::parse(&diff_response)?;
 549
 550        println!(
 551            "{}Judge #{judge_number} - Diff score: {}",
 552            self.log_prefix, diff_output.score
 553        );
 554
 555        Ok((diff_response, diff_output))
 556    }
 557
 558    async fn judge_thread(
 559        &self,
 560        model: Arc<dyn LanguageModel>,
 561        run_output: &RunOutput,
 562        judge_number: u32,
 563        cx: &AsyncApp,
 564    ) -> Result<(String, Option<JudgeResponse>)> {
 565        if let Some(criteria) = self.thread_criteria.clone() {
 566            let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
 567            let judge_thread_prompt_name = "judge_thread_prompt";
 568            let mut hbs = Handlebars::new();
 569            hbs.register_template_string(judge_thread_prompt_name, judge_thread_prompt)?;
 570
 571            let request_markdown = RequestMarkdown::new(&run_output.last_request);
 572            let thread_prompt = hbs.render(
 573                judge_thread_prompt_name,
 574                &JudgeThreadInput {
 575                    messages: request_markdown.messages,
 576                    criteria,
 577                },
 578            )?;
 579
 580            let request = LanguageModelRequest {
 581                thread_id: None,
 582                prompt_id: None,
 583                messages: vec![LanguageModelRequestMessage {
 584                    role: Role::User,
 585                    content: vec![MessageContent::Text(thread_prompt)],
 586                    cache: false,
 587                }],
 588                temperature: None,
 589                tools: Vec::new(),
 590                stop: Vec::new(),
 591            };
 592
 593            let thread_response = send_language_model_request(model, request, cx).await?;
 594            let thread_output = JudgeResponse::parse(&thread_response)?;
 595
 596            println!(
 597                "{}Judge #{judge_number} - Thread score: {}",
 598                self.log_prefix, thread_output.score
 599            );
 600
 601            Ok((thread_response, Some(thread_output)))
 602        } else {
 603            let msg = "There were no criteria specified for this thread, so this example was not judged on its thread.".to_string();
 604            Ok((msg, None))
 605        }
 606    }
 607
 608    pub async fn judge(
 609        &self,
 610        model: Arc<dyn LanguageModel>,
 611        run_output: &RunOutput,
 612        judge_number: u32,
 613        cx: &AsyncApp,
 614    ) -> Result<JudgeOutput> {
 615        let mut output_file = File::create(
 616            self.example_output_directory()
 617                .join(format!("judge_{}.md", judge_number)),
 618        )
 619        .expect("failed to create judge.md");
 620
 621        println!("{}Running judge #{judge_number}", self.log_prefix);
 622
 623        let diff_task = self.judge_diff(model.clone(), &run_output, judge_number, cx);
 624        let thread_task = self.judge_thread(model.clone(), &run_output, judge_number, cx);
 625
 626        let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
 627
 628        let (diff_response, diff_output) = diff_result?;
 629        let (thread_response, thread_output) = thread_result?;
 630
 631        writeln!(
 632            &mut output_file,
 633            "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
 634        )
 635        .log_err();
 636
 637        Ok(JudgeOutput {
 638            thread: thread_output,
 639            diff: diff_output,
 640        })
 641    }
 642
 643    async fn repository_diff(&self) -> Result<String> {
 644        let worktree_path = self.worktree_path();
 645        run_git(&worktree_path, &["add", "."]).await?;
 646        let mut diff_args = vec!["diff", "--staged"];
 647        if self.base.url == ZED_REPO_URL {
 648            diff_args.push(":(exclude).rules");
 649        }
 650        run_git(&worktree_path, &diff_args).await
 651    }
 652}
 653
 654fn wait_for_lang_server(
 655    project: &Entity<Project>,
 656    buffer: &Entity<Buffer>,
 657    log_prefix: String,
 658    cx: &mut AsyncApp,
 659) -> Task<Result<()>> {
 660    println!("{}⏵ Waiting for language server", log_prefix);
 661
 662    let (mut tx, mut rx) = mpsc::channel(1);
 663
 664    let lsp_store = project
 665        .update(cx, |project, _| project.lsp_store())
 666        .unwrap();
 667
 668    let has_lang_server = buffer
 669        .update(cx, |buffer, cx| {
 670            lsp_store.update(cx, |lsp_store, cx| {
 671                lsp_store
 672                    .language_servers_for_local_buffer(&buffer, cx)
 673                    .next()
 674                    .is_some()
 675            })
 676        })
 677        .unwrap_or(false);
 678
 679    if has_lang_server {
 680        project
 681            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
 682            .unwrap()
 683            .detach();
 684    }
 685
 686    let subscriptions =
 687        [
 688            cx.subscribe(&lsp_store, {
 689                let log_prefix = log_prefix.clone();
 690                move |_, event, _| match event {
 691                    project::LspStoreEvent::LanguageServerUpdate {
 692                        message:
 693                            client::proto::update_language_server::Variant::WorkProgress(
 694                                LspWorkProgress {
 695                                    message: Some(message),
 696                                    ..
 697                                },
 698                            ),
 699                        ..
 700                    } => println!("{}{message}", log_prefix),
 701                    _ => {}
 702                }
 703            }),
 704            cx.subscribe(&project, {
 705                let buffer = buffer.clone();
 706                move |project, event, cx| match event {
 707                    project::Event::LanguageServerAdded(_, _, _) => {
 708                        let buffer = buffer.clone();
 709                        project
 710                            .update(cx, |project, cx| project.save_buffer(buffer, cx))
 711                            .detach();
 712                    }
 713                    project::Event::DiskBasedDiagnosticsFinished { .. } => {
 714                        tx.try_send(()).ok();
 715                    }
 716                    _ => {}
 717                }
 718            }),
 719        ];
 720
 721    cx.spawn(async move |cx| {
 722        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
 723        let result = futures::select! {
 724            _ = rx.next() => {
 725                println!("{}⚑ Language server idle", log_prefix);
 726                anyhow::Ok(())
 727            },
 728            _ = timeout.fuse() => {
 729                Err(anyhow!("LSP wait timed out after 5 minutes"))
 730            }
 731        };
 732        drop(subscriptions);
 733        result
 734    })
 735}
 736
 737async fn query_lsp_diagnostics(
 738    project: Entity<Project>,
 739    cx: &mut AsyncApp,
 740) -> Result<Option<String>> {
 741    let paths_with_diagnostics = project.update(cx, |project, cx| {
 742        project
 743            .diagnostic_summaries(true, cx)
 744            .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
 745            .map(|(project_path, _, _)| project_path)
 746            .collect::<Vec<_>>()
 747    })?;
 748
 749    if paths_with_diagnostics.is_empty() {
 750        return Ok(None);
 751    }
 752
 753    let mut output = String::new();
 754    for project_path in paths_with_diagnostics {
 755        let buffer = project
 756            .update(cx, |project, cx| project.open_buffer(project_path, cx))?
 757            .await?;
 758        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 759
 760        for (_, group) in snapshot.diagnostic_groups(None) {
 761            let entry = &group.entries[group.primary_ix];
 762            let range = entry.range.to_point(&snapshot);
 763            let severity = match entry.diagnostic.severity {
 764                DiagnosticSeverity::ERROR => "error",
 765                DiagnosticSeverity::WARNING => "warning",
 766                _ => continue,
 767            };
 768
 769            writeln!(
 770                output,
 771                "{} at line {}: {}",
 772                severity,
 773                range.start.row + 1,
 774                entry.diagnostic.message
 775            )?;
 776        }
 777    }
 778    anyhow::Ok(Some(output))
 779}
 780
 781impl JudgeResponse {
 782    fn parse(response: &str) -> Result<Self> {
 783        let analysis = get_tag("analysis", response)?.to_string();
 784        let score = get_tag("score", response)?
 785            .parse()
 786            .context("error parsing score")?;
 787
 788        Ok(Self { analysis, score })
 789    }
 790}
 791
 792fn get_tag(name: &'static str, response: &str) -> Result<String> {
 793    let start_tag = format!("<{}>", name);
 794    let end_tag = format!("</{}>", name);
 795
 796    let start_ix = response
 797        .find(&start_tag)
 798        .context(format!("{} start tag not found", name))?;
 799    let content_start_ix = start_ix + start_tag.len();
 800
 801    let end_ix = content_start_ix
 802        + response[content_start_ix..]
 803            .find(&end_tag)
 804            .context(format!("{} end tag not found", name))?;
 805
 806    let content = response[content_start_ix..end_ix].trim().unindent();
 807
 808    anyhow::Ok(content)
 809}
 810
 811pub fn repo_path_for_url(repo_url: &str) -> PathBuf {
 812    let repo_name = repo_url
 813        .trim_start_matches("https://")
 814        .replace(|c: char| !c.is_alphanumeric(), "-");
 815    Path::new(REPOS_DIR)
 816        .canonicalize()
 817        .context(format!("No such directory {REPOS_DIR}"))
 818        .unwrap()
 819        .join(repo_name)
 820}
 821
 822pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
 823    let output = new_smol_command("git")
 824        .current_dir(repo_path)
 825        .args(args)
 826        .output()
 827        .await?;
 828
 829    if output.status.success() {
 830        Ok(String::from_utf8(output.stdout)?.trim().to_string())
 831    } else {
 832        Err(anyhow!(
 833            "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
 834            args.join(" "),
 835            repo_path.display(),
 836            output.status,
 837            String::from_utf8_lossy(&output.stderr),
 838            String::from_utf8_lossy(&output.stdout),
 839        ))
 840    }
 841}
 842
 843pub async fn send_language_model_request(
 844    model: Arc<dyn LanguageModel>,
 845    request: LanguageModelRequest,
 846    cx: &AsyncApp,
 847) -> anyhow::Result<String> {
 848    match model.stream_completion_text(request, &cx).await {
 849        Ok(mut stream) => {
 850            let mut full_response = String::new();
 851            while let Some(chunk_result) = stream.stream.next().await {
 852                match chunk_result {
 853                    Ok(chunk_str) => {
 854                        full_response.push_str(&chunk_str);
 855                    }
 856                    Err(err) => {
 857                        return Err(anyhow!(
 858                            "Error receiving response from language model: {err}"
 859                        ));
 860                    }
 861                }
 862            }
 863            Ok(full_response)
 864        }
 865        Err(err) => Err(anyhow!(
 866            "Failed to get response from language model. Error was: {err}"
 867        )),
 868    }
 869}
 870
 871struct RequestMarkdown {
 872    tools: String,
 873    messages: String,
 874}
 875
 876impl RequestMarkdown {
 877    fn new(request: &LanguageModelRequest) -> Self {
 878        let mut tools = String::new();
 879        let mut messages = String::new();
 880        let mut assistant_message_number: u32 = 1;
 881
 882        // Print the tools
 883        if !request.tools.is_empty() {
 884            for tool in &request.tools {
 885                write!(&mut tools, "# {}\n\n", tool.name).unwrap();
 886                write!(&mut tools, "{}\n\n", tool.description).unwrap();
 887                write!(
 888                    &mut tools,
 889                    "{}\n",
 890                    MarkdownString::code_block("json", &format!("{:#}", tool.input_schema))
 891                )
 892                .unwrap();
 893            }
 894        }
 895
 896        // Print the messages
 897        for message in &request.messages {
 898            match message.role {
 899                Role::System => messages.push_str("# ⚙️ SYSTEM\n\n"),
 900                Role::User => messages.push_str("# 👤 USER\n\n"),
 901                Role::Assistant => {
 902                    messages.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
 903                    assistant_message_number += 1;
 904                }
 905            };
 906
 907            for content in &message.content {
 908                match content {
 909                    MessageContent::Text(text) => {
 910                        messages.push_str(text);
 911                        messages.push_str("\n\n");
 912                    }
 913                    MessageContent::Image(_) => {
 914                        messages.push_str("[IMAGE DATA]\n\n");
 915                    }
 916                    MessageContent::Thinking { text, signature } => {
 917                        messages.push_str("**Thinking**:\n\n");
 918                        if let Some(sig) = signature {
 919                            messages.push_str(&format!("Signature: {}\n\n", sig));
 920                        }
 921                        messages.push_str(text);
 922                        messages.push_str("\n");
 923                    }
 924                    MessageContent::RedactedThinking(items) => {
 925                        messages.push_str(&format!(
 926                            "**Redacted Thinking**: {} item(s)\n\n",
 927                            items.len()
 928                        ));
 929                    }
 930                    MessageContent::ToolUse(tool_use) => {
 931                        messages.push_str(&format!(
 932                            "**Tool Use**: {} (ID: {})\n",
 933                            tool_use.name, tool_use.id
 934                        ));
 935                        messages.push_str(&format!(
 936                            "{}\n",
 937                            MarkdownString::code_block("json", &format!("{:#}", tool_use.input))
 938                        ));
 939                    }
 940                    MessageContent::ToolResult(tool_result) => {
 941                        messages.push_str(&format!(
 942                            "**Tool Result**: {} (ID: {})\n\n",
 943                            tool_result.tool_name, tool_result.tool_use_id
 944                        ));
 945                        if tool_result.is_error {
 946                            messages.push_str("**ERROR:**\n");
 947                        }
 948                        messages.push_str(&format!("{}\n\n", tool_result.content));
 949                    }
 950                }
 951            }
 952        }
 953
 954        Self { tools, messages }
 955    }
 956}
 957
 958fn response_events_to_markdown(
 959    response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
 960) -> String {
 961    let mut response = String::new();
 962    // Print the response events if any
 963    response.push_str("# Response\n\n");
 964    let mut text_buffer = String::new();
 965    let mut thinking_buffer = String::new();
 966
 967    let flush_buffers =
 968        |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
 969            if !text_buffer.is_empty() {
 970                output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
 971                text_buffer.clear();
 972            }
 973            if !thinking_buffer.is_empty() {
 974                output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
 975                thinking_buffer.clear();
 976            }
 977        };
 978
 979    for event in response_events {
 980        match event {
 981            Ok(LanguageModelCompletionEvent::Text(text)) => {
 982                text_buffer.push_str(text);
 983            }
 984            Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
 985                thinking_buffer.push_str(text);
 986            }
 987            Ok(LanguageModelCompletionEvent::Stop(reason)) => {
 988                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 989                response.push_str(&format!("**Stop**: {:?}\n\n", reason));
 990            }
 991            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
 992                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 993                response.push_str(&format!(
 994                    "**Tool Use**: {} (ID: {})\n",
 995                    tool_use.name, tool_use.id
 996                ));
 997                response.push_str(&format!(
 998                    "{}\n",
 999                    MarkdownString::code_block("json", &format!("{:#}", tool_use.input))
1000                ));
1001            }
1002            Ok(
1003                LanguageModelCompletionEvent::UsageUpdate(_)
1004                | LanguageModelCompletionEvent::StartMessage { .. },
1005            ) => {}
1006            Err(error) => {
1007                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1008                response.push_str(&format!("**Error**: {}\n\n", error));
1009            }
1010        }
1011    }
1012
1013    flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1014
1015    response
1016}
1017
1018#[cfg(test)]
1019mod test {
1020    use super::*;
1021    use handlebars::Handlebars;
1022
1023    #[test]
1024    fn test_parse_judge_output() {
1025        let response = r#"
1026            <analysis>The model did a good job but there were still compilations errors.</analysis>
1027            <score>3</score>
1028        "#
1029        .unindent();
1030
1031        let output = JudgeResponse::parse(&response).unwrap();
1032        assert_eq!(
1033            output.analysis,
1034            "The model did a good job but there were still compilations errors."
1035        );
1036        assert_eq!(output.score, 3);
1037
1038        let response = r#"
1039            Text around ignored
1040
1041            <analysis>
1042                Failed to compile:
1043                - Error 1
1044                - Error 2
1045            </analysis>
1046
1047            <score>1</score>
1048        "#
1049        .unindent();
1050
1051        let output = JudgeResponse::parse(&response).unwrap();
1052        assert_eq!(output.analysis, "Failed to compile:\n- Error 1\n- Error 2");
1053        assert_eq!(output.score, 1);
1054    }
1055
1056    #[test]
1057    fn test_judge_prompt_with_diagnostics() {
1058        // Case 1: Both diagnostics before and after are present
1059        let input = JudgeDiffInput {
1060            repository_diff: "diff content goes here".to_string(),
1061            ran_diagnostics_check: true,
1062            diagnostics_before: Some("Error at line 10: variable not found".to_string()),
1063            diagnostics_after: Some("Error at line 15: missing semicolon".to_string()),
1064            criteria: "Fix all bugs".to_string(),
1065        };
1066
1067        let rendered = templates().render(JUDGE_PROMPT_NAME, &input).unwrap();
1068
1069        let expected_diagnostics_section = r#"
1070            Take into account the diagnostics before and after applying the change:
1071
1072            <diagnostics_before>
1073            Error at line 10: variable not found
1074            </diagnostics_before>
1075
1076            <diagnostics_after>
1077            Error at line 15: missing semicolon
1078            </diagnostics_after>
1079            "#
1080        .unindent();
1081
1082        assert!(rendered.contains(&expected_diagnostics_section));
1083    }
1084
1085    #[test]
1086    fn test_judge_prompt_with_empty_diagnostics() {
1087        // Case 2: Diagnostics check run but no diagnostics found
1088        let input = JudgeDiffInput {
1089            repository_diff: "diff content goes here".to_string(),
1090            ran_diagnostics_check: true,
1091            diagnostics_before: None,
1092            diagnostics_after: None,
1093            criteria: "Fix all bugs".to_string(),
1094        };
1095
1096        let rendered = templates().render(JUDGE_PROMPT_NAME, &input).unwrap();
1097
1098        let expected_diagnostics_section = r#"
1099            Take into account the diagnostics before and after applying the change:
1100
1101            <diagnostics_before>
1102            No diagnostics before applying the edits.
1103            </diagnostics_before>
1104
1105            <diagnostics_after>
1106            No diagnostics after applying the edits.
1107            </diagnostics_after>
1108            "#
1109        .unindent();
1110
1111        assert!(rendered.contains(&expected_diagnostics_section));
1112    }
1113
1114    #[test]
1115    fn test_judge_prompt_with_mixed_diagnostics() {
1116        let templates = templates();
1117
1118        // Case 3: Before diagnostics present, after diagnostics absent
1119        let input = JudgeDiffInput {
1120            repository_diff: "diff content goes here".to_string(),
1121            ran_diagnostics_check: true,
1122            diagnostics_before: Some("Error at line 10: variable not found".to_string()),
1123            diagnostics_after: None,
1124            criteria: "Fix all bugs".to_string(),
1125        };
1126
1127        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1128
1129        let expected_diagnostics_section = r#"
1130            Take into account the diagnostics before and after applying the change:
1131
1132            <diagnostics_before>
1133            Error at line 10: variable not found
1134            </diagnostics_before>
1135
1136            <diagnostics_after>
1137            No diagnostics after applying the edits.
1138            </diagnostics_after>
1139            "#
1140        .unindent();
1141
1142        assert!(rendered.contains(&expected_diagnostics_section));
1143
1144        // Case 4: Before diagnostics absent, after diagnostics present
1145        let input = JudgeDiffInput {
1146            repository_diff: "diff content goes here".to_string(),
1147            ran_diagnostics_check: true,
1148            diagnostics_before: None,
1149            diagnostics_after: Some("Error at line 15: missing semicolon".to_string()),
1150            criteria: "Fix all bugs".to_string(),
1151        };
1152
1153        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1154
1155        let expected_diagnostics_section = r#"
1156            Take into account the diagnostics before and after applying the change:
1157
1158            <diagnostics_before>
1159            No diagnostics before applying the edits.
1160            </diagnostics_before>
1161
1162            <diagnostics_after>
1163            Error at line 15: missing semicolon
1164            </diagnostics_after>
1165            "#
1166        .unindent();
1167
1168        assert!(rendered.contains(&expected_diagnostics_section));
1169    }
1170
1171    #[test]
1172    fn test_judge_prompt_without_diagnostics() {
1173        let templates = templates();
1174
1175        // Case 5: No diagnostics check run
1176        let input = JudgeDiffInput {
1177            repository_diff: "diff content goes here".to_string(),
1178            ran_diagnostics_check: false,
1179            diagnostics_before: None,
1180            diagnostics_after: None,
1181            criteria: "Fix all bugs".to_string(),
1182        };
1183
1184        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1185
1186        // Check for the message when no diagnostics were performed
1187        let diagnostics_message = "No diagnostic checks were performed.";
1188
1189        assert!(rendered.contains(diagnostics_message));
1190        assert!(!rendered.contains("<diagnostics_before>"));
1191        assert!(!rendered.contains("<diagnostics_after>"));
1192    }
1193
1194    const JUDGE_PROMPT_NAME: &str = "judge_prompt";
1195
1196    fn templates() -> Handlebars<'static> {
1197        let mut judge_prompt = include_str!("judge_diff_prompt.hbs").to_string();
1198        language::LineEnding::normalize(&mut judge_prompt);
1199        let mut handlebars = Handlebars::new();
1200        handlebars
1201            .register_template_string(JUDGE_PROMPT_NAME, judge_prompt)
1202            .unwrap();
1203        handlebars
1204    }
1205}