A platform for community discussion. Free, open, simple.
FEATURE: improve GitHub tool output for AI (#38250)
Sam8ae1c094f5d4
diff --git a/plugins/discourse-ai/lib/personas/bot.rb b/plugins/discourse-ai/lib/personas/bot.rbindex 62739c427f7..2fa76c81360 100644--- a/plugins/discourse-ai/lib/personas/bot.rb+++ b/plugins/discourse-ai/lib/personas/bot.rb@@ -6,10 +6,10 @@ module DiscourseAiBOT_NOT_FOUND = Class.new(StandardError)# the future is agentic, allow for more turns- MAX_COMPLETIONS = 8+ MAX_COMPLETIONS = 12# limit is arbitrary, but 5 which was used in the past was too low- MAX_TOOLS = 20+ MAX_TOOLS = 30def self.as(bot_user, persona: DiscourseAi::Personas::General.new, model: nil)new(bot_user, persona, model)diff --git a/plugins/discourse-ai/lib/personas/tools/github_file_content.rb b/plugins/discourse-ai/lib/personas/tools/github_file_content.rbindex 8a35da827ee..02c4004a2dd 100644--- a/plugins/discourse-ai/lib/personas/tools/github_file_content.rb+++ b/plugins/discourse-ai/lib/personas/tools/github_file_content.rb@@ -173,13 +173,24 @@ module DiscourseAi/#L(\d+)(?:-L?(\d+))?\z/iend- def extract_requested_content(content, start_line, end_line)- return content if start_line.nil?+ MAX_LINES = 200+ def extract_requested_content(content, start_line, end_line)normalized = content.gsub("\r\n", "\n")lines = normalized.split("\n")total_lines = lines.length+ if start_line.nil?+ if total_lines <= MAX_LINES+ return normalized+ else+ extracted = lines[0...MAX_LINES].join("\n")+ return(+ "#{extracted}\n\n[truncated — file has #{total_lines} lines, showing first #{MAX_LINES}. Use file_path#L#{MAX_LINES + 1}-L#{MAX_LINES + 200} to read more]"+ )+ end+ end+if start_line > total_linesreturn("Requested lines #{start_line}-#{end_line || start_line} exceed file length of #{total_lines}."@@ -188,7 +199,14 @@ module DiscourseAifinal_end_line = [end_line || start_line, total_lines].minextracted = lines[(start_line - 1)..(final_end_line - 1)] || []- extracted.join("\n")+ result = extracted.join("\n")++ if final_end_line < total_lines+ result +=+ "\n\n[showing lines #{start_line}-#{final_end_line} of #{total_lines}. Use file_path#L#{final_end_line + 1}-L#{[final_end_line + 200, total_lines].min} to read more]"+ end++ resultenddef format_line_range(start_line, end_line)diff --git a/plugins/discourse-ai/lib/personas/tools/github_search_code.rb b/plugins/discourse-ai/lib/personas/tools/github_search_code.rbindex b4f9851e107..cbee46ed3a1 100644--- a/plugins/discourse-ai/lib/personas/tools/github_search_code.rb+++ b/plugins/discourse-ai/lib/personas/tools/github_search_code.rb@@ -34,6 +34,14 @@ module DiscourseAitype: "integer",required: false,},+ {+ name: "ignore_paths",+ description:+ "File path prefixes to exclude from results (e.g., ['config/locales/', 'spec/'])",+ type: "array",+ item_type: "string",+ required: false,+ },],}end@@ -56,6 +64,10 @@ module DiscourseAi[requested, MAX_ALLOWED_PAGE].minend+ def ignore_paths+ Array(parameters[:ignore_paths]).map(&:to_s)+ end+def description_args{ repo: repo, query: query, page: page }end@@ -84,7 +96,9 @@ module DiscourseAiendif response_code == "200"- formatted_results = trim_results(format_results(search_data["items"]))+ formatted_results = format_results(search_data["items"])+ grouped = group_by_file(formatted_results)+ trimmed = trim_results(grouped)total_count = search_data["total_count"].to_itotal_pages =@@ -94,19 +108,11 @@ module DiscourseAi[((total_count.to_f / PER_PAGE).ceil), MAX_ALLOWED_PAGE].minend- result = {- search_results: formatted_results,- pagination: {- current_page: page,- per_page: PER_PAGE,- total_count: total_count,- total_pages: total_pages,- has_next_page: page < total_pages,- next_page: page < total_pages ? page + 1 : nil,- has_previous_page: page > 1,- previous_page: page > 1 ? page - 1 : nil,- },- }+ result = { search_results: trimmed }++ result[:page] = page if page > 1+ result[:total_results] = total_count+ result[:next_page] = page + 1 if page < total_pagesif search_data["incomplete_results"]result[:notes] = "GitHub marked the search results as incomplete."@@ -127,24 +133,40 @@ module DiscourseAi"https://api.github.com/search/code?#{encoded_params}"end+ # Cap blob fetches to avoid excessive API calls for line-number enrichment.+ # Files beyond this limit still appear in results but without line numbers.+ MAX_BLOB_FETCHES = 10+def format_results(items)return [] if items.blank?file_cache = {}+ blob_fetches = 0+ ignored = ignore_pathsresults =items.flat_map do |item|text_matches = item["text_matches"]next [] if text_matches.blank?- repo_full_name = item.dig("repository", "full_name") || repopath = item["path"]+ next [] if ignored.any? { |prefix| path.start_with?(prefix) }++ repo_full_name = item.dig("repository", "full_name") || reporef =extract_ref(item) || item.dig("repository", "default_branch") ||fetch_default_branch(repo_full_name)sha = item["sha"]- file_details = fetch_file_content(repo_full_name, path, ref, file_cache, sha)+ cache_key = blob_cache_key(repo_full_name, path, ref, sha)+ if file_cache.key?(cache_key)+ file_details = file_cache[cache_key]+ elsif blob_fetches < MAX_BLOB_FETCHES+ file_details = fetch_file_content(repo_full_name, path, ref, file_cache, sha)+ blob_fetches += 1+ else+ file_details = nil+ endtext_matches.map do |match|fragment = match["fragment"]@@ -166,38 +188,64 @@ module DiscourseAiresults.compactend- def trim_results(results)+ def group_by_file(results)return [] if results.blank?+ grouped = {}++ results.each do |entry|+ file = entry[:file]+ grouped[file] ||= { file: file, total_lines: entry[:total_file_lines], matches: [] }+ grouped[file][:matches] << { lines: entry[:lines], content: entry[:content] }+ end++ grouped.values+ end++ def trim_results(grouped_results)+ return [] if grouped_results.blank?+max_chars = 20_000used_chars = 0- trimmed =- results.each_with_object([]) do |entry, acc|- file = entry[:file].to_s- lines = entry[:lines].to_s- content = entry[:content].to_s+ grouped_results.each_with_object([]) do |file_entry, acc|+ file = file_entry[:file].to_s+ file_overhead = file.length + file_entry[:total_lines].to_s.length+ remaining = max_chars - used_chars- entry_length = file.length + lines.length + content.length- remaining = max_chars - used_chars+ break acc if remaining <= file_overhead- break acc if remaining <= 0+ trimmed_matches = []+ match_chars = 0- if entry_length > remaining- # Require space for file and line metadata.- metadata_length = file.length + lines.length- break acc if metadata_length >= remaining+ file_entry[:matches].each do |match|+ lines = match[:lines].to_s+ content = match[:content].to_s+ entry_length = lines.length + content.length+ match_remaining = remaining - file_overhead - match_chars- allowed_content_length = remaining - metadata_length- content = content[0...allowed_content_length]- entry_length = metadata_length + content.length+ break if match_remaining <= 0++ if entry_length > match_remaining+ allowed = match_remaining - lines.length+ break if allowed <= 0+ content = content[0...allowed]+ entry_length = lines.length + content.lengthend- acc << entry.merge(content: content)- used_chars += entry_length+ trimmed_matches << { lines: match[:lines], content: content }+ match_chars += entry_lengthend- trimmed+ next if trimmed_matches.empty?++ acc << {+ file: file_entry[:file],+ total_lines: file_entry[:total_lines],+ matches: trimmed_matches,+ }+ used_chars += file_overhead + match_chars+ endenddef format_line_label(line_range)@@ -210,11 +258,15 @@ module DiscourseAiendend+ def blob_cache_key(repo_full_name, path, ref, blob_sha)+ suffix = ref.presence || blob_sha.presence || "main"+ "#{repo_full_name || repo}@#{suffix}:#{path}"+ end+def fetch_file_content(repo_full_name, path, ref, cache, blob_sha)repo_full_name ||= repo- cache_suffix = ref.presence || blob_sha.presence || "main"- cache_key = "#{repo_full_name}@#{cache_suffix}:#{path}"+ cache_key = blob_cache_key(repo_full_name, path, ref, blob_sha)return cache[cache_key] if cache.key?(cache_key)owner, repo_name = repo_full_name.to_s.split("/", 2)diff --git a/plugins/discourse-ai/lib/personas/tools/github_search_files.rb b/plugins/discourse-ai/lib/personas/tools/github_search_files.rbindex 811d16d6a81..dc47d5cd138 100644--- a/plugins/discourse-ai/lib/personas/tools/github_search_files.rb+++ b/plugins/discourse-ai/lib/personas/tools/github_search_files.rb@@ -90,7 +90,7 @@ module DiscourseAiitem["type"] == "blob" &&keywords.any? { |keyword| item["path"].include?(keyword) }end- .map { |item| item["path"] }+ .map { |item| { path: item["path"], size: item["size"] } }.take(MAX_FILE_SEARCH_RESULTS)result = { matching_files: matching_files, branch: branch_name }diff --git a/plugins/discourse-ai/spec/lib/personas/tools/github_file_content_spec.rb b/plugins/discourse-ai/spec/lib/personas/tools/github_file_content_spec.rbindex aea6e4c92c2..46d417b40c4 100644--- a/plugins/discourse-ai/spec/lib/personas/tools/github_file_content_spec.rb+++ b/plugins/discourse-ai/spec/lib/personas/tools/github_file_content_spec.rb@@ -168,6 +168,65 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubFileContent doendend+ context "when a file exceeds the line limit" do+ let(:large_file_tool) do+ described_class.new(+ { repo_name: "discourse/discourse-ai", file_paths: ["lib/large.rb"], branch: "main" },+ bot_user: nil,+ llm: llm,+ )+ end++ before do+ large_content = (1..500).map { |i| "line #{i}" }.join("\n")+ stub_request(+ :get,+ "https://api.github.com/repos/discourse/discourse-ai/contents/lib/large.rb?ref=main",+ ).to_return(status: 200, body: { content: Base64.encode64(large_content) }.to_json)+ end++ it "truncates to MAX_LINES and shows a continuation hint" do+ result = large_file_tool.invoke+ content = result[:file_contents]++ expect(content).to include("line 1")+ expect(content).to include("line 200")+ expect(content).not_to include("line 201")+ expect(content).to include("[truncated")+ expect(content).to include("file has 500 lines")+ expect(content).to include("#L201-L400")+ end+ end++ context "when a line range does not reach end of file" do+ let(:range_tool) do+ described_class.new(+ { repo_name: "discourse/discourse-ai", file_paths: ["lib/big.rb#L1-L5"], branch: "main" },+ bot_user: nil,+ llm: llm,+ )+ end++ before do+ file_content = (1..50).map { |i| "line #{i}" }.join("\n")+ stub_request(+ :get,+ "https://api.github.com/repos/discourse/discourse-ai/contents/lib/big.rb?ref=main",+ ).to_return(status: 200, body: { content: Base64.encode64(file_content) }.to_json)+ end++ it "shows a continuation hint with remaining lines" do+ result = range_tool.invoke+ content = result[:file_contents]++ expect(content).to include("line 1")+ expect(content).to include("line 5")+ expect(content).not_to include("line 6")+ expect(content).to include("showing lines 1-5 of 50")+ expect(content).to include("#L6-L50")+ end+ end+context "when repo_name is invalid" dolet(:invalid_tool) dodescribed_class.new(diff --git a/plugins/discourse-ai/spec/lib/personas/tools/github_search_code_spec.rb b/plugins/discourse-ai/spec/lib/personas/tools/github_search_code_spec.rbindex 2cc6132ebd4..d1acb235553 100644--- a/plugins/discourse-ai/spec/lib/personas/tools/github_search_code_spec.rb+++ b/plugins/discourse-ai/spec/lib/personas/tools/github_search_code_spec.rb@@ -12,7 +12,7 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchCode dolet(:repo) { "discourse/discourse" }let(:query) { "def hello" }- it "searches for code in the repository" do+ it "searches for code and groups results by file" dofile_body = "def hellö\n puts 'hellö'\nend\n".dup.force_encoding(Encoding::ASCII_8BIT)stub_request(:get,@@ -50,18 +50,143 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchCode do).to_return(status: 200, body: { content: Base64.encode64(file_body) }.to_json)result = tool.invoke- expect(result[:search_results]).to include(- file: "test/hello.rb",- lines: "1-3",- total_file_lines: 3,- content: "def hellö\n puts 'hellö'\nend",+ expect(result[:search_results].length).to eq(1)++ file_entry = result[:search_results].first+ expect(file_entry[:file]).to eq("test/hello.rb")+ expect(file_entry[:total_lines]).to eq(3)+ expect(file_entry[:matches]).to contain_exactly(+ { lines: "1-3", content: "def hellö\n puts 'hellö'\nend" },)- expect(result[:pagination][:current_page]).to eq(1)- expect(result[:pagination][:total_pages]).to eq(1)++ expect(result[:total_results]).to eq(1)+ expect(result[:page]).to be_nil+ expect(result[:next_page]).to be_nilexpect(result[:error]).to be_nilendend+ context "with multiple matches in the same file" do+ let(:repo) { "discourse/discourse" }+ let(:query) { "published_page" }++ it "groups matches under a single file entry" do+ file_content =+ "class Ctrl\n def show\n published_page\n end\n\n def edit\n published_page\n end\nend\n"++ stub_request(+ :get,+ "https://api.github.com/search/code?page=1&per_page=30&q=published_page%20repo:discourse/discourse",+ ).to_return(+ status: 200,+ body: {+ total_count: 1,+ items: [+ {+ path: "app/controllers/ctrl.rb",+ sha: "aaa111",+ url:+ "https://api.github.com/repositories/1/contents/app/controllers/ctrl.rb?ref=main",+ repository: {+ full_name: "discourse/discourse",+ default_branch: "main",+ },+ text_matches: [+ { fragment: " def show\n published_page\n end" },+ { fragment: " def edit\n published_page\n end" },+ ],+ },+ ],+ }.to_json,+ )++ stub_request(+ :get,+ "https://api.github.com/repos/discourse/discourse/git/blobs/aaa111",+ ).to_return(status: 200, body: { content: Base64.encode64(file_content) }.to_json)++ result = tool.invoke+ expect(result[:search_results].length).to eq(1)++ file_entry = result[:search_results].first+ expect(file_entry[:file]).to eq("app/controllers/ctrl.rb")+ expect(file_entry[:matches].length).to eq(2)+ expect(file_entry[:matches][0][:lines]).to eq("2-4")+ expect(file_entry[:matches][1][:lines]).to eq("6-8")+ end+ end++ context "with ignore_paths" do+ let(:repo) { "discourse/discourse" }+ let(:query) { "enable_page_publishing" }++ let(:tool) do+ described_class.new(+ { repo: repo, query: query, ignore_paths: %w[config/locales/ spec/] },+ bot_user: bot_user,+ llm: llm,+ )+ end++ it "excludes files matching ignored path prefixes" do+ stub_request(+ :get,+ "https://api.github.com/search/code?page=1&per_page=30&q=enable_page_publishing%20repo:discourse/discourse",+ ).to_return(+ status: 200,+ body: {+ total_count: 3,+ items: [+ {+ path: "config/site_settings.yml",+ sha: "s1",+ url:+ "https://api.github.com/repositories/1/contents/config/site_settings.yml?ref=main",+ repository: {+ full_name: "discourse/discourse",+ default_branch: "main",+ },+ text_matches: [{ fragment: "enable_page_publishing: true" }],+ },+ {+ path: "config/locales/server.lt.yml",+ sha: "s2",+ url:+ "https://api.github.com/repositories/1/contents/config/locales/server.lt.yml?ref=main",+ repository: {+ full_name: "discourse/discourse",+ default_branch: "main",+ },+ text_matches: [{ fragment: "enable_page_publishing: translated" }],+ },+ {+ path: "spec/requests/published_pages_spec.rb",+ sha: "s3",+ url:+ "https://api.github.com/repositories/1/contents/spec/requests/published_pages_spec.rb?ref=main",+ repository: {+ full_name: "discourse/discourse",+ default_branch: "main",+ },+ text_matches: [{ fragment: "enable_page_publishing = true" }],+ },+ ],+ }.to_json,+ )++ stub_request(:get, "https://api.github.com/repos/discourse/discourse/git/blobs/s1").to_return(+ status: 200,+ body: { content: Base64.encode64("enable_page_publishing: true\n") }.to_json,+ )++ result = tool.invoke+ files = result[:search_results].map { |r| r[:file] }+ expect(files).to eq(["config/site_settings.yml"])+ expect(files).not_to include("config/locales/server.lt.yml")+ expect(files).not_to include("spec/requests/published_pages_spec.rb")+ end+ end+context "with partial metadata" dolet(:repo) { "discourse/discourse" }let(:query) { "A_CONSTANT" }@@ -102,12 +227,10 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchCode do).to_return(status: 404)result = tool.invoke- expect(result[:search_results]).to include(- file: "config/constants.rb",- lines: nil,- total_file_lines: nil,- content: "A_CONSTANT = true",- )+ file_entry = result[:search_results].first+ expect(file_entry[:file]).to eq("config/constants.rb")+ expect(file_entry[:total_lines]).to be_nil+ expect(file_entry[:matches]).to contain_exactly({ lines: nil, content: "A_CONSTANT = true" })endenddiff --git a/plugins/discourse-ai/spec/lib/personas/tools/github_search_files_spec.rb b/plugins/discourse-ai/spec/lib/personas/tools/github_search_files_spec.rbindex 48e31e2ff7a..9cde352ea9c 100644--- a/plugins/discourse-ai/spec/lib/personas/tools/github_search_files_spec.rb+++ b/plugins/discourse-ai/spec/lib/personas/tools/github_search_files_spec.rb@@ -36,8 +36,8 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchFiles dostatus: 200,body: {tree: [- { path: "lib/modules/ai_bot/tools/github_search_code.rb", type: "blob" },- { path: "lib/modules/ai_bot/tools/github_file_content.rb", type: "blob" },+ { path: "lib/modules/ai_bot/tools/github_search_code.rb", type: "blob", size: 8_432 },+ { path: "lib/modules/ai_bot/tools/github_file_content.rb", type: "blob", size: 5_210 },],}.to_json,)@@ -45,15 +45,13 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchFiles doit "retrieves files matching the specified keywords" doresult = tool.invoke- expected = {- branch: "main",- matching_files: %w[- lib/modules/ai_bot/tools/github_search_code.rb- lib/modules/ai_bot/tools/github_file_content.rb+ expect(result[:branch]).to eq("main")+ expect(result[:matching_files]).to eq(+ [+ { path: "lib/modules/ai_bot/tools/github_search_code.rb", size: 8_432 },+ { path: "lib/modules/ai_bot/tools/github_file_content.rb", size: 5_210 },],- }-- expect(result).to eq(expected)+ )endit "handles missing branches gracefully" do@@ -80,7 +78,8 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchFiles doit "fetches the default branch if none is specified" doresult = tool.invoke- expect(result[:matching_files]).to match_array(+ files = result[:matching_files].map { |f| f[:path] }+ expect(files).to match_array(%w[lib/modules/ai_bot/tools/github_search_code.rblib/modules/ai_bot/tools/github_file_content.rb@@ -91,13 +90,13 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchFiles doit "limits results to MAX_FILE_SEARCH_RESULTS and adds a note when limit is reached" domax_results = described_class::MAX_FILE_SEARCH_RESULTS- matching_files = (1..max_results + 1).map { |i| "lib/tools/search_tool_#{i}.rb" }+ file_paths = (1..max_results + 1).map { |i| "lib/tools/search_tool_#{i}.rb" }stub_request(:get,"https://api.github.com/repos/discourse/discourse-ai/git/trees/#{default_branch}?recursive=1",).to_return(status: 200,- body: { tree: matching_files.map { |path| { path: path, type: "blob" } } }.to_json,+ body: { tree: file_paths.map { |path| { path: path, type: "blob", size: 1000 } } }.to_json,)result = tool.invoke