Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions docs-agent-mcp/pipelines/issues-pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,28 @@ def fetch_comments(owner, name, issue_number):

while True:
comments = api_request(comments_url, {"per_page": 100, "page": page})
if comments is None:
print(
f"WARNING: Failed to fetch comments for "
f"{owner}/{name}#{issue_number} (page {page}); "
f"indexing with {len(comments_list)} comments "
f"fetched so far."
)
break
if not comments:
break

for comment in comments:
if not isinstance(comment, dict):
continue
user = comment.get("user") or {}
if not isinstance(user, dict):
user = {}
comments_list.append({
"author": comment.get("user", {}).get("login", "unknown"),
"author": user.get("login", "unknown"),
"created_at": (comment.get("created_at", "") or "")[:10],
"body": comment.get("body", "") or "",
"url": comment.get("html_url", "") or "",
})

if len(comments) < 100:
Expand All @@ -142,10 +156,14 @@ def format_issue_markdown(title, repo_name, issue_number, url, labels_str, issue
content += f"**Updated:** {updated_at}\n\n"
content += body or ""
for comment in comments:
content += (
f"\n\n---\n**Comment by @{comment['author']}** "
f"({comment['created_at']}):\n{comment['body']}"
header = (
f"**Comment by @{comment['author']}** "
f"({comment['created_at']}):"
)
curl = comment.get("url", "") or ""
if curl:
header += f" {curl}"
content += f"\n\n---\n{header}\n{comment['body']}"
return content

for repo in repos.split(","):
Expand Down Expand Up @@ -362,7 +380,11 @@ def content_segments(issue):
author = comment.get("author", "unknown")
created = comment.get("created_at", "")
cbody = comment.get("body", "") or ""
seg = f"**Comment by @{author}** ({created}):\n{cbody}".strip()
curl = comment.get("url", "") or ""
header = f"**Comment by @{author}** ({created}):"
if curl:
header += f" {curl}"
seg = f"{header}\n{cbody}".strip()
if seg:
segments.append(seg)
return segments if segments else [issue.get("content", "") or ""]
Expand Down
99 changes: 75 additions & 24 deletions docs-agent-mcp/pipelines/utils/issues_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ def format_issue_markdown(
author = comment.get("author", "unknown")
created = comment.get("created_at", "")
cbody = comment.get("body", "") or ""
content += f"\n\n---\n**Comment by @{author}** ({created}):\n{cbody}"
curl = comment.get("url", "") or ""
header = f"**Comment by @{author}** ({created}):"
if curl:
header += f" {curl}"
content += f"\n\n---\n{header}\n{cbody}"

return content

Expand Down Expand Up @@ -125,11 +129,7 @@ def metadata_from_structured(record: dict[str, Any]) -> dict[str, Any]:
"issue_number": issue_number,
"issue_state": (record.get("issue_state") or "").strip(),
"issue_labels": (record.get("issue_labels") or "").strip(),
"citation_url": (
record.get("url")
or record.get("citation_url")
or ""
).strip(),
"citation_url": (record.get("url") or record.get("citation_url") or "").strip(),
}


Expand All @@ -147,12 +147,12 @@ def parse_issue_metadata(content: str) -> dict:
issue_labels, citation_url. Missing fields default to empty string
(or 0 for issue_number).
"""
title_match = re.search(r'^#\s+(.+)', content, re.MULTILINE)
repo_match = re.search(r'\*\*Repository:\*\*\s*(.+)', content)
number_match = re.search(r'\*\*Issue:\*\*\s*#(\d+)', content)
url_match = re.search(r'\*\*URL:\*\*\s*(.+)', content)
labels_match = re.search(r'\*\*Labels:\*\*[ \t]*(.*)', content)
state_match = re.search(r'\*\*State:\*\*\s*(\w+)', content)
title_match = re.search(r"^#\s+(.+)", content, re.MULTILINE)
repo_match = re.search(r"\*\*Repository:\*\*\s*(.+)", content)
number_match = re.search(r"\*\*Issue:\*\*\s*#(\d+)", content)
url_match = re.search(r"\*\*URL:\*\*\s*(.+)", content)
labels_match = re.search(r"\*\*Labels:\*\*[ \t]*(.*)", content)
state_match = re.search(r"\*\*State:\*\*\s*(\w+)", content)

return {
"title": title_match.group(1).strip() if title_match else "",
Expand All @@ -177,21 +177,15 @@ def resolve_issue_metadata(record: dict[str, Any] | str) -> dict[str, Any]:
if isinstance(record, str):
metadata = parse_issue_metadata(record)
if _is_empty_metadata(metadata):
print(
"WARNING: Failed to parse GitHub issue metadata. "
"Upstream markdown format may have changed."
)
print("WARNING: Failed to parse GitHub issue metadata. Upstream markdown format may have changed.")
return metadata

if has_structured_metadata(record):
return metadata_from_structured(record)

metadata = parse_issue_metadata(record.get("content", "") or "")
if _is_empty_metadata(metadata):
print(
"WARNING: Failed to parse GitHub issue metadata. "
"Upstream markdown format may have changed."
)
print("WARNING: Failed to parse GitHub issue metadata. Upstream markdown format may have changed.")
return metadata


Expand All @@ -214,11 +208,70 @@ def build_metadata_prefix(metadata: dict) -> str:
return " | ".join(parts) + "\n\n"


def fetch_issue_comments(
owner: str,
repo: str,
issue_number: int,
request_fn,
per_page: int = 100,
) -> list[dict[str, Any]]:
"""Fetch all comments for one issue, keeping each comment's URL.

Args:
owner: GitHub repo owner, e.g. "kubeflow".
repo: GitHub repo name, e.g. "docs-agent".
issue_number: Issue number to fetch comments for.
request_fn: Callable ``request_fn(url, params) -> list | None``.
In the pipeline, pass the nested ``api_request`` as
``request_fn``. Tests pass a mock. Returning ``None``
means the API call failed (after retries / non-200).
per_page: Comments per API page (GitHub max 100).

Returns:
List of comment dicts with ``author``, ``created_at`` (date
only), ``body`` and ``url`` (the comment's ``html_url``).
On a failed page it prints a WARNING and returns the
comments fetched so far, instead of silently returning [].
"""
comments: list[dict[str, Any]] = []
page = 1
url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}/comments"
while True:
result = request_fn(url, {"per_page": per_page, "page": page})
if result is None:
print(
f"WARNING: Failed to fetch comments for "
f"{owner}/{repo}#{issue_number} (page {page}); "
f"indexing with {len(comments)} comments fetched so far."
)
break
for comment in result or []:
if not isinstance(comment, dict):
continue
user = comment.get("user") or {}
comments.append(
{
"author": user.get("login", "unknown"),
"created_at": (comment.get("created_at", "") or "")[:10],
"body": comment.get("body", "") or "",
"url": comment.get("html_url", "") or "",
}
)
if len(result) < per_page:
break
page += 1
return comments


def _comment_segment(comment: dict[str, Any]) -> str:
author = comment.get("author", "unknown")
created = comment.get("created_at", "")
body = comment.get("body", "") or ""
return f"**Comment by @{author}** ({created}):\n{body}"
url = comment.get("url", "") or ""
header = f"**Comment by @{author}** ({created}):"
if url:
header += f" {url}"
return f"{header}\n{body}"


def issue_content_segments(record: dict[str, Any]) -> list[str]:
Expand All @@ -227,9 +280,7 @@ def issue_content_segments(record: dict[str, Any]) -> list[str]:
Prefers structured `body` + `comments` when present; otherwise falls back
to splitting the human-readable `content` on comment separators.
"""
if isinstance(record.get("body"), str) and (
"comments" in record or has_structured_metadata(record)
):
if isinstance(record.get("body"), str) and ("comments" in record or has_structured_metadata(record)):
segments: list[str] = []
# Include title + body as the first segment (matches prior MD layout)
title = (record.get("title") or "").strip()
Expand Down
135 changes: 135 additions & 0 deletions tests/test_issues_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from issues_utils import (
build_issue_record,
build_metadata_prefix,
fetch_issue_comments,
format_issue_markdown,
has_structured_metadata,
issue_content_segments,
Expand Down Expand Up @@ -88,11 +89,13 @@
"author": "alice",
"created_at": "2026-01-16",
"body": "Have you tried setting memory limits in your InferenceService spec?",
"url": "https://github.com/kubeflow/kubeflow/issues/42#issuecomment-1001",
},
{
"author": "bob",
"created_at": "2026-01-17",
"body": "Fixed by upgrading KServe to v0.12. The GPU memory allocation was improved.",
"url": "https://github.com/kubeflow/kubeflow/issues/42#issuecomment-1002",
},
],
)
Expand Down Expand Up @@ -309,3 +312,135 @@ def test_respects_chunk_size(self):
def test_handles_empty_content(self):
chunks = split_issue_into_chunks("", "prefix\n\n", chunk_size=1000)
assert len(chunks) == 1


def _api_comment(login, created_at, body, html_url):
"""Build one fake GitHub API comment dict."""
return {
"user": {"login": login} if login is not None else None,
"created_at": created_at,
"body": body,
"html_url": html_url,
}


class TestFetchIssueComments:
"""Tests for fetch_issue_comments (mocked request_fn, no network)."""

def test_maps_author_date_body_url(self):
def request_fn(url, params):
assert url == ("https://api.github.com/repos/kubeflow/docs-agent/issues/9/comments")
assert params == {"per_page": 100, "page": 1}
return [
_api_comment(
"alice",
"2026-01-16T10:00:00Z",
"Have you tried setting memory limits?",
"https://github.com/kubeflow/docs-agent/issues/9#issuecomment-1001",
)
]

comments = fetch_issue_comments("kubeflow", "docs-agent", 9, request_fn)
assert comments == [
{
"author": "alice",
"created_at": "2026-01-16",
"body": "Have you tried setting memory limits?",
"url": "https://github.com/kubeflow/docs-agent/issues/9#issuecomment-1001",
}
]

def test_pagination_two_pages(self):
def request_fn(url, params):
if params["page"] == 1:
return [_api_comment("a", "2026-01-01T00:00:00Z", f"c{i}", "") for i in range(100)]
return [_api_comment("b", "2026-01-02T00:00:00Z", "last", "")]

comments = fetch_issue_comments("kubeflow", "docs-agent", 9, request_fn)
assert len(comments) == 101
assert comments[0]["author"] == "a"
assert comments[-1]["author"] == "b"

def test_empty_comments_returns_empty(self):
comments = fetch_issue_comments("kubeflow", "docs-agent", 9, lambda url, params: [])
assert comments == []

def test_malformed_comment_missing_user_body(self):
def request_fn(url, params):
return [
{"created_at": "2026-01-16T10:00:00Z", "body": None},
"not-a-dict",
]

comments = fetch_issue_comments("kubeflow", "docs-agent", 9, request_fn)
assert comments == [
{
"author": "unknown",
"created_at": "2026-01-16",
"body": "",
"url": "",
}
]

def test_failed_fetch_returns_empty_and_warns(self, capsys):
comments = fetch_issue_comments("kubeflow", "docs-agent", 9, lambda url, params: None)
assert comments == []
captured = capsys.readouterr()
assert "WARNING: Failed to fetch comments" in captured.out
assert "kubeflow/docs-agent#9" in captured.out

def test_failed_second_page_keeps_first_page_and_warns(self, capsys):
def request_fn(url, params):
if params["page"] == 1:
return [_api_comment("a", "2026-01-01T00:00:00Z", "c0", "") for _ in range(100)]
return None

comments = fetch_issue_comments("kubeflow", "docs-agent", 9, request_fn)
assert len(comments) == 100
captured = capsys.readouterr()
assert "WARNING: Failed to fetch comments" in captured.out

def test_comment_segment_includes_url_when_present(self):
segments = issue_content_segments(SAMPLE_STRUCTURED_RECORD)
assert "https://github.com/kubeflow/kubeflow/issues/42#issuecomment-1001" in segments[1]
assert "https://github.com/kubeflow/kubeflow/issues/42#issuecomment-1002" in segments[2]

def test_comment_without_url_still_renders_old_format(self):
record = build_issue_record(
repo_name="kubeflow/kubeflow",
repo_short_name="kubeflow",
issue_number=42,
title="KServe model not loading",
url="https://github.com/kubeflow/kubeflow/issues/42",
labels="",
state="open",
created_at="2026-01-15",
updated_at="2026-01-20",
body="Body.",
comments=[{"author": "alice", "created_at": "2026-01-16", "body": "Hi."}],
)
segments = issue_content_segments(record)
assert segments[1] == "**Comment by @alice** (2026-01-16):\nHi."
assert "http" not in segments[1]

def test_format_issue_markdown_includes_comment_url(self):
md = format_issue_markdown(
title="T",
repo_name="kubeflow/docs-agent",
issue_number=9,
url="https://github.com/kubeflow/docs-agent/issues/9",
labels="",
state="open",
created_at="2026-01-30",
updated_at="2026-03-22",
body="Body.",
comments=[
{
"author": "alice",
"created_at": "2026-01-16",
"body": "Hi.",
"url": "https://github.com/kubeflow/docs-agent/issues/9#issuecomment-1001",
}
],
)
assert "https://github.com/kubeflow/docs-agent/issues/9#issuecomment-1001" in md