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::StreamedToolUse { .. } |
 452                            ThreadEvent::StreamedCompletion |
 453                            ThreadEvent::MessageAdded(_) |
 454                            ThreadEvent::MessageEdited(_) |
 455                            ThreadEvent::MessageDeleted(_) |
 456                            ThreadEvent::SummaryChanged |
 457                            ThreadEvent::SummaryGenerated |
 458                            ThreadEvent::CheckpointChanged |
 459                            ThreadEvent::UsageUpdated(_) => {
 460                                if std::env::var("ZED_EVAL_DEBUG").is_ok() {
 461                                    println!("{}Event: {:#?}", log_prefix, event);
 462                                }
 463                            }
 464                        }
 465                    }
 466                }
 467            });
 468
 469            thread.update(cx, |thread, cx| {
 470                let context = vec![];
 471                thread.insert_user_message(this.prompt.clone(), context, None, cx);
 472                thread.send_to_model(model, cx);
 473            })?;
 474
 475            event_handler_task.await?;
 476
 477            println!("{}Stopped", this.log_prefix);
 478
 479            if let Some((_, lsp_store)) = lsp_open_handle_and_store.as_ref() {
 480                wait_for_lang_server(lsp_store, this.log_prefix.clone(), cx).await?;
 481            }
 482
 483            println!("{}Getting repository diff", this.log_prefix);
 484            let repository_diff = this.repository_diff().await?;
 485
 486            let example_output_dir = this.example_output_directory();
 487            let repository_diff_path = example_output_dir.join("patch.diff");
 488            let mut repository_diff_output_file = File::create(&repository_diff_path)?;
 489            writeln!(&mut repository_diff_output_file, "{}", &repository_diff).log_err();
 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_open_handle_and_store);
 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_use_counts: tool_use_counts.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        run_git(&worktree_path, &["diff", "--staged"]).await
 670    }
 671}
 672
 673fn wait_for_lang_server(
 674    lsp_store: &Entity<LspStore>,
 675    log_prefix: String,
 676    cx: &mut AsyncApp,
 677) -> Task<Result<()>> {
 678    if cx
 679        .update(|cx| !has_pending_lang_server_work(lsp_store, cx))
 680        .unwrap()
 681        || std::env::var("ZED_EVAL_SKIP_LS_WAIT").is_ok()
 682    {
 683        return Task::ready(anyhow::Ok(()));
 684    }
 685
 686    println!("{}⏵ Waiting for language server", log_prefix);
 687
 688    let (mut tx, mut rx) = mpsc::channel(1);
 689
 690    let subscription =
 691        cx.subscribe(&lsp_store, {
 692            let log_prefix = log_prefix.clone();
 693            move |lsp_store, event, cx| {
 694                match event {
 695                    project::LspStoreEvent::LanguageServerUpdate {
 696                        message:
 697                            client::proto::update_language_server::Variant::WorkProgress(
 698                                LspWorkProgress {
 699                                    message: Some(message),
 700                                    ..
 701                                },
 702                            ),
 703                        ..
 704                    } => println!("{}{message}", log_prefix),
 705                    _ => {}
 706                }
 707
 708                if !has_pending_lang_server_work(&lsp_store, cx) {
 709                    tx.try_send(()).ok();
 710                }
 711            }
 712        });
 713
 714    cx.spawn(async move |cx| {
 715        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
 716        let result = futures::select! {
 717            _ = rx.next() => {
 718                println!("{}⚑ Language server idle", log_prefix);
 719                anyhow::Ok(())
 720            },
 721            _ = timeout.fuse() => {
 722                Err(anyhow!("LSP wait timed out after 5 minutes"))
 723            }
 724        };
 725        drop(subscription);
 726        result
 727    })
 728}
 729
 730fn has_pending_lang_server_work(lsp_store: &Entity<LspStore>, cx: &App) -> bool {
 731    lsp_store
 732        .read(cx)
 733        .language_server_statuses()
 734        .any(|(_, status)| !status.pending_work.is_empty())
 735}
 736
 737async fn query_lsp_diagnostics(
 738    project: Entity<Project>,
 739    cx: &mut AsyncApp,
 740) -> Result<Option<String>> {
 741    let paths_with_diagnostics = project.update(cx, |project, cx| {
 742        project
 743            .diagnostic_summaries(true, cx)
 744            .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
 745            .map(|(project_path, _, _)| project_path)
 746            .collect::<Vec<_>>()
 747    })?;
 748
 749    if paths_with_diagnostics.is_empty() {
 750        return Ok(None);
 751    }
 752
 753    let mut output = String::new();
 754    for project_path in paths_with_diagnostics {
 755        let buffer = project
 756            .update(cx, |project, cx| project.open_buffer(project_path, cx))?
 757            .await?;
 758        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 759
 760        for (_, group) in snapshot.diagnostic_groups(None) {
 761            let entry = &group.entries[group.primary_ix];
 762            let range = entry.range.to_point(&snapshot);
 763            let severity = match entry.diagnostic.severity {
 764                DiagnosticSeverity::ERROR => "error",
 765                DiagnosticSeverity::WARNING => "warning",
 766                _ => continue,
 767            };
 768
 769            writeln!(
 770                output,
 771                "{} at line {}: {}",
 772                severity,
 773                range.start.row + 1,
 774                entry.diagnostic.message
 775            )?;
 776        }
 777    }
 778    anyhow::Ok(Some(output))
 779}
 780
 781impl JudgeResponse {
 782    fn parse(response: &str) -> Result<Self> {
 783        let analysis = get_tag("analysis", response)?.to_string();
 784        let score = get_tag("score", response)?
 785            .parse()
 786            .context("error parsing score")?;
 787
 788        Ok(Self { analysis, score })
 789    }
 790}
 791
 792fn get_tag(name: &'static str, response: &str) -> Result<String> {
 793    let start_tag = format!("<{}>", name);
 794    let end_tag = format!("</{}>", name);
 795
 796    let start_ix = response
 797        .find(&start_tag)
 798        .context(format!("{} start tag not found", name))?;
 799    let content_start_ix = start_ix + start_tag.len();
 800
 801    let end_ix = content_start_ix
 802        + response[content_start_ix..]
 803            .find(&end_tag)
 804            .context(format!("{} end tag not found", name))?;
 805
 806    let content = response[content_start_ix..end_ix].trim().unindent();
 807
 808    anyhow::Ok(content)
 809}
 810
 811pub fn repo_path_for_url(repo_url: &str) -> PathBuf {
 812    let repo_name = repo_url
 813        .trim_start_matches("https://")
 814        .replace(|c: char| !c.is_alphanumeric(), "-");
 815    Path::new(REPOS_DIR)
 816        .canonicalize()
 817        .context(format!("No such directory {REPOS_DIR}"))
 818        .unwrap()
 819        .join(repo_name)
 820}
 821
 822pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
 823    let output = new_smol_command("git")
 824        .current_dir(repo_path)
 825        .args(args)
 826        .output()
 827        .await?;
 828
 829    if output.status.success() {
 830        Ok(String::from_utf8(output.stdout)?.trim().to_string())
 831    } else {
 832        Err(anyhow!(
 833            "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
 834            args.join(" "),
 835            repo_path.display(),
 836            output.status,
 837            String::from_utf8_lossy(&output.stderr),
 838            String::from_utf8_lossy(&output.stdout),
 839        ))
 840    }
 841}
 842
 843pub async fn send_language_model_request(
 844    model: Arc<dyn LanguageModel>,
 845    request: LanguageModelRequest,
 846    cx: &AsyncApp,
 847) -> anyhow::Result<String> {
 848    match model.stream_completion_text(request, &cx).await {
 849        Ok(mut stream) => {
 850            let mut full_response = String::new();
 851            while let Some(chunk_result) = stream.stream.next().await {
 852                match chunk_result {
 853                    Ok(chunk_str) => {
 854                        full_response.push_str(&chunk_str);
 855                    }
 856                    Err(err) => {
 857                        return Err(anyhow!(
 858                            "Error receiving response from language model: {err}"
 859                        ));
 860                    }
 861                }
 862            }
 863            Ok(full_response)
 864        }
 865        Err(err) => Err(anyhow!(
 866            "Failed to get response from language model. Error was: {err}"
 867        )),
 868    }
 869}
 870
 871struct RequestMarkdown {
 872    tools: String,
 873    messages: String,
 874}
 875
 876impl RequestMarkdown {
 877    fn new(request: &LanguageModelRequest) -> Self {
 878        let mut tools = String::new();
 879        let mut messages = String::new();
 880
 881        // Print the tools
 882        if !request.tools.is_empty() {
 883            for tool in &request.tools {
 884                write!(&mut tools, "# {}\n\n", tool.name).unwrap();
 885                write!(&mut tools, "{}\n\n", tool.description).unwrap();
 886                write!(
 887                    &mut tools,
 888                    "```json\n{}\n```\n\n",
 889                    serde_json::to_string_pretty(&tool.input_schema).unwrap_or_default()
 890                )
 891                .unwrap();
 892            }
 893        }
 894
 895        // Print the messages
 896        for message in &request.messages {
 897            let role_str = match message.role {
 898                Role::User => "👤 USER",
 899                Role::Assistant => "🤖 ASSISTANT",
 900                Role::System => "⚙️ SYSTEM",
 901            };
 902
 903            messages.push_str(&format!("# {}\n\n", role_str));
 904
 905            for content in &message.content {
 906                match content {
 907                    MessageContent::Text(text) => {
 908                        messages.push_str(text);
 909                        messages.push_str("\n\n");
 910                    }
 911                    MessageContent::Image(_) => {
 912                        messages.push_str("[IMAGE DATA]\n\n");
 913                    }
 914                    MessageContent::Thinking { text, signature } => {
 915                        messages.push_str("**Thinking**:\n\n");
 916                        if let Some(sig) = signature {
 917                            messages.push_str(&format!("Signature: {}\n\n", sig));
 918                        }
 919                        messages.push_str(text);
 920                        messages.push_str("\n");
 921                    }
 922                    MessageContent::RedactedThinking(items) => {
 923                        messages.push_str(&format!(
 924                            "**Redacted Thinking**: {} item(s)\n\n",
 925                            items.len()
 926                        ));
 927                    }
 928                    MessageContent::ToolUse(tool_use) => {
 929                        messages.push_str(&format!(
 930                            "**Tool Use**: {} (ID: {})\n",
 931                            tool_use.name, tool_use.id
 932                        ));
 933                        messages.push_str(&format!("```json\n{}\n```\n\n", tool_use.input));
 934                    }
 935                    MessageContent::ToolResult(tool_result) => {
 936                        messages.push_str(&format!(
 937                            "**Tool Result**: {} (ID: {})\n\n",
 938                            tool_result.tool_name, tool_result.tool_use_id
 939                        ));
 940                        if tool_result.is_error {
 941                            messages.push_str("**ERROR:**\n");
 942                        }
 943                        messages.push_str(&format!("{}\n\n", tool_result.content));
 944                    }
 945                }
 946            }
 947        }
 948
 949        Self { tools, messages }
 950    }
 951}
 952
 953fn response_events_to_markdown(
 954    response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
 955) -> String {
 956    let mut response = String::new();
 957    // Print the response events if any
 958    response.push_str("# Response\n\n");
 959    let mut text_buffer = String::new();
 960    let mut thinking_buffer = String::new();
 961
 962    let flush_buffers =
 963        |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
 964            if !text_buffer.is_empty() {
 965                output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
 966                text_buffer.clear();
 967            }
 968            if !thinking_buffer.is_empty() {
 969                output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
 970                thinking_buffer.clear();
 971            }
 972        };
 973
 974    for event in response_events {
 975        match event {
 976            Ok(LanguageModelCompletionEvent::Text(text)) => {
 977                text_buffer.push_str(text);
 978            }
 979            Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
 980                thinking_buffer.push_str(text);
 981            }
 982            Ok(LanguageModelCompletionEvent::Stop(reason)) => {
 983                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 984                response.push_str(&format!("**Stop**: {:?}\n\n", reason));
 985            }
 986            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
 987                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 988                response.push_str(&format!(
 989                    "**Tool Use**: {} (ID: {})\n",
 990                    tool_use.name, tool_use.id
 991                ));
 992                response.push_str(&format!("```json\n{}\n```\n\n", tool_use.input));
 993            }
 994            Ok(
 995                LanguageModelCompletionEvent::UsageUpdate(_)
 996                | LanguageModelCompletionEvent::StartMessage { .. },
 997            ) => {}
 998            Err(error) => {
 999                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1000                response.push_str(&format!("**Error**: {}\n\n", error));
1001            }
1002        }
1003    }
1004
1005    flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1006
1007    response
1008}
1009
1010#[cfg(test)]
1011mod test {
1012    use super::*;
1013    use handlebars::Handlebars;
1014
1015    #[test]
1016    fn test_parse_judge_output() {
1017        let response = r#"
1018            <analysis>The model did a good job but there were still compilations errors.</analysis>
1019            <score>3</score>
1020        "#
1021        .unindent();
1022
1023        let output = JudgeResponse::parse(&response).unwrap();
1024        assert_eq!(
1025            output.analysis,
1026            "The model did a good job but there were still compilations errors."
1027        );
1028        assert_eq!(output.score, 3);
1029
1030        let response = r#"
1031            Text around ignored
1032
1033            <analysis>
1034                Failed to compile:
1035                - Error 1
1036                - Error 2
1037            </analysis>
1038
1039            <score>1</score>
1040        "#
1041        .unindent();
1042
1043        let output = JudgeResponse::parse(&response).unwrap();
1044        assert_eq!(output.analysis, "Failed to compile:\n- Error 1\n- Error 2");
1045        assert_eq!(output.score, 1);
1046    }
1047
1048    #[test]
1049    fn test_judge_prompt_with_diagnostics() {
1050        // Case 1: Both diagnostics before and after are present
1051        let input = JudgeDiffInput {
1052            repository_diff: "diff content goes here".to_string(),
1053            ran_diagnostics_check: true,
1054            diagnostics_before: Some("Error at line 10: variable not found".to_string()),
1055            diagnostics_after: Some("Error at line 15: missing semicolon".to_string()),
1056            criteria: "Fix all bugs".to_string(),
1057        };
1058
1059        let rendered = templates().render(JUDGE_PROMPT_NAME, &input).unwrap();
1060
1061        let expected_diagnostics_section = r#"
1062            Take into account the diagnostics before and after applying the change:
1063
1064            <diagnostics_before>
1065            Error at line 10: variable not found
1066            </diagnostics_before>
1067
1068            <diagnostics_after>
1069            Error at line 15: missing semicolon
1070            </diagnostics_after>
1071            "#
1072        .unindent();
1073
1074        assert!(rendered.contains(&expected_diagnostics_section));
1075    }
1076
1077    #[test]
1078    fn test_judge_prompt_with_empty_diagnostics() {
1079        // Case 2: Diagnostics check run but no diagnostics found
1080        let input = JudgeDiffInput {
1081            repository_diff: "diff content goes here".to_string(),
1082            ran_diagnostics_check: true,
1083            diagnostics_before: None,
1084            diagnostics_after: None,
1085            criteria: "Fix all bugs".to_string(),
1086        };
1087
1088        let rendered = templates().render(JUDGE_PROMPT_NAME, &input).unwrap();
1089
1090        let expected_diagnostics_section = r#"
1091            Take into account the diagnostics before and after applying the change:
1092
1093            <diagnostics_before>
1094            No diagnostics before applying the edits.
1095            </diagnostics_before>
1096
1097            <diagnostics_after>
1098            No diagnostics after applying the edits.
1099            </diagnostics_after>
1100            "#
1101        .unindent();
1102
1103        assert!(rendered.contains(&expected_diagnostics_section));
1104    }
1105
1106    #[test]
1107    fn test_judge_prompt_with_mixed_diagnostics() {
1108        let templates = templates();
1109
1110        // Case 3: Before diagnostics present, after diagnostics absent
1111        let input = JudgeDiffInput {
1112            repository_diff: "diff content goes here".to_string(),
1113            ran_diagnostics_check: true,
1114            diagnostics_before: Some("Error at line 10: variable not found".to_string()),
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            Error at line 10: variable not found
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        // Case 4: Before diagnostics absent, after diagnostics present
1137        let input = JudgeDiffInput {
1138            repository_diff: "diff content goes here".to_string(),
1139            ran_diagnostics_check: true,
1140            diagnostics_before: None,
1141            diagnostics_after: Some("Error at line 15: missing semicolon".to_string()),
1142            criteria: "Fix all bugs".to_string(),
1143        };
1144
1145        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1146
1147        let expected_diagnostics_section = r#"
1148            Take into account the diagnostics before and after applying the change:
1149
1150            <diagnostics_before>
1151            No diagnostics before applying the edits.
1152            </diagnostics_before>
1153
1154            <diagnostics_after>
1155            Error at line 15: missing semicolon
1156            </diagnostics_after>
1157            "#
1158        .unindent();
1159
1160        assert!(rendered.contains(&expected_diagnostics_section));
1161    }
1162
1163    #[test]
1164    fn test_judge_prompt_without_diagnostics() {
1165        let templates = templates();
1166
1167        // Case 5: No diagnostics check run
1168        let input = JudgeDiffInput {
1169            repository_diff: "diff content goes here".to_string(),
1170            ran_diagnostics_check: false,
1171            diagnostics_before: None,
1172            diagnostics_after: None,
1173            criteria: "Fix all bugs".to_string(),
1174        };
1175
1176        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1177
1178        // Check for the message when no diagnostics were performed
1179        let diagnostics_message = "No diagnostic checks were performed.";
1180
1181        assert!(rendered.contains(diagnostics_message));
1182        assert!(!rendered.contains("<diagnostics_before>"));
1183        assert!(!rendered.contains("<diagnostics_after>"));
1184    }
1185
1186    const JUDGE_PROMPT_NAME: &str = "judge_prompt";
1187
1188    fn templates() -> Handlebars<'static> {
1189        let mut judge_prompt = include_str!("judge_diff_prompt.hbs").to_string();
1190        language::LineEnding::normalize(&mut judge_prompt);
1191        let mut handlebars = Handlebars::new();
1192        handlebars
1193            .register_template_string(JUDGE_PROMPT_NAME, judge_prompt)
1194            .unwrap();
1195        handlebars
1196    }
1197}