Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: line number support for Github helper (#36058)

Sam3ddc1fa768ad
diff --git a/plugins/discourse-ai/lib/personas/github_helper.rb b/plugins/discourse-ai/lib/personas/github_helper.rb
index bd75624d0e3..91bba812080 100644
--- a/plugins/discourse-ai/lib/personas/github_helper.rb
+++ b/plugins/discourse-ai/lib/personas/github_helper.rb
@@ -14,15 +14,18 @@ module DiscourseAi
def system_prompt
<<~PROMPT
- You are a helpful GitHub assistant.
- You _understand_ and **generate** Discourse Flavored Markdown.
- You live in a Discourse Forum Message.
+ You are a helpful GitHub assistant.
+ You _understand_ and **generate** Discourse Flavored Markdown.
+ You live in a Discourse Forum Message.
- Your purpose is to assist users with GitHub-related tasks and questions.
- When asked about a specific repository, pull request, or file, try to use the available tools to provide accurate and helpful information.
+ When answering GitHub questions, use available tools to search repositories, read files, and fetch PR/issue details.
- The date now is: {time}, much has changed since you were trained.
- PROMPT
+ ALWAYS link to relevant GitHub resources:
+ - Files: [file.rb](https://github.com/owner/repo/blob/branch/file.rb#L10-L25)
+ - PRs/Issues: [#123](https://github.com/owner/repo/pull/123)
+
+ The date now is: {time}, much has changed since you were trained.
+ PROMPT
end
end
end
diff --git a/plugins/discourse-ai/lib/personas/tools/github_file_content.rb b/plugins/discourse-ai/lib/personas/tools/github_file_content.rb
index aef00c1e65d..7c75a3005a1 100644
--- a/plugins/discourse-ai/lib/personas/tools/github_file_content.rb
+++ b/plugins/discourse-ai/lib/personas/tools/github_file_content.rb
@@ -16,7 +16,8 @@ module DiscourseAi
},
{
name: "file_paths",
- description: "The paths of the files to retrieve within the repository",
+ description:
+ "The file paths to retrieve. Append '#Lstart-Lend' (e.g., app/models/user.rb#L10-L25) to limit the returned lines",
type: "array",
item_type: "string",
required: true,
@@ -45,21 +46,27 @@ module DiscourseAi
end
def branch
- parameters[:branch] || "main"
+ parameters[:branch]
end
def description_args
- { repo_name: repo_name, file_paths: file_paths.join(", "), branch: branch }
+ {
+ repo_name: repo_name,
+ file_paths: file_paths.join(", "),
+ branch: branch || default_branch,
+ }
end
def invoke
owner, repo = repo_name.split("/")
- file_contents = {}
+ ref = branch || default_branch
+ retrieved_entries = []
missing_files = []
- file_paths.each do |file_path|
+ parsed_file_requests.each do |file_request|
+ file_path = file_request[:path]
api_url =
- "https://api.github.com/repos/#{owner}/#{repo}/contents/#{file_path}?ref=#{branch}"
+ "https://api.github.com/repos/#{owner}/#{repo}/contents/#{file_path}?ref=#{ref}"
response_code = "-1 unknown"
body = nil
@@ -78,16 +85,36 @@ module DiscourseAi
if response_code == "200"
file_data = JSON.parse(body)
content = Base64.decode64(file_data["content"])
- file_contents[file_path] = content
+ snippet =
+ extract_requested_content(
+ content,
+ file_request[:start_line],
+ file_request[:end_line],
+ )
+ retrieved_entries << {
+ path: file_path,
+ content: snippet,
+ start_line: file_request[:start_line],
+ end_line: file_request[:end_line],
+ }
else
- missing_files << file_path
+ missing_files << file_request[:raw]
end
end
result = {}
- unless file_contents.empty?
+ unless retrieved_entries.empty?
blob =
- file_contents.map { |path, content| "File Path: #{path}:\n#{content}" }.join("\n")
+ retrieved_entries
+ .map do |entry|
+ label = "File Path: #{entry[:path]}"
+ if entry[:start_line]
+ label += " (lines #{format_line_range(entry[:start_line], entry[:end_line])})"
+ end
+
+ "#{label}:\n#{entry[:content]}"
+ end
+ .join("\n")
truncated_blob = truncate(blob, max_length: 20_000, percent_length: 0.3, llm: llm)
result[:file_contents] = truncated_blob
end
@@ -96,6 +123,72 @@ module DiscourseAi
result.empty? ? { error: "No files found or retrieved." } : result
end
+
+ private
+
+ def default_branch
+ @default_branch ||= fetch_default_branch(repo_name)
+ end
+
+ def parsed_file_requests
+ @parsed_file_requests ||=
+ file_paths.map do |raw|
+ start_line, end_line = extract_line_bounds(raw)
+
+ {
+ raw: raw,
+ path: raw.sub(line_fragment_regex, ""),
+ start_line: start_line,
+ end_line: end_line || start_line,
+ }
+ end
+ end
+
+ def extract_line_bounds(raw)
+ match = raw.match(line_fragment_regex)
+ return nil, nil unless match
+
+ start_line = positive_line_number(match[1])
+ end_line = positive_line_number(match[2])
+ end_line = start_line if start_line && end_line && end_line < start_line
+
+ [start_line, end_line]
+ end
+
+ def positive_line_number(value)
+ return if value.blank?
+
+ number = value.to_i
+ number.positive? ? number : nil
+ end
+
+ def line_fragment_regex
+ /#L(\d+)(?:-L?(\d+))?\z/i
+ end
+
+ def extract_requested_content(content, start_line, end_line)
+ return content if start_line.nil?
+
+ normalized = content.gsub("\r\n", "\n")
+ lines = normalized.split("\n")
+ total_lines = lines.length
+
+ if start_line > total_lines
+ return(
+ "Requested lines #{start_line}-#{end_line || start_line} exceed file length of #{total_lines}."
+ )
+ end
+
+ final_end_line = [end_line || start_line, total_lines].min
+ extracted = lines[(start_line - 1)..(final_end_line - 1)] || []
+ extracted.join("\n")
+ end
+
+ def format_line_range(start_line, end_line)
+ return start_line.to_s if start_line == end_line || end_line.nil?
+
+ "#{start_line}-#{end_line}"
+ end
end
end
end
diff --git a/plugins/discourse-ai/lib/personas/tools/github_search_code.rb b/plugins/discourse-ai/lib/personas/tools/github_search_code.rb
index 3bb93d02154..b4f9851e107 100644
--- a/plugins/discourse-ai/lib/personas/tools/github_search_code.rb
+++ b/plugins/discourse-ai/lib/personas/tools/github_search_code.rb
@@ -1,9 +1,16 @@
# frozen_string_literal: true
+require "cgi"
+require "uri"
+
module DiscourseAi
module Personas
module Tools
class GithubSearchCode < Tool
+ MAX_GH_RESULTS = 1_000
+ PER_PAGE = 30
+ MAX_ALLOWED_PAGE = (MAX_GH_RESULTS / PER_PAGE.to_f).ceil
+
def self.signature
{
name: name,
@@ -21,6 +28,12 @@ module DiscourseAi
type: "string",
required: true,
},
+ {
+ name: "page",
+ description: "Results page to retrieve (GitHub returns up to 30 results per page)",
+ type: "integer",
+ required: false,
+ },
],
}
end
@@ -37,12 +50,18 @@ module DiscourseAi
parameters[:query]
end
+ def page
+ requested = parameters[:page].to_i
+ requested = 1 if requested <= 0
+ [requested, MAX_ALLOWED_PAGE].min
+ end
+
def description_args
- { repo: repo, query: query }
+ { repo: repo, query: query, page: page }
end
def invoke
- api_url = "https://api.github.com/search/code?q=#{query}+repo:#{repo}"
+ api_url = build_url
response_code = "unknown error"
search_data = nil
@@ -65,17 +84,234 @@ module DiscourseAi
end
if response_code == "200"
- results =
- search_data["items"]
- .map { |item| "#{item["path"]}:\n#{item["text_matches"][0]["fragment"]}" }
- .join("\n---\n")
+ formatted_results = trim_results(format_results(search_data["items"]))
+
+ total_count = search_data["total_count"].to_i
+ total_pages =
+ if total_count <= 0
+ 1
+ else
+ [((total_count.to_f / PER_PAGE).ceil), MAX_ALLOWED_PAGE].min
+ end
+
+ 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,
+ },
+ }
+
+ if search_data["incomplete_results"]
+ result[:notes] = "GitHub marked the search results as incomplete."
+ end
- results = truncate(results, max_length: 20_000, percent_length: 0.3, llm: llm)
- { search_results: results }
+ result
else
{ error: "Failed to perform code search. Status code: #{response_code}" }
end
end
+
+ private
+
+ def build_url
+ base_query = "#{query} repo:#{repo}"
+ encoded_params = URI.encode_www_form({ q: base_query, page: page, per_page: PER_PAGE })
+
+ "https://api.github.com/search/code?#{encoded_params}"
+ end
+
+ def format_results(items)
+ return [] if items.blank?
+
+ file_cache = {}
+
+ results =
+ items.flat_map do |item|
+ text_matches = item["text_matches"]
+ next [] if text_matches.blank?
+
+ repo_full_name = item.dig("repository", "full_name") || repo
+ path = item["path"]
+ ref =
+ 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)
+
+ text_matches.map do |match|
+ fragment = match["fragment"]
+ next if fragment.blank?
+
+ content = file_details&.dig(:content)
+ total_lines = file_details&.dig(:total_lines)
+ line_range = derive_line_range(content, fragment)
+
+ {
+ file: path,
+ lines: format_line_label(line_range),
+ total_file_lines: total_lines,
+ content: fragment,
+ }
+ end
+ end
+
+ results.compact
+ end
+
+ def trim_results(results)
+ return [] if results.blank?
+
+ max_chars = 20_000
+ used_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
+
+ entry_length = file.length + lines.length + content.length
+ remaining = max_chars - used_chars
+
+ break acc if remaining <= 0
+
+ if entry_length > remaining
+ # Require space for file and line metadata.
+ metadata_length = file.length + lines.length
+ break acc if metadata_length >= remaining
+
+ allowed_content_length = remaining - metadata_length
+ content = content[0...allowed_content_length]
+ entry_length = metadata_length + content.length
+ end
+
+ acc << entry.merge(content: content)
+ used_chars += entry_length
+ end
+
+ trimmed
+ end
+
+ def format_line_label(line_range)
+ return nil if line_range.nil?
+
+ if line_range[:start_line] == line_range[:end_line]
+ line_range[:start_line].to_s
+ else
+ "#{line_range[:start_line]}-#{line_range[:end_line]}"
+ end
+ 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}"
+ return cache[cache_key] if cache.key?(cache_key)
+
+ owner, repo_name = repo_full_name.to_s.split("/", 2)
+ if owner.blank? || repo_name.blank?
+ cache[cache_key] = nil
+ return nil
+ end
+
+ url =
+ if blob_sha.present?
+ "https://api.github.com/repos/#{owner}/#{repo_name}/git/blobs/#{blob_sha}"
+ else
+ actual_ref = ref.presence || fetch_default_branch(repo_full_name)
+ "https://api.github.com/repos/#{owner}/#{repo_name}/contents/#{path}?ref=#{actual_ref}"
+ end
+
+ response_code = nil
+ body = nil
+
+ send_http_request(
+ url,
+ headers: {
+ "Accept" => "application/vnd.github.v3+json",
+ },
+ authenticate_github: true,
+ ) do |response|
+ response_code = response.code
+ body = read_response_body(response)
+ end
+
+ if response_code == "200"
+ begin
+ data = JSON.parse(body)
+ decoded = ensure_utf8(Base64.decode64(data["content"].to_s))
+ cache[cache_key] = { content: decoded, total_lines: count_lines(decoded) }
+ rescue JSON::ParserError
+ cache[cache_key] = nil
+ end
+ else
+ cache[cache_key] = nil
+ end
+
+ cache[cache_key]
+ end
+
+ def extract_ref(item)
+ url = item["url"]
+ return if url.blank?
+
+ uri =
+ begin
+ URI.parse(url)
+ rescue StandardError
+ nil
+ end
+ return unless uri&.query
+
+ CGI.parse(uri.query || "")["ref"]&.first
+ end
+
+ def derive_line_range(file_content, fragment)
+ return if file_content.blank? || fragment.blank?
+
+ file = normalize_line_endings(file_content)
+ snippet = normalize_line_endings(fragment)
+
+ # GitHub fragments mirror contiguous file sections, so match directly.
+ index = file.index(snippet)
+ return if index.nil?
+
+ prefix = file[0...index]
+ start_line = prefix.count("\n") + 1
+ line_count = snippet.each_line.count
+
+ { start_line: start_line, end_line: start_line + line_count - 1 }
+ end
+
+ def normalize_line_endings(text)
+ text.gsub("\r\n", "\n")
+ end
+
+ def count_lines(content)
+ return 0 if content.blank?
+
+ normalized = normalize_line_endings(content)
+ normalized.count("\n") + (normalized.end_with?("\n") ? 0 : 1)
+ end
+
+ def ensure_utf8(text)
+ return "" if text.nil?
+
+ result = text.dup
+ result.force_encoding(Encoding::UTF_8)
+ return result if result.valid_encoding?
+
+ result.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "")
+ end
end
end
end
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.rb
index ca46fbe2d6f..e0588e5935c 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
@@ -19,32 +19,95 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubFileContent do
before { enable_current_plugin }
describe "#invoke" do
- before do
- stub_request(
- :get,
- "https://api.github.com/repos/discourse/discourse-ai/contents/lib/database/connection.rb?ref=8b382d6098fde879d28bbee68d3cbe0a193e4ffc",
- ).to_return(
- status: 200,
- body: { content: Base64.encode64("content of connection.rb") }.to_json,
- )
+ context "when fetching full files" do
+ before do
+ stub_request(
+ :get,
+ "https://api.github.com/repos/discourse/discourse-ai/contents/lib/database/connection.rb?ref=8b382d6098fde879d28bbee68d3cbe0a193e4ffc",
+ ).to_return(
+ status: 200,
+ body: { content: Base64.encode64("content of connection.rb") }.to_json,
+ )
- stub_request(
- :get,
- "https://api.github.com/repos/discourse/discourse-ai/contents/lib/ai_bot/tools/github_pull_request_diff.rb?ref=8b382d6098fde879d28bbee68d3cbe0a193e4ffc",
- ).to_return(
- status: 200,
- body: { content: Base64.encode64("content of github_pull_request_diff.rb") }.to_json,
- )
+ stub_request(
+ :get,
+ "https://api.github.com/repos/discourse/discourse-ai/contents/lib/ai_bot/tools/github_pull_request_diff.rb?ref=8b382d6098fde879d28bbee68d3cbe0a193e4ffc",
+ ).to_return(
+ status: 200,
+ body: { content: Base64.encode64("content of github_pull_request_diff.rb") }.to_json,
+ )
+ end
+
+ it "retrieves the content of the specified GitHub files" do
+ result = tool.invoke
+ expected = {
+ file_contents:
+ "File Path: lib/database/connection.rb:\ncontent of connection.rb\nFile Path: lib/ai_bot/tools/github_pull_request_diff.rb:\ncontent of github_pull_request_diff.rb",
+ }
+
+ expect(result).to eq(expected)
+ end
end
- it "retrieves the content of the specified GitHub files" do
- result = tool.invoke
- expected = {
- file_contents:
- "File Path: lib/database/connection.rb:\ncontent of connection.rb\nFile Path: lib/ai_bot/tools/github_pull_request_diff.rb:\ncontent of github_pull_request_diff.rb",
- }
+ context "when requesting specific line ranges" do
+ let(:range_tool) do
+ described_class.new(
+ { repo_name: "discourse/discourse-ai", file_paths: ["lib/sample.rb#L2-L3"] },
+ bot_user: nil,
+ llm: llm,
+ )
+ end
+
+ before do
+ stub_request(
+ :get,
+ "https://api.github.com/repos/discourse/discourse-ai/contents/lib/sample.rb?ref=main",
+ ).to_return(
+ status: 200,
+ body: { content: Base64.encode64("line1\nline2\nline3\nline4\n") }.to_json,
+ )
+
+ stub_request(:get, "https://api.github.com/repos/discourse/discourse-ai").to_return(
+ status: 200,
+ body: { default_branch: "main" }.to_json,
+ )
+ end
+
+ it "returns only the requested lines with metadata" do
+ result = range_tool.invoke
+ expect(result[:file_contents]).to include("File Path: lib/sample.rb (lines 2-3):")
+ expect(result[:file_contents]).to include("line2\nline3")
+ end
+ end
+
+ context "when no branch is provided" do
+ let(:range_tool) do
+ described_class.new(
+ { repo_name: "discourse/discourse-ai", file_paths: ["lib/sample.rb#L2-L3"] },
+ bot_user: nil,
+ llm: llm,
+ )
+ end
+
+ before do
+ stub_request(:get, "https://api.github.com/repos/discourse/discourse-ai").to_return(
+ status: 200,
+ body: { default_branch: "testing" }.to_json,
+ )
+
+ stub_request(
+ :get,
+ "https://api.github.com/repos/discourse/discourse-ai/contents/lib/sample.rb?ref=testing",
+ ).to_return(
+ status: 200,
+ body: { content: Base64.encode64("line1\nline2\nline3\nline4\n") }.to_json,
+ )
+ end
- expect(result).to eq(expected)
+ it "uses the default branch" do
+ result = range_tool.invoke
+ expect(result[:file_contents]).to include("File Path: lib/sample.rb (lines 2-3):")
+ end
end
end
@@ -63,7 +126,8 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubFileContent do
},
{
name: "file_paths",
- description: "The paths of the files to retrieve within the repository",
+ description:
+ "The file paths to retrieve. Append '#Lstart-Lend' (e.g., app/models/user.rb#L10-L25) to limit the returned lines",
type: "array",
item_type: "string",
required: true,
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.rb
index 6dacc7bd134..2cc6132ebd4 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
@@ -13,9 +13,10 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchCode do
let(:query) { "def hello" }
it "searches for code in the repository" do
+ file_body = "def hellö\n puts 'hellö'\nend\n".dup.force_encoding(Encoding::ASCII_8BIT)
stub_request(
:get,
- "https://api.github.com/search/code?q=def%20hello+repo:discourse/discourse",
+ "https://api.github.com/search/code?page=1&per_page=30&q=def%20hello%20repo:discourse/discourse",
).with(
headers: {
"Accept" => "application/vnd.github.v3.text-match+json",
@@ -29,26 +30,94 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchCode do
{
path: "test/hello.rb",
name: "hello.rb",
- text_matches: [{ fragment: "def hello\n puts 'hello'\nend" }],
+ sha: "abc123",
+ url:
+ "https://api.github.com/repositories/1/contents/test/hello.rb?ref=main-sha-commit",
+ repository: {
+ full_name: "discourse/discourse",
+ default_branch: "main",
+ },
+ text_matches: [{ fragment: "def hellö\n puts 'hellö'\nend" }],
},
],
}.to_json,
)
+ stub_request(:get, "https://api.github.com/repos/discourse/discourse/git/blobs/abc123").with(
+ headers: {
+ "Accept" => "application/vnd.github.v3+json",
+ "User-Agent" => DiscourseAi::AiBot::USER_AGENT,
+ },
+ ).to_return(status: 200, body: { content: Base64.encode64(file_body) }.to_json)
result = tool.invoke
- expect(result[:search_results]).to include("def hello\n puts 'hello'\nend")
- expect(result[:search_results]).to include("test/hello.rb")
+ 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[:pagination][:current_page]).to eq(1)
+ expect(result[:pagination][:total_pages]).to eq(1)
expect(result[:error]).to be_nil
end
end
+ context "with partial metadata" do
+ let(:repo) { "discourse/discourse" }
+ let(:query) { "A_CONSTANT" }
+
+ it "falls back gracefully when file content cannot be retrieved" do
+ stub_request(
+ :get,
+ "https://api.github.com/search/code?page=1&per_page=30&q=A_CONSTANT%20repo:discourse/discourse",
+ ).with(
+ headers: {
+ "Accept" => "application/vnd.github.v3.text-match+json",
+ "User-Agent" => DiscourseAi::AiBot::USER_AGENT,
+ },
+ ).to_return(
+ status: 200,
+ body: {
+ total_count: 1,
+ items: [
+ {
+ path: "config/constants.rb",
+ sha: "def456",
+ url: "https://api.github.com/repositories/1/contents/config/constants.rb?ref=main",
+ repository: {
+ full_name: "discourse/discourse",
+ default_branch: "main",
+ },
+ text_matches: [{ fragment: "A_CONSTANT = true" }],
+ },
+ ],
+ }.to_json,
+ )
+
+ stub_request(:get, "https://api.github.com/repos/discourse/discourse/git/blobs/def456").with(
+ headers: {
+ "Accept" => "application/vnd.github.v3+json",
+ "User-Agent" => DiscourseAi::AiBot::USER_AGENT,
+ },
+ ).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",
+ )
+ end
+ end
+
context "with an empty search result" do
let(:repo) { "discourse/discourse" }
let(:query) { "nonexistent_method" }
describe "#description_args" do
it "returns the repo and query" do
- expect(tool.description_args).to eq(repo: repo, query: query)
+ expect(tool.description_args).to eq(repo: repo, query: query, page: 1)
end
end
@@ -56,7 +125,7 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchCode do
SiteSetting.ai_bot_github_access_token = "ABC"
stub_request(
:get,
- "https://api.github.com/search/code?q=nonexistent_method+repo:discourse/discourse",
+ "https://api.github.com/search/code?page=1&per_page=30&q=nonexistent_method%20repo:discourse/discourse",
).with(
headers: {
"Accept" => "application/vnd.github.v3.text-match+json",
@@ -78,7 +147,7 @@ RSpec.describe DiscourseAi::Personas::Tools::GithubSearchCode do
it "returns an error message" do
stub_request(
:get,
- "https://api.github.com/search/code?q=def%20hello+repo:discourse/discourse",
+ "https://api.github.com/search/code?page=1&per_page=30&q=def%20hello%20repo:discourse/discourse",
).with(
headers: {
"Accept" => "application/vnd.github.v3.text-match+json",