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 example_output_dir = this.example_output_directory();
 327            let last_diff_file_path = example_output_dir.join("last.diff");
 328
 329            // Write an empty "last.diff" so that it can be opened in Zed for convenient view of the
 330            // history using undo/redo.
 331            std::fs::write(&last_diff_file_path, "")?;
 332
 333            let thread_store = thread_store.await?;
 334            let thread =
 335                thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx))?;
 336            let last_request = Rc::new(RefCell::new(None));
 337
 338            thread.update(cx, |thread, _cx| {
 339                let mut request_count = 0;
 340                let last_request = Rc::clone(&last_request);
 341                let previous_diff = Rc::new(RefCell::new("".to_string()));
 342                let example_output_dir = example_output_dir.clone();
 343                let last_diff_file_path = last_diff_file_path.clone();
 344                let this = this.clone();
 345                thread.set_request_callback(move |request, response_events| {
 346                    *last_request.borrow_mut() = Some(request.clone());
 347
 348                    request_count += 1;
 349                    let messages_file_path = example_output_dir.join(format!("{request_count}.messages.md"));
 350                    let diff_file_path = example_output_dir.join(format!("{request_count}.diff"));
 351                    let last_messages_file_path = example_output_dir.join("last.messages.md");
 352                    let request_markdown = RequestMarkdown::new(request);
 353                    let response_events_markdown = response_events_to_markdown(response_events);
 354
 355                    let messages = format!("{}\n\n{}", request_markdown.messages, response_events_markdown);
 356                    fs::write(&messages_file_path, messages.clone()).expect("failed to write messages file");
 357                    fs::write(&last_messages_file_path, messages).expect("failed to write last messages file");
 358
 359                    let diff_result = smol::block_on(this.repository_diff());
 360                    match diff_result {
 361                        Ok(diff) => {
 362                            if diff != previous_diff.borrow().clone() {
 363                                fs::write(&diff_file_path, &diff).expect("failed to write diff file");
 364                                fs::write(&last_diff_file_path, &diff).expect("failed to write last diff file");
 365                                *previous_diff.borrow_mut() = diff;
 366                            }
 367                        }
 368                        Err(err) => {
 369                            let error_message = format!("{err:?}");
 370                            fs::write(&diff_file_path, &error_message).expect("failed to write diff error to file");
 371                            fs::write(&last_diff_file_path, &error_message).expect("failed to write last diff file");
 372                        }
 373                    }
 374
 375                    if request_count == 1 {
 376                        let tools_file_path = example_output_dir.join("tools.md");
 377                        fs::write(tools_file_path, request_markdown.tools).expect("failed to write tools file");
 378                    }
 379                });
 380            })?;
 381
 382            let tool_metrics = Arc::new(Mutex::new(ToolMetrics::default()));
 383
 384            let (thread_event_tx, mut thread_event_rx) = mpsc::unbounded();
 385
 386            let subscription = cx.subscribe(&thread, move |_thread, event: &ThreadEvent, _cx| {
 387                thread_event_tx.unbounded_send(event.clone()).log_err();
 388            });
 389
 390            let event_handler_task = cx.spawn({
 391                let log_prefix = this.log_prefix.clone();
 392                let tool_metrics = tool_metrics.clone();
 393                let thread = thread.downgrade();
 394                async move |cx| {
 395                    loop {
 396                        let event = select_biased! {
 397                            event = thread_event_rx.next() => event,
 398                            _ = cx.background_executor().timer(THREAD_EVENT_TIMEOUT).fuse() => {
 399                                return Err(anyhow!("Agentic loop stalled - waited {:?} without any events", THREAD_EVENT_TIMEOUT));
 400                            }
 401                        };
 402                        let Some(event) = event else {
 403                            return Err(anyhow!("ThreadEvent channel ended early"));
 404                        };
 405
 406                        match event {
 407                            ThreadEvent::Stopped(reason) => match reason {
 408                                Ok(StopReason::EndTurn) => {
 409                                    return Ok(());
 410                                }
 411                                Ok(StopReason::MaxTokens) => {
 412                                    return Err(anyhow!("Exceeded maximum tokens"));
 413                                }
 414                                Ok(StopReason::ToolUse) => {
 415                                    if std::env::var("ZED_EVAL_DEBUG").is_ok() {
 416                                        println!("{}StopReason: Tool use", log_prefix);
 417                                    }
 418                                }
 419                                Err(error) => {
 420                                    return Err(anyhow!(error.clone()));
 421                                }
 422                            },
 423                            ThreadEvent::ShowError(thread_error) => {
 424                                break Err(anyhow!(thread_error.clone()));
 425                            }
 426                            ThreadEvent::StreamedAssistantText(_, _)| ThreadEvent::StreamedAssistantThinking(_, _) | ThreadEvent::UsePendingTools { .. } => {
 427                            }
 428                            ThreadEvent::ToolFinished {
 429                                tool_use_id,
 430                                pending_tool_use,
 431                                ..
 432                            } => {
 433                                thread.update(cx, |thread, _cx| {
 434                                    if let Some(tool_use) = pending_tool_use {
 435                                        let mut tool_metrics = tool_metrics.lock().unwrap();
 436                                        if let Some(tool_result) = thread.tool_result(&tool_use_id) {
 437                                            let message = if tool_result.is_error {
 438                                                format!("TOOL FAILED: {}", tool_use.name)
 439                                            } else {
 440                                                format!("TOOL FINISHED: {}", tool_use.name)
 441                                            };
 442                                            println!("{log_prefix}{message}");
 443                                            tool_metrics.insert(tool_result.tool_name.clone(), !tool_result.is_error);
 444                                        } else {
 445                                            let message = format!("TOOL FINISHED WITHOUT RESULT: {}", tool_use.name);
 446                                            println!("{log_prefix}{message}");
 447                                            tool_metrics.insert(tool_use.name.clone(), true);
 448                                        }
 449                                    }
 450                                })?;
 451                            }
 452                            ThreadEvent::ToolConfirmationNeeded => {
 453                                panic!("{}Bug: Tool confirmation should not be required in eval", log_prefix);
 454                            },
 455                            ThreadEvent::StreamedToolUse { .. } |
 456                            ThreadEvent::StreamedCompletion |
 457                            ThreadEvent::MessageAdded(_) |
 458                            ThreadEvent::MessageEdited(_) |
 459                            ThreadEvent::MessageDeleted(_) |
 460                            ThreadEvent::SummaryChanged |
 461                            ThreadEvent::SummaryGenerated |
 462                            ThreadEvent::CheckpointChanged |
 463                            ThreadEvent::UsageUpdated(_) => {
 464                                if std::env::var("ZED_EVAL_DEBUG").is_ok() {
 465                                    println!("{}Event: {:#?}", log_prefix, event);
 466                                }
 467                            }
 468                        }
 469                    }
 470                }
 471            });
 472
 473            thread.update(cx, |thread, cx| {
 474                let context = vec![];
 475                thread.insert_user_message(this.prompt.clone(), context, None, cx);
 476                thread.send_to_model(model, cx);
 477            })?;
 478
 479            event_handler_task.await?;
 480
 481            println!("{}Stopped", this.log_prefix);
 482
 483            if let Some((_, language_file_buffer)) = lsp.as_ref() {
 484                wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
 485            }
 486
 487            println!("{}Getting repository diff", this.log_prefix);
 488            let repository_diff = this.repository_diff().await?;
 489            std::fs::write(last_diff_file_path, &repository_diff)?;
 490
 491            println!("{}Getting diagnostics", this.log_prefix);
 492            let diagnostics_after = cx
 493                .update(move |cx| {
 494                    cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
 495                })?
 496                .await?;
 497            println!("{}Got diagnostics", this.log_prefix);
 498
 499            let Some(last_request) = last_request.borrow_mut().take() else {
 500                return Err(anyhow!("No requests ran."));
 501            };
 502
 503            drop(subscription);
 504            drop(lsp);
 505
 506            if let Some(diagnostics_before) = &diagnostics_before {
 507                fs::write(example_output_dir.join("diagnostics_before.txt"), diagnostics_before)?;
 508            }
 509
 510            if let Some(diagnostics_after) = &diagnostics_after {
 511                fs::write(example_output_dir.join("diagnostics_after.txt"), diagnostics_after)?;
 512            }
 513
 514
 515            thread.update(cx, |thread, _cx| {
 516                let response_count = thread
 517                    .messages()
 518                    .filter(|message| message.role == language_model::Role::Assistant)
 519                    .count();
 520                RunOutput {
 521                    repository_diff,
 522                    ran_diagnostics_check: this.base.require_lsp,
 523                    diagnostics_before,
 524                    diagnostics_after,
 525                    response_count,
 526                    token_usage: thread.cumulative_token_usage(),
 527                    tool_metrics: tool_metrics.lock().unwrap().clone(),
 528                    last_request,
 529                }
 530            })
 531        })
 532    }
 533
 534    async fn judge_diff(
 535        &self,
 536        model: Arc<dyn LanguageModel>,
 537        run_output: &RunOutput,
 538        judge_number: u32,
 539        cx: &AsyncApp,
 540    ) -> Result<(String, JudgeResponse)> {
 541        let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
 542        let judge_diff_prompt_name = "judge_diff_prompt";
 543        let mut hbs = Handlebars::new();
 544        hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)?;
 545
 546        let diff_prompt = hbs.render(
 547            judge_diff_prompt_name,
 548            &JudgeDiffInput {
 549                repository_diff: run_output.repository_diff.clone(),
 550                ran_diagnostics_check: run_output.ran_diagnostics_check,
 551                diagnostics_before: run_output.diagnostics_before.clone(),
 552                diagnostics_after: run_output.diagnostics_after.clone(),
 553                criteria: self.diff_criteria.clone(),
 554            },
 555        )?;
 556
 557        let request = LanguageModelRequest {
 558            thread_id: None,
 559            prompt_id: None,
 560            messages: vec![LanguageModelRequestMessage {
 561                role: Role::User,
 562                content: vec![MessageContent::Text(diff_prompt)],
 563                cache: false,
 564            }],
 565            temperature: None,
 566            tools: Vec::new(),
 567            stop: Vec::new(),
 568        };
 569
 570        let diff_response = send_language_model_request(model, request, cx).await?;
 571        let diff_output = JudgeResponse::parse(&diff_response)?;
 572
 573        println!(
 574            "{}Judge #{judge_number} - Diff score: {}",
 575            self.log_prefix, diff_output.score
 576        );
 577
 578        Ok((diff_response, diff_output))
 579    }
 580
 581    async fn judge_thread(
 582        &self,
 583        model: Arc<dyn LanguageModel>,
 584        run_output: &RunOutput,
 585        judge_number: u32,
 586        cx: &AsyncApp,
 587    ) -> Result<(String, Option<JudgeResponse>)> {
 588        if let Some(criteria) = self.thread_criteria.clone() {
 589            let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
 590            let judge_thread_prompt_name = "judge_thread_prompt";
 591            let mut hbs = Handlebars::new();
 592            hbs.register_template_string(judge_thread_prompt_name, judge_thread_prompt)?;
 593
 594            let request_markdown = RequestMarkdown::new(&run_output.last_request);
 595            let thread_prompt = hbs.render(
 596                judge_thread_prompt_name,
 597                &JudgeThreadInput {
 598                    messages: request_markdown.messages,
 599                    criteria,
 600                },
 601            )?;
 602
 603            let request = LanguageModelRequest {
 604                thread_id: None,
 605                prompt_id: None,
 606                messages: vec![LanguageModelRequestMessage {
 607                    role: Role::User,
 608                    content: vec![MessageContent::Text(thread_prompt)],
 609                    cache: false,
 610                }],
 611                temperature: None,
 612                tools: Vec::new(),
 613                stop: Vec::new(),
 614            };
 615
 616            let thread_response = send_language_model_request(model, request, cx).await?;
 617            let thread_output = JudgeResponse::parse(&thread_response)?;
 618
 619            println!(
 620                "{}Judge #{judge_number} - Thread score: {}",
 621                self.log_prefix, thread_output.score
 622            );
 623
 624            Ok((thread_response, Some(thread_output)))
 625        } else {
 626            let msg = "There were no criteria specified for this thread, so this example was not judged on its thread.".to_string();
 627            Ok((msg, None))
 628        }
 629    }
 630
 631    pub async fn judge(
 632        &self,
 633        model: Arc<dyn LanguageModel>,
 634        run_output: &RunOutput,
 635        judge_number: u32,
 636        cx: &AsyncApp,
 637    ) -> Result<JudgeOutput> {
 638        let mut output_file = File::create(
 639            self.example_output_directory()
 640                .join(format!("judge_{}.md", judge_number)),
 641        )
 642        .expect("failed to create judge.md");
 643
 644        println!("{}Running judge #{judge_number}", self.log_prefix);
 645
 646        let diff_task = self.judge_diff(model.clone(), &run_output, judge_number, cx);
 647        let thread_task = self.judge_thread(model.clone(), &run_output, judge_number, cx);
 648
 649        let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
 650
 651        let (diff_response, diff_output) = diff_result?;
 652        let (thread_response, thread_output) = thread_result?;
 653
 654        writeln!(
 655            &mut output_file,
 656            "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
 657        )
 658        .log_err();
 659
 660        Ok(JudgeOutput {
 661            thread: thread_output,
 662            diff: diff_output,
 663        })
 664    }
 665
 666    async fn repository_diff(&self) -> Result<String> {
 667        let worktree_path = self.worktree_path();
 668        run_git(&worktree_path, &["add", "."]).await?;
 669        let mut diff_args = vec!["diff", "--staged"];
 670        if self.base.url == ZED_REPO_URL {
 671            diff_args.push(":(exclude).rules");
 672        }
 673        run_git(&worktree_path, &diff_args).await
 674    }
 675}
 676
 677fn wait_for_lang_server(
 678    project: &Entity<Project>,
 679    buffer: &Entity<Buffer>,
 680    log_prefix: String,
 681    cx: &mut AsyncApp,
 682) -> Task<Result<()>> {
 683    println!("{}⏵ Waiting for language server", log_prefix);
 684
 685    let (mut tx, mut rx) = mpsc::channel(1);
 686
 687    let lsp_store = project
 688        .update(cx, |project, _| project.lsp_store())
 689        .unwrap();
 690
 691    let has_lang_server = buffer
 692        .update(cx, |buffer, cx| {
 693            lsp_store.update(cx, |lsp_store, cx| {
 694                lsp_store
 695                    .language_servers_for_local_buffer(&buffer, cx)
 696                    .next()
 697                    .is_some()
 698            })
 699        })
 700        .unwrap_or(false);
 701
 702    if has_lang_server {
 703        project
 704            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
 705            .unwrap()
 706            .detach();
 707    }
 708
 709    let subscriptions =
 710        [
 711            cx.subscribe(&lsp_store, {
 712                let log_prefix = log_prefix.clone();
 713                move |_, event, _| match event {
 714                    project::LspStoreEvent::LanguageServerUpdate {
 715                        message:
 716                            client::proto::update_language_server::Variant::WorkProgress(
 717                                LspWorkProgress {
 718                                    message: Some(message),
 719                                    ..
 720                                },
 721                            ),
 722                        ..
 723                    } => println!("{}{message}", log_prefix),
 724                    _ => {}
 725                }
 726            }),
 727            cx.subscribe(&project, {
 728                let buffer = buffer.clone();
 729                move |project, event, cx| match event {
 730                    project::Event::LanguageServerAdded(_, _, _) => {
 731                        let buffer = buffer.clone();
 732                        project
 733                            .update(cx, |project, cx| project.save_buffer(buffer, cx))
 734                            .detach();
 735                    }
 736                    project::Event::DiskBasedDiagnosticsFinished { .. } => {
 737                        tx.try_send(()).ok();
 738                    }
 739                    _ => {}
 740                }
 741            }),
 742        ];
 743
 744    cx.spawn(async move |cx| {
 745        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
 746        let result = futures::select! {
 747            _ = rx.next() => {
 748                println!("{}⚑ Language server idle", log_prefix);
 749                anyhow::Ok(())
 750            },
 751            _ = timeout.fuse() => {
 752                Err(anyhow!("LSP wait timed out after 5 minutes"))
 753            }
 754        };
 755        drop(subscriptions);
 756        result
 757    })
 758}
 759
 760async fn query_lsp_diagnostics(
 761    project: Entity<Project>,
 762    cx: &mut AsyncApp,
 763) -> Result<Option<String>> {
 764    let paths_with_diagnostics = project.update(cx, |project, cx| {
 765        project
 766            .diagnostic_summaries(true, cx)
 767            .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
 768            .map(|(project_path, _, _)| project_path)
 769            .collect::<Vec<_>>()
 770    })?;
 771
 772    if paths_with_diagnostics.is_empty() {
 773        return Ok(None);
 774    }
 775
 776    let mut output = String::new();
 777    for project_path in paths_with_diagnostics {
 778        let buffer = project
 779            .update(cx, |project, cx| project.open_buffer(project_path, cx))?
 780            .await?;
 781        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 782
 783        for (_, group) in snapshot.diagnostic_groups(None) {
 784            let entry = &group.entries[group.primary_ix];
 785            let range = entry.range.to_point(&snapshot);
 786            let severity = match entry.diagnostic.severity {
 787                DiagnosticSeverity::ERROR => "error",
 788                DiagnosticSeverity::WARNING => "warning",
 789                _ => continue,
 790            };
 791
 792            writeln!(
 793                output,
 794                "{} at line {}: {}",
 795                severity,
 796                range.start.row + 1,
 797                entry.diagnostic.message
 798            )?;
 799        }
 800    }
 801    anyhow::Ok(Some(output))
 802}
 803
 804impl JudgeResponse {
 805    fn parse(response: &str) -> Result<Self> {
 806        let analysis = get_tag("analysis", response)?.to_string();
 807        let score = get_tag("score", response)?
 808            .parse()
 809            .context("error parsing score")?;
 810
 811        Ok(Self { analysis, score })
 812    }
 813}
 814
 815fn get_tag(name: &'static str, response: &str) -> Result<String> {
 816    let start_tag = format!("<{}>", name);
 817    let end_tag = format!("</{}>", name);
 818
 819    let start_ix = response
 820        .find(&start_tag)
 821        .context(format!("{} start tag not found", name))?;
 822    let content_start_ix = start_ix + start_tag.len();
 823
 824    let end_ix = content_start_ix
 825        + response[content_start_ix..]
 826            .find(&end_tag)
 827            .context(format!("{} end tag not found", name))?;
 828
 829    let content = response[content_start_ix..end_ix].trim().unindent();
 830
 831    anyhow::Ok(content)
 832}
 833
 834pub fn repo_path_for_url(repo_url: &str) -> PathBuf {
 835    let repo_name = repo_url
 836        .trim_start_matches("https://")
 837        .replace(|c: char| !c.is_alphanumeric(), "-");
 838    Path::new(REPOS_DIR)
 839        .canonicalize()
 840        .context(format!("No such directory {REPOS_DIR}"))
 841        .unwrap()
 842        .join(repo_name)
 843}
 844
 845pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
 846    let output = new_smol_command("git")
 847        .current_dir(repo_path)
 848        .args(args)
 849        .output()
 850        .await?;
 851
 852    if output.status.success() {
 853        Ok(String::from_utf8(output.stdout)?.trim().to_string())
 854    } else {
 855        Err(anyhow!(
 856            "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
 857            args.join(" "),
 858            repo_path.display(),
 859            output.status,
 860            String::from_utf8_lossy(&output.stderr),
 861            String::from_utf8_lossy(&output.stdout),
 862        ))
 863    }
 864}
 865
 866pub async fn send_language_model_request(
 867    model: Arc<dyn LanguageModel>,
 868    request: LanguageModelRequest,
 869    cx: &AsyncApp,
 870) -> anyhow::Result<String> {
 871    match model.stream_completion_text(request, &cx).await {
 872        Ok(mut stream) => {
 873            let mut full_response = String::new();
 874            while let Some(chunk_result) = stream.stream.next().await {
 875                match chunk_result {
 876                    Ok(chunk_str) => {
 877                        full_response.push_str(&chunk_str);
 878                    }
 879                    Err(err) => {
 880                        return Err(anyhow!(
 881                            "Error receiving response from language model: {err}"
 882                        ));
 883                    }
 884                }
 885            }
 886            Ok(full_response)
 887        }
 888        Err(err) => Err(anyhow!(
 889            "Failed to get response from language model. Error was: {err}"
 890        )),
 891    }
 892}
 893
 894struct RequestMarkdown {
 895    tools: String,
 896    messages: String,
 897}
 898
 899impl RequestMarkdown {
 900    fn new(request: &LanguageModelRequest) -> Self {
 901        let mut tools = String::new();
 902        let mut messages = String::new();
 903        let mut assistant_message_number: u32 = 1;
 904
 905        // Print the tools
 906        if !request.tools.is_empty() {
 907            for tool in &request.tools {
 908                write!(&mut tools, "# {}\n\n", tool.name).unwrap();
 909                write!(&mut tools, "{}\n\n", tool.description).unwrap();
 910                write!(
 911                    &mut tools,
 912                    "{}\n",
 913                    MarkdownString::code_block("json", &format!("{:#}", tool.input_schema))
 914                )
 915                .unwrap();
 916            }
 917        }
 918
 919        // Print the messages
 920        for message in &request.messages {
 921            match message.role {
 922                Role::System => messages.push_str("# ⚙️ SYSTEM\n\n"),
 923                Role::User => messages.push_str("# 👤 USER\n\n"),
 924                Role::Assistant => {
 925                    messages.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
 926                    assistant_message_number += 1;
 927                }
 928            };
 929
 930            for content in &message.content {
 931                match content {
 932                    MessageContent::Text(text) => {
 933                        messages.push_str(text);
 934                        messages.push_str("\n\n");
 935                    }
 936                    MessageContent::Image(_) => {
 937                        messages.push_str("[IMAGE DATA]\n\n");
 938                    }
 939                    MessageContent::Thinking { text, signature } => {
 940                        messages.push_str("**Thinking**:\n\n");
 941                        if let Some(sig) = signature {
 942                            messages.push_str(&format!("Signature: {}\n\n", sig));
 943                        }
 944                        messages.push_str(text);
 945                        messages.push_str("\n");
 946                    }
 947                    MessageContent::RedactedThinking(items) => {
 948                        messages.push_str(&format!(
 949                            "**Redacted Thinking**: {} item(s)\n\n",
 950                            items.len()
 951                        ));
 952                    }
 953                    MessageContent::ToolUse(tool_use) => {
 954                        messages.push_str(&format!(
 955                            "**Tool Use**: {} (ID: {})\n",
 956                            tool_use.name, tool_use.id
 957                        ));
 958                        messages.push_str(&format!(
 959                            "{}\n",
 960                            MarkdownString::code_block("json", &format!("{:#}", tool_use.input))
 961                        ));
 962                    }
 963                    MessageContent::ToolResult(tool_result) => {
 964                        messages.push_str(&format!(
 965                            "**Tool Result**: {} (ID: {})\n\n",
 966                            tool_result.tool_name, tool_result.tool_use_id
 967                        ));
 968                        if tool_result.is_error {
 969                            messages.push_str("**ERROR:**\n");
 970                        }
 971                        messages.push_str(&format!("{}\n\n", tool_result.content));
 972                    }
 973                }
 974            }
 975        }
 976
 977        Self { tools, messages }
 978    }
 979}
 980
 981fn response_events_to_markdown(
 982    response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
 983) -> String {
 984    let mut response = String::new();
 985    // Print the response events if any
 986    response.push_str("# Response\n\n");
 987    let mut text_buffer = String::new();
 988    let mut thinking_buffer = String::new();
 989
 990    let flush_buffers =
 991        |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
 992            if !text_buffer.is_empty() {
 993                output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
 994                text_buffer.clear();
 995            }
 996            if !thinking_buffer.is_empty() {
 997                output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
 998                thinking_buffer.clear();
 999            }
1000        };
1001
1002    for event in response_events {
1003        match event {
1004            Ok(LanguageModelCompletionEvent::Text(text)) => {
1005                text_buffer.push_str(text);
1006            }
1007            Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
1008                thinking_buffer.push_str(text);
1009            }
1010            Ok(LanguageModelCompletionEvent::Stop(reason)) => {
1011                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1012                response.push_str(&format!("**Stop**: {:?}\n\n", reason));
1013            }
1014            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1015                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1016                response.push_str(&format!(
1017                    "**Tool Use**: {} (ID: {})\n",
1018                    tool_use.name, tool_use.id
1019                ));
1020                response.push_str(&format!(
1021                    "{}\n",
1022                    MarkdownString::code_block("json", &format!("{:#}", tool_use.input))
1023                ));
1024            }
1025            Ok(
1026                LanguageModelCompletionEvent::UsageUpdate(_)
1027                | LanguageModelCompletionEvent::StartMessage { .. },
1028            ) => {}
1029            Err(error) => {
1030                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1031                response.push_str(&format!("**Error**: {}\n\n", error));
1032            }
1033        }
1034    }
1035
1036    flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1037
1038    response
1039}
1040
1041#[cfg(test)]
1042mod test {
1043    use super::*;
1044    use handlebars::Handlebars;
1045
1046    #[test]
1047    fn test_parse_judge_output() {
1048        let response = r#"
1049            <analysis>The model did a good job but there were still compilations errors.</analysis>
1050            <score>3</score>
1051        "#
1052        .unindent();
1053
1054        let output = JudgeResponse::parse(&response).unwrap();
1055        assert_eq!(
1056            output.analysis,
1057            "The model did a good job but there were still compilations errors."
1058        );
1059        assert_eq!(output.score, 3);
1060
1061        let response = r#"
1062            Text around ignored
1063
1064            <analysis>
1065                Failed to compile:
1066                - Error 1
1067                - Error 2
1068            </analysis>
1069
1070            <score>1</score>
1071        "#
1072        .unindent();
1073
1074        let output = JudgeResponse::parse(&response).unwrap();
1075        assert_eq!(output.analysis, "Failed to compile:\n- Error 1\n- Error 2");
1076        assert_eq!(output.score, 1);
1077    }
1078
1079    #[test]
1080    fn test_judge_prompt_with_diagnostics() {
1081        // Case 1: Both diagnostics before and after are present
1082        let input = JudgeDiffInput {
1083            repository_diff: "diff content goes here".to_string(),
1084            ran_diagnostics_check: true,
1085            diagnostics_before: Some("Error at line 10: variable not found".to_string()),
1086            diagnostics_after: Some("Error at line 15: missing semicolon".to_string()),
1087            criteria: "Fix all bugs".to_string(),
1088        };
1089
1090        let rendered = templates().render(JUDGE_PROMPT_NAME, &input).unwrap();
1091
1092        let expected_diagnostics_section = r#"
1093            Take into account the diagnostics before and after applying the change:
1094
1095            <diagnostics_before>
1096            Error at line 10: variable not found
1097            </diagnostics_before>
1098
1099            <diagnostics_after>
1100            Error at line 15: missing semicolon
1101            </diagnostics_after>
1102            "#
1103        .unindent();
1104
1105        assert!(rendered.contains(&expected_diagnostics_section));
1106    }
1107
1108    #[test]
1109    fn test_judge_prompt_with_empty_diagnostics() {
1110        // Case 2: Diagnostics check run but no diagnostics found
1111        let input = JudgeDiffInput {
1112            repository_diff: "diff content goes here".to_string(),
1113            ran_diagnostics_check: true,
1114            diagnostics_before: None,
1115            diagnostics_after: None,
1116            criteria: "Fix all bugs".to_string(),
1117        };
1118
1119        let rendered = templates().render(JUDGE_PROMPT_NAME, &input).unwrap();
1120
1121        let expected_diagnostics_section = r#"
1122            Take into account the diagnostics before and after applying the change:
1123
1124            <diagnostics_before>
1125            No diagnostics before applying the edits.
1126            </diagnostics_before>
1127
1128            <diagnostics_after>
1129            No diagnostics after applying the edits.
1130            </diagnostics_after>
1131            "#
1132        .unindent();
1133
1134        assert!(rendered.contains(&expected_diagnostics_section));
1135    }
1136
1137    #[test]
1138    fn test_judge_prompt_with_mixed_diagnostics() {
1139        let templates = templates();
1140
1141        // Case 3: Before diagnostics present, after diagnostics absent
1142        let input = JudgeDiffInput {
1143            repository_diff: "diff content goes here".to_string(),
1144            ran_diagnostics_check: true,
1145            diagnostics_before: Some("Error at line 10: variable not found".to_string()),
1146            diagnostics_after: None,
1147            criteria: "Fix all bugs".to_string(),
1148        };
1149
1150        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1151
1152        let expected_diagnostics_section = r#"
1153            Take into account the diagnostics before and after applying the change:
1154
1155            <diagnostics_before>
1156            Error at line 10: variable not found
1157            </diagnostics_before>
1158
1159            <diagnostics_after>
1160            No diagnostics after applying the edits.
1161            </diagnostics_after>
1162            "#
1163        .unindent();
1164
1165        assert!(rendered.contains(&expected_diagnostics_section));
1166
1167        // Case 4: Before diagnostics absent, after diagnostics present
1168        let input = JudgeDiffInput {
1169            repository_diff: "diff content goes here".to_string(),
1170            ran_diagnostics_check: true,
1171            diagnostics_before: None,
1172            diagnostics_after: Some("Error at line 15: missing semicolon".to_string()),
1173            criteria: "Fix all bugs".to_string(),
1174        };
1175
1176        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1177
1178        let expected_diagnostics_section = r#"
1179            Take into account the diagnostics before and after applying the change:
1180
1181            <diagnostics_before>
1182            No diagnostics before applying the edits.
1183            </diagnostics_before>
1184
1185            <diagnostics_after>
1186            Error at line 15: missing semicolon
1187            </diagnostics_after>
1188            "#
1189        .unindent();
1190
1191        assert!(rendered.contains(&expected_diagnostics_section));
1192    }
1193
1194    #[test]
1195    fn test_judge_prompt_without_diagnostics() {
1196        let templates = templates();
1197
1198        // Case 5: No diagnostics check run
1199        let input = JudgeDiffInput {
1200            repository_diff: "diff content goes here".to_string(),
1201            ran_diagnostics_check: false,
1202            diagnostics_before: None,
1203            diagnostics_after: None,
1204            criteria: "Fix all bugs".to_string(),
1205        };
1206
1207        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1208
1209        // Check for the message when no diagnostics were performed
1210        let diagnostics_message = "No diagnostic checks were performed.";
1211
1212        assert!(rendered.contains(diagnostics_message));
1213        assert!(!rendered.contains("<diagnostics_before>"));
1214        assert!(!rendered.contains("<diagnostics_after>"));
1215    }
1216
1217    const JUDGE_PROMPT_NAME: &str = "judge_prompt";
1218
1219    fn templates() -> Handlebars<'static> {
1220        let mut judge_prompt = include_str!("judge_diff_prompt.hbs").to_string();
1221        language::LineEnding::normalize(&mut judge_prompt);
1222        let mut handlebars = Handlebars::new();
1223        handlebars
1224            .register_template_string(JUDGE_PROMPT_NAME, judge_prompt)
1225            .unwrap();
1226        handlebars
1227    }
1228}