example.rs

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