Skip to content

fix: recognize generated descriptions with leading content - #2667

Merged
IsmaelMartinez merged 2 commits into
The-PR-Agent:mainfrom
bunnysayzz:fix/description-self-recognition-2633
Aug 26, 2026
Merged

IsmaelMartinez merged 2 commits into
The-PR-Agent:mainfrom
bunnysayzz:fix/description-self-recognition-2633

Conversation

@bunnysayzz

Copy link
Copy Markdown
Contributor

Description

Fixes #2633. GitProvider._is_generated_by_pr_agent only recognized pr-agent output when the description started with one of the standard headers. If the model places anything above the first header (in the reported case, a one-line instruction leaked in via extra_instructions), recognition fails, the entire previous description including prior AI content is classified as user text, and the next /describe republishes it under ### **User description**. Each run adds one nesting layer, so descriptions grow without bound (74k characters observed, eventually crashing load_yaml in pr_description.py).

The fix recognizes generated output by its unique section markers (### **PR Type**, ### **PR Description**, ### **PR Labels**, ### 🤖 Generated by PR Agent) anywhere in the body, while keeping the startswith check for the generic headers. Only pr-agent-specific markers are matched anywhere, so a human description that merely contains a generic header like ### **Description** is not misclassified. get_user_description already extracts between the User description header and the next header, so leading noise is simply skipped and never re-embedded.

This is fix (b) from the issue (relax recognition), scoped to pr-agent-unique markers to avoid false positives on human-written descriptions.

Verification

  • New tests/unittest/test_git_provider_description_recognition.py (7 tests): regression tests for recognition with leading content, clean generated descriptions, plain user descriptions, generic-header-in-middle safety, and get_user_description extraction.
  • The two regression tests that cover the reported bug fail on the original code and pass with the fix.
  • Full unit suite: 1706 passed, 28 failed before and after the change (identical pre-existing failures in this environment: missing google-cloud-storage, litellm model-list drift, langfuse version behavior), so the change introduces zero new failures.

Impact: any pr-agent user on any provider (GitHub, GitLab, Bitbucket, etc.) whose generated description carries leading content. Existing already-grown descriptions stop growing on the next /describe; a fresh run produces a normal description.

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fix pr-agent generated-description detection with leading content

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Detect pr-agent generated PR bodies even when content appears before the first header.
• Prevent /describe from re-embedding prior AI output and growing descriptions unbounded.
• Add regression tests for recognition and user-description extraction edge cases.
Diagram

graph TD
  A[("PR description")]
  --> B["_is_generated_by_pr_agent()\n(startswith OR marker-in-body)"]
  --> C{"Generated?"}
  C -->|"No"| D["Return full text"] --> F["/describe publishes new body"]
  C -->|"Yes"| E["Extract 'User description' block"] --> F

  subgraph Legend
    direction LR
    _blob[(Text/blob)] ~~~ _proc["Process"] ~~~ _dec{Decision}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Skip leading noise then run existing startswith check
  • ➕ Keeps current header list as the single source of truth
  • ➕ Avoids scanning entire body for markers
  • ➖ Requires defining what counts as “noise” vs valid user content
  • ➖ More brittle when formatting changes (blank lines, markdown, comments)
2. Embed an explicit hidden sentinel token (HTML comment)
  • ➕ Most reliable self-recognition with near-zero false positives
  • ➕ Constant-time detection with startswith/contains on a single token
  • ➖ Requires guaranteeing the sentinel is always preserved by providers/UIs
  • ➖ Could leak into user-visible text if markdown rendering differs

Recommendation: The implemented approach (startswith for generic headers + contains search for pr-agent-unique markers) is a good balance: it fixes the leading-noise regression while limiting false positives on human-written descriptions that include generic headers mid-body. Alternatives add brittleness (noise skipping) or introduce new persistence constraints (sentinel token).

Files changed (2) +165 / -1

Bug fix (1) +17 / -1
git_provider.pyRecognize pr-agent output even with leading content +17/-1

Recognize pr-agent output even with leading content

• Extends _is_generated_by_pr_agent to detect pr-agent-specific section markers anywhere in the description when a strict startswith check fails. Retains the startswith behavior for generic headers to reduce false positives on human descriptions containing common headings mid-text.

pr_agent/git_providers/git_provider.py

Tests (1) +148 / -0
test_git_provider_description_recognition.pyAdd regression tests for description self-recognition and extraction +148/-0

Add regression tests for description self-recognition and extraction

• Introduces a minimal DummyGitProvider and test cases covering: clean generated descriptions, generated descriptions with leading noise, plain user descriptions, safety against generic headers inside user text, and correct get_user_description extraction behavior.

tests/unittest/test_git_provider_description_recognition.py

@qodo-code-review

qodo-code-review Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (4) 📜 Skill insights (0)

Grey Divider


Action required

1. Invalid YAML overwrites description ✓ Resolved 🐞 Bug ☼ Reliability
Description
When a truthy but malformed or whitespace-only model response makes load_yaml() return None,
_prepare_data() converts it to {} and allows the normal publication flow to continue instead of
aborting. The renderer then overwrites the existing generated description with only the preserved
user section, or just the hidden marker when no user text exists, discarding the prior AI-produced
content.
Code

pr_agent/tools/pr_description.py[R474-476]

+        if self.data is None:
+            get_logger().warning(f"Failed to parse prediction YAML, treating as empty")
+            self.data = {}
Relevance

●●● Strong

This is a concrete data-loss path; repository history favors defensive handling of malformed inputs
and failed processing.

PR-#2314

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
run() validates only that the raw prediction is truthy, calls _prepare_data(), and then proceeds
to prepare and publish the description. Because load_yaml() can return None after parsing and
fallback failure, the new conversion turns that failed result into an empty dictionary;
_prepare_pr_answer() then iterates no AI body fields and produces an empty pr_body, after which
the direct publication path prepends the hidden marker and overwrites the PR description.

pr_agent/algo/utils.py[772-787]
pr_agent/tools/pr_description.py[118-123]
pr_agent/tools/pr_description.py[598-665]
pr_agent/tools/pr_description.py[195-203]
pr_agent/tools/pr_description.py[116-137]
pr_agent/tools/pr_description.py[471-476]
pr_agent/tools/pr_description.py[616-665]
pr_agent/tools/pr_description.py[196-203]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A malformed or whitespace-only model response can make `load_yaml()` return `None`. Treating that failed parse as an empty dictionary lets `/describe` publish a replacement body with no generated sections, potentially erasing the existing AI-generated PR description and leaving only preserved user text or the hidden marker.

## Issue Context
`run()` executes `_prepare_data()` for every truthy model response and then continues through answer preparation and description publication. Reject the failed parse before rendering or publication while preserving the existing error-handling and cleanup behavior, and add a regression test proving that a truthy but unparsable prediction never invokes `publish_description`.

## Fix Focus Areas
- pr_agent/tools/pr_description.py[103-140]
- pr_agent/tools/pr_description.py[118-123]
- pr_agent/tools/pr_description.py[196-203]
- pr_agent/tools/pr_description.py[471-477]
- pr_agent/tools/pr_description.py[598-665]
- tests/unittest/test_git_provider_description_recognition.py[1-227]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Legacy descriptions still re-embedded ✓ Resolved 🐞 Bug ≡ Correctness
Description
Descriptions generated before this change have no hidden marker, so a leading instruction still
fails both the new marker check and the unchanged startswith check. /describe consequently
treats the complete old generated body as user text and republishes it inside a new User Description
section, adding the nesting layer the fix is intended to prevent.
Code

pr_agent/git_providers/git_provider.py[R326-327]

+        if '<!-- pr-agent-generated -->' in description_lowercase:
+            return True
Relevance

●● Moderate

The limitation is explicitly documented in the PR, but no close historical precedent resolves
whether compatibility is required.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The detection implementation only returns true for the newly written comment or for a header at byte
zero. The new regression fixture is a generated description with leading content and no marker, and
the added test verifies it returns false; get_user_description() returns any unrecognized
description verbatim as user text.

pr_agent/git_providers/git_provider.py[280-284]
pr_agent/git_providers/git_provider.py[326-333]
tests/unittest/test_git_provider_description_recognition.py[194-201]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Pre-marker PR-Agent descriptions with text before their first section remain unrecognized and are re-embedded on the next `/describe` run.

## Issue Context
The newly added test explicitly asserts that a leading-noise legacy generated description is not detected, despite this being the regression this PR is intended to resolve. Add recognition for unquoted, PR-Agent-specific visible section markers in legacy descriptions while preserving protection against quoted human content.

## Fix Focus Areas
- pr_agent/git_providers/git_provider.py[323-333]
- tests/unittest/test_git_provider_description_recognition.py[194-201]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. Imports missing blank line 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new test module mixes standard-library and first-party imports without a blank line between
sections. This violates the required isort-style import grouping and can cause lint failures under
the configured Ruff checks.
Code

tests/unittest/test_git_provider_description_recognition.py[R8-9]

+import types
+from pr_agent.git_providers.git_provider import GitProvider
Relevance

●●● Strong

Recent test-file precedents accept import/style lint corrections; standard-library and first-party
grouping is a deterministic Ruff fix.

PR-#2467
PR-#2587

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694656 requires standard-library and first-party imports to be separated into
ordered sections with a blank line. The new file places import types immediately followed by `from
pr_agent...` without an empty line.

Rule 2694656: Group Python imports according to isort sections and order
tests/unittest/test_git_provider_description_recognition.py[8-9]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new test file does not include a blank line between the standard-library import and the first-party import, violating the required isort section separation.

## Issue Context
Ruff is configured to enforce basic isort checks (I001/I002), and the compliance rule requires distinct import sections separated by a blank line.

## Fix Focus Areas
- tests/unittest/test_git_provider_description_recognition.py[8-10]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Line exceeds 120 characters 📘 Rule violation ⚙ Maintainability ⭐ New
Description
A newly added line in GitProvider._is_generated_by_pr_agent() exceeds the configured 120-character
maximum. This violates the Ruff line-length compliance requirement and may cause lint failures.
Code

pr_agent/git_providers/git_provider.py[346]

+        return any(description_lowercase.startswith(header) for header in possible_headers if header not in self._UNIQUE_PR_AGENT_HEADERS)
Relevance

●●● Strong

Recent repository precedents accept Ruff line-length fixes, including newly added long lines in
provider code.

PR-#2776
PR-#2424

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694655 requires no Python line exceed 120 characters (Ruff is configured with
line-length = 120). The return any(...) line added in git_provider.py is longer than 120
characters.

Rule 2694655: Enforce 120-character maximum line length in Python source per Ruff config
pyproject.toml[52-54]
pr_agent/git_providers/git_provider.py[346-346]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A newly added `return any(...)` expression is longer than 120 characters, exceeding the configured Ruff `line-length`.

## Issue Context
The repository Ruff configuration sets `line-length = 120`, and compliance requires all changed Python lines to respect this limit.

## Fix Focus Areas
- pr_agent/git_providers/git_provider.py[343-346]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Warning message triggers F541 ⊘ Outdated 📘 Rule violation ✧ Quality
Description
The warning uses an f-string without any replacement fields, which triggers the enabled Pyflakes
F541 diagnostic. The modified Python code therefore cannot pass the configured lint checks with
zero warnings.
Code

pr_agent/tools/pr_description.py[475]

+            get_logger().warning(f"Failed to parse prediction YAML, treating as empty")
Relevance

●●● Strong

An exact recent precedent accepted removing an interpolation-free f-string to resolve F541 lint
failure.

PR-#2314

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Compliance rule 2694666 requires zero lint errors or warnings in changed Python code; the newly
added interpolation-free f-string is an F541 violation under the configured F checks.

Rule 2694666: Python code must pass flake8 in CI with zero errors or warnings
pr_agent/tools/pr_description.py[475-475]
pyproject.toml[52-60]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new warning message is an f-string with no interpolation and triggers `F541`.

## Issue Context
Use a normal double-quoted string because the message contains no replacement fields.

## Fix Focus Areas
- pr_agent/tools/pr_description.py[475-475]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (4)
6. Marker uses single quotes 📘 Rule violation ⚙ Maintainability
Description
The generated-description marker is written as a single-quoted Python string even though double
quotes require no escaping. This violates the repository-wide string literal convention.
Code

pr_agent/git_providers/git_provider.py[326]

+        if '<!-- pr-agent-generated -->' in description_lowercase:
Relevance

●● Moderate

Recent style precedents conflict: similar quote fixes were accepted, but same-file style feedback
was rejected.

PR-#2679
PR-#2598

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Compliance rule 2694657 requires double quotes for Python string literals unless double quotes would
require additional escaping; the newly added marker literal has no such constraint.

Rule 2694657: Use double quotes for all Python string literals
pr_agent/git_providers/git_provider.py[326-326]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The generated-description marker uses a single-quoted Python string, contrary to the required double-quote convention.

## Issue Context
The literal contains no double quotes that would justify an exception.

## Fix Focus Areas
- pr_agent/git_providers/git_provider.py[326-326]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Prepended marker uses single quotes 📘 Rule violation ⚙ Maintainability
Description
The marker prepended to pr_body is a single-quoted Python string despite requiring no double-quote
escaping. This violates the required string literal style.
Code

pr_agent/tools/pr_description.py[202]

+                    pr_body = '<!-- pr-agent-generated -->\n' + pr_body
Relevance

●● Moderate

Recent quote-style feedback is mixed, including rejection of comparable touched code despite the
repository convention.

PR-#2679
PR-#2598
PR-#2212

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Compliance rule 2694657 requires double-quoted Python literals, while the added pr_body assignment
uses single quotes without an escaping justification.

Rule 2694657: Use double quotes for all Python string literals
pr_agent/tools/pr_description.py[202-202]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The marker prepended to `pr_body` uses a single-quoted Python string, contrary to the required double-quote convention.

## Issue Context
Changing the delimiters does not alter the marker or newline content.

## Fix Focus Areas
- pr_agent/tools/pr_description.py[202-202]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


8. Comments use descriptive phrasing ⊘ Outdated 📘 Rule violation ⚙ Maintainability
Description
The newly added block comments describe behavior narratively (for example, `The generated
description may carry...`) rather than using imperative commands as required. This violates the
imperative-phrasing rule for comments and docstrings.
Code

pr_agent/git_providers/git_provider.py[R319-322]

+        # The generated description may carry leading content above the first standard
+        # header (e.g. a line the model was instructed to emit via `extra_instructions`).
+        # A plain `startswith` check then fails, the previous AI output gets classified as
+        # user text, and the next /describe re-embeds it under "User description", growing
Evidence
The checklist requires newly added behavior comments to be phrased as commands or instructions. The
cited diff adds comments beginning with descriptive statements such as `The generated description
may carry and A plain startswith check then fails`, which do not follow that requirement.

Rule 2694688: Docstrings and comments must use imperative phrasing
pr_agent/git_providers/git_provider.py[319-322]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
New comments in the generated-description recognition logic use descriptive narrative phrasing instead of imperative phrasing.

## Issue Context
The compliance rule requires behavior-describing comments and docstrings to use commands such as `Recognize`, `Avoid`, or `Prevent` rather than statements such as `The generated description may...`.

## Fix Focus Areas
- pr_agent/git_providers/git_provider.py[319-322]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. Substring markers misclassify user text ✓ Resolved 🐞 Bug ≡ Correctness
Description
The new in checks treat any occurrence of a PR-Agent marker as proof that the entire body was
generated, including human text that quotes or discusses ### **PR Description** or `### **PR
Type**. get_user_description()` then enters the generated branch and returns an empty string when
no User description section exists, silently dropping the user's actual description on the next
/describe.
Code

pr_agent/git_providers/git_provider.py[R327-333]

+        pr_agent_markers = (
+            "### **pr type**",
+            "### **pr description**",
+            "### **pr labels**",
+            "### 🤖 generated by pr agent",
+        )
+        return any(marker in description_lowercase for marker in pr_agent_markers)
Evidence
The changed code searches for each marker anywhere in the lowercase body. The existing downstream
logic treats a positive result as generated and returns an empty string if the body has no User
description header, so an exact marker quoted in normal user text causes data loss.

pr_agent/git_providers/git_provider.py[327-333]
pr_agent/git_providers/git_provider.py[273-285]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The marker detection uses unbounded substring matching, so a human-authored description containing a quoted or embedded PR-Agent header is classified as generated. If it lacks a User description section, `get_user_description()` returns an empty string and loses the human text.

## Issue Context
Recognition must allow leading content before actual generated sections, but should not match marker text embedded inside prose, quotations, or code blocks.

## Fix Focus Areas
- pr_agent/git_providers/git_provider.py[327-333]
- pr_agent/git_providers/git_provider.py[273-285]

Use line-anchored, complete-header matching with suitable whitespace/boundary handling, and add a regression test proving that a human description containing a quoted marker is preserved.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Context sources
✅ Compliance rules (platform): 34 rules
Review mode: ⚖️ Balanced

Grey Divider

Tip of the day
💡 Did you know, you can start a comment with 'qodo' or '@qodo' to chat about any finding

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 187398c

Results up to commit 00ec8aa 🚀 Fast


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 📜 Skill insights (0)


Remediation recommended
1. Substring markers misclassify user text ✓ Resolved 🐞 Bug ≡ Correctness
Description
The new in checks treat any occurrence of a PR-Agent marker as proof that the entire body was
generated, including human text that quotes or discusses ### **PR Description** or `### **PR
Type**. get_user_description()` then enters the generated branch and returns an empty string when
no User description section exists, silently dropping the user's actual description on the next
/describe.
Code

pr_agent/git_providers/git_provider.py[R327-333]

+        pr_agent_markers = (
+            "### **pr type**",
+            "### **pr description**",
+            "### **pr labels**",
+            "### 🤖 generated by pr agent",
+        )
+        return any(marker in description_lowercase for marker in pr_agent_markers)
Evidence
The changed code searches for each marker anywhere in the lowercase body. The existing downstream
logic treats a positive result as generated and returns an empty string if the body has no User
description header, so an exact marker quoted in normal user text causes data loss.

pr_agent/git_providers/git_provider.py[327-333]
pr_agent/git_providers/git_provider.py[273-285]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The marker detection uses unbounded substring matching, so a human-authored description containing a quoted or embedded PR-Agent header is classified as generated. If it lacks a User description section, `get_user_description()` returns an empty string and loses the human text.

## Issue Context
Recognition must allow leading content before actual generated sections, but should not match marker text embedded inside prose, quotations, or code blocks.

## Fix Focus Areas
- pr_agent/git_providers/git_provider.py[327-333]
- pr_agent/git_providers/git_provider.py[273-285]

Use line-anchored, complete-header matching with suitable whitespace/boundary handling, and add a regression test proving that a human description containing a quoted marker is preserved.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Comments use descriptive phrasing ⊘ Outdated 📘 Rule violation ⚙ Maintainability
Description
The newly added block comments describe behavior narratively (for example, `The generated
description may carry...`) rather than using imperative commands as required. This violates the
imperative-phrasing rule for comments and docstrings.
Code

pr_agent/git_providers/git_provider.py[R319-322]

+        # The generated description may carry leading content above the first standard
+        # header (e.g. a line the model was instructed to emit via `extra_instructions`).
+        # A plain `startswith` check then fails, the previous AI output gets classified as
+        # user text, and the next /describe re-embeds it under "User description", growing
Evidence
The checklist requires newly added behavior comments to be phrased as commands or instructions. The
cited diff adds comments beginning with descriptive statements such as `The generated description
may carry and A plain startswith check then fails`, which do not follow that requirement.

Rule 2694688: Docstrings and comments must use imperative phrasing
pr_agent/git_providers/git_provider.py[319-322]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
New comments in the generated-description recognition logic use descriptive narrative phrasing instead of imperative phrasing.

## Issue Context
The compliance rule requires behavior-describing comments and docstrings to use commands such as `Recognize`, `Avoid`, or `Prevent` rather than statements such as `The generated description may...`.

## Fix Focus Areas
- pr_agent/git_providers/git_provider.py[319-322]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit 27872a8 🧠 Deep


🐞 Bugs (0) 📘 Rule violations (2) 📎 Requirement gaps (0) 🎨 UX issues (0) 📜 Skill insights (0)


Action required
1. Invalid YAML overwrites description ✓ Resolved 🐞 Bug ☼ Reliability
Description
When a truthy but malformed or whitespace-only model response makes load_yaml() return None,
_prepare_data() converts it to {} and allows the normal publication flow to continue instead of
aborting. The renderer then overwrites the existing generated description with only the preserved
user section, or just the hidden marker when no user text exists, discarding the prior AI-produced
content.
Code

pr_agent/tools/pr_description.py[R474-476]

+        if self.data is None:
+            get_logger().warning(f"Failed to parse prediction YAML, treating as empty")
+            self.data = {}
Relevance

●●● Strong

This is a concrete data-loss path; repository history favors defensive handling of malformed inputs
and failed processing.

PR-#2314

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
run() validates only that the raw prediction is truthy, calls _prepare_data(), and then proceeds
to prepare and publish the description. Because load_yaml() can return None after parsing and
fallback failure, the new conversion turns that failed result into an empty dictionary;
_prepare_pr_answer() then iterates no AI body fields and produces an empty pr_body, after which
the direct publication path prepends the hidden marker and overwrites the PR description.

pr_agent/algo/utils.py[772-787]
pr_agent/tools/pr_description.py[118-123]
pr_agent/tools/pr_description.py[598-665]
pr_agent/tools/pr_description.py[195-203]
pr_agent/tools/pr_description.py[116-137]
pr_agent/tools/pr_description.py[471-476]
pr_agent/tools/pr_description.py[616-665]
pr_agent/tools/pr_description.py[196-203]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A malformed or whitespace-only model response can make `load_yaml()` return `None`. Treating that failed parse as an empty dictionary lets `/describe` publish a replacement body with no generated sections, potentially erasing the existing AI-generated PR description and leaving only preserved user text or the hidden marker.

## Issue Context
`run()` executes `_prepare_data()` for every truthy model response and then continues through answer preparation and description publication. Reject the failed parse before rendering or publication while preserving the existing error-handling and cleanup behavior, and add a regression test proving that a truthy but unparsable prediction never invokes `publish_description`.

## Fix Focus Areas
- pr_agent/tools/pr_description.py[103-140]
- pr_agent/tools/pr_description.py[118-123]
- pr_agent/tools/pr_description.py[196-203]
- pr_agent/tools/pr_description.py[471-477]
- pr_agent/tools/pr_description.py[598-665]
- tests/unittest/test_git_provider_description_recognition.py[1-227]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Legacy descriptions still re-embedded ✓ Resolved 🐞 Bug ≡ Correctness
Description
Descriptions generated before this change have no hidden marker, so a leading instruction still
fails both the new marker check and the unchanged startswith check. /describe consequently
treats the complete old generated body as user text and republishes it inside a new User Description
section, adding the nesting layer the fix is intended to prevent.
Code

pr_agent/git_providers/git_provider.py[R326-327]

+        if '<!-- pr-agent-generated -->' in description_lowercase:
+            return True
Relevance

●● Moderate

The limitation is explicitly documented in the PR, but no close historical precedent resolves
whether compatibility is required.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The detection implementation only returns true for the newly written comment or for a header at byte
zero. The new regression fixture is a generated description with leading content and no marker, and
the added test verifies it returns false; get_user_description() returns any unrecognized
description verbatim as user text.

pr_agent/git_providers/git_provider.py[280-284]
pr_agent/git_providers/git_provider.py[326-333]
tests/unittest/test_git_provider_description_recognition.py[194-201]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Pre-marker PR-Agent descriptions with text before their first section remain unrecognized and are re-embedded on the next `/describe` run.

## Issue Context
The newly added test explicitly asserts that a leading-noise legacy generated description is not detected, despite this being the regression this PR is intended to resolve. Add recognition for unquoted, PR-Agent-specific visible section markers in legacy descriptions while preserving protection against quoted human content.

## Fix Focus Areas
- pr_agent/git_providers/git_provider.py[323-333]
- tests/unittest/test_git_provider_description_recognition.py[194-201]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended
3. Warning message triggers F541 ⊘ Outdated 📘 Rule violation ✧ Quality
Description
The warning uses an f-string without any replacement fields, which triggers the enabled Pyflakes
F541 diagnostic. The modified Python code therefore cannot pass the configured lint checks with
zero warnings.
Code

pr_agent/tools/pr_description.py[475]

+            get_logger().warning(f"Failed to parse prediction YAML, treating as empty")
Relevance

●●● Strong

An exact recent precedent accepted removing an interpolation-free f-string to resolve F541 lint
failure.

PR-#2314

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Compliance rule 2694666 requires zero lint errors or warnings in changed Python code; the newly
added interpolation-free f-string is an F541 violation under the configured F checks.

Rule 2694666: Python code must pass flake8 in CI with zero errors or warnings
pr_agent/tools/pr_description.py[475-475]
pyproject.toml[52-60]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new warning message is an f-string with no interpolation and triggers `F541`.

## Issue Context
Use a normal double-quoted string because the message contains no replacement fields.

## Fix Focus Areas
- pr_agent/tools/pr_description.py[475-475]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Marker uses single quotes 📘 Rule violation ⚙ Maintainability
Description
The generated-description marker is written as a single-quoted Python string even though double
quotes require no escaping. This violates the repository-wide string literal convention.
Code

pr_agent/git_providers/git_provider.py[326]

+        if '<!-- pr-agent-generated -->' in description_lowercase:
Relevance

●● Moderate

Recent style precedents conflict: similar quote fixes were accepted, but same-file style feedback
was rejected.

PR-#2679
PR-#2598

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Compliance rule 2694657 requires double quotes for Python string literals unless double quotes would
require additional escaping; the newly added marker literal has no such constraint.

Rule 2694657: Use double quotes for all Python string literals
pr_agent/git_providers/git_provider.py[326-326]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The generated-description marker uses a single-quoted Python string, contrary to the required double-quote convention.

## Issue Context
The literal contains no double quotes that would justify an exception.

## Fix Focus Areas
- pr_agent/git_providers/git_provider.py[326-326]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Prepended marker uses single quotes 📘 Rule violation ⚙ Maintainability
Description
The marker prepended to pr_body is a single-quoted Python string despite requiring no double-quote
escaping. This violates the required string literal style.
Code

pr_agent/tools/pr_description.py[202]

+                    pr_body = '<!-- pr-agent-generated -->\n' + pr_body
Relevance

●● Moderate

Recent quote-style feedback is mixed, including rejection of comparable touched code despite the
repository convention.

PR-#2679
PR-#2598
PR-#2212

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Compliance rule 2694657 requires double-quoted Python literals, while the added pr_body assignment
uses single quotes without an escaping justification.

Rule 2694657: Use double quotes for all Python string literals
pr_agent/tools/pr_description.py[202-202]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The marker prepended to `pr_body` uses a single-quoted Python string, contrary to the required double-quote convention.

## Issue Context
Changing the delimiters does not alter the marker or newline content.

## Fix Focus Areas
- pr_agent/tools/pr_description.py[202-202]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread pr_agent/git_providers/git_provider.py Resolved
@bunnysayzz
bunnysayzz force-pushed the fix/description-self-recognition-2633 branch from 00ec8aa to 27872a8 Compare August 19, 2026 16:02
bunnysayzz added a commit to bunnysayzz/pr-agent that referenced this pull request Aug 19, 2026
…ml crash

Three changes addressing maintainer feedback on The-PR-Agent#2667:

1. Hidden HTML comment injected at write time in pr_description.py.
Detection checks for it anywhere in the body first (fast path), then
falls back to startswith against the standard header list. This avoids
the false-positive of matching visible headers anywhere.

2. Removed fallback that matched visible pr-agent headers anywhere.
With the hidden marker as primary signal, this caused false positives
when human text quoted a pr-agent header (IsmaelMartinez review Aug 18).

3. Fixed load_yaml crash: _prepare_data now handles None return from
load_yaml (the other half of The-PR-Agent#2633). Returns empty dict instead of
crashing with TypeError.

11 tests pass; full unit suite 1947 passed, 0 new failures.

Fixes The-PR-Agent#2633
@bunnysayzz

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @IsmaelMartinez. Reworked per your feedback:

1. Hidden HTML marker instead of matching visible headers anywhere. A <!-- pr-agent-generated --> comment is now injected at write time in pr_description.py before publish_description(). Detection checks for it anywhere in the body (fast path), then falls back to startswith against the standard header list. This avoids the false-positive you flagged: human text quoting ### **PR Type** in a blockquote is no longer misclassified as generated.

2. Removed the visible-header-anywhere fallback. With the hidden marker as the primary signal, matching visible pr-agent headers anywhere is no longer needed and was the source of the false positive.

3. Fixed load_yaml crash (the other half of #2633). _prepare_data now handles None return from load_yaml gracefully, returning an empty dict instead of crashing with TypeError.

Verification: 11 tests in test_git_provider_description_recognition.py (all pass), including:

  • Hidden marker detected anywhere in body
  • Hidden marker with leading noise still detected
  • Human text quoting ### **PR Type** in blockquote is NOT misclassified
  • Legacy descriptions (no marker, starts with header) still detected
  • get_user_description extraction works with hidden marker

Full unit suite: 1947 passed, 0 new failures.

Comment thread pr_agent/tools/pr_description.py Resolved
Comment thread pr_agent/git_providers/git_provider.py Resolved
@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 27872a8

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Green and the tests bite, but I do not think this does what the title says. Running _is_generated_by_pr_agent over a few shapes, a description with a leading blank line or a leading sentence is still not recognised, before and after. The marker only helps descriptions published after this lands, so nothing already out there changes.

Could the visible-header path tolerate leading content too, rather than the marker alone? The load_yaml None guard looks right but would be cleaner as its own PR.

Thanks for contributing!

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

A correction to my note above: the leading blank line case does work, because get_user_description strips before matching; my probe called the private method directly and skipped that. The leading sentence case stands though, still not recognised before and after this change, and that is the ratchet case from #2633. So the ask is unchanged: tolerate leading content in the visible-header path.

…he-PR-Agent#2667)

Two changes addressing maintainer feedback on The-PR-Agent#2667:

1. Hidden HTML comment injected at write time in pr_description.py.
Detection checks for it anywhere in the body first (fast path), then
falls back to header matching. This catches new pr-agent output
regardless of leading content.

2. Visible-header detection tolerates leading content for headers
unique to pr-agent (PR Type, PR Description, etc.) by using `in`
instead of `startswith`. Generic headers (Description, Type, Labels)
still require startswith to avoid misclassifying human descriptions
that happen to contain these common markdown headings.

The load_yaml None guard from the original The-PR-Agent#2667 commit is
intentionally excluded per maintainer request to split it into
its own PR.

23 new tests cover: hidden marker detection, leading-content
tolerance, generic header startswith enforcement, and edge cases.
Full suite: 2213 passed, zero failures.

Fixes The-PR-Agent#2633
@bunnysayzz
bunnysayzz force-pushed the fix/description-self-recognition-2633 branch from 27872a8 to 464d00b Compare August 25, 2026 10:22
@bunnysayzz

Copy link
Copy Markdown
Contributor Author

Reworked per your feedback. Two changes:

  1. Visible-header tolerance: _is_generated_by_pr_agent now matches pr-agent-unique headers (### PR Type, ### PR Description, ### PR Labels, ### User Description, and the robot-generated marker) anywhere in the body with in, not just startswith. This catches the leading-sentence case you flagged. Generic headers (### Description, ### Type, ### Labels) still require startswith to avoid false positives when a human description quotes them.

  2. Hidden marker: <!-- pr-agent-generated --> injected at write time, checked anywhere as a fast path.

The load_yaml None guard is excluded from this commit per your request to split it into its own PR.

23 new tests cover: hidden marker detection, leading-content tolerance for each unique header, generic header startswith enforcement, and edge cases. Full suite 2213 passed, zero failures.

PR head updated to 464d00b.

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 464d00b

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for reworking this, and the hidden marker is the right mechanism.

The visible-header half needs one more turn. Qodo's finding 5 asked for recognition of unquoted markers "while preserving protection against quoted human content"; the anywhere-match delivers the first half and drops the second. A description that quotes our headers is now read as ours, and get_user_description returns '', so the text is dropped on the next describe.

What the suggestion cannot close is a verbatim paste with the header on its own line, since that is byte-identical to a legacy description with a line prepended. The marker is what settles those going forward.

Comment on lines +340 to +342
for header in possible_headers:
if header in self._UNIQUE_PR_AGENT_HEADERS and header in description_lowercase:
return True

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requiring the header to start its own line keeps the ratchet fix and stops a quoted copy counting. It closes the blockquote, inline-backtick and indented cases; your 23 tests stay green and the suite stays at 2273.

Suggested change
for header in possible_headers:
if header in self._UNIQUE_PR_AGENT_HEADERS and header in description_lowercase:
return True
for header in possible_headers:
if header in self._UNIQUE_PR_AGENT_HEADERS and (
description_lowercase.startswith(header)
or ("\n" + header) in description_lowercase):
return True

Matching the unique headers anywhere meant a human description that quotes
them was read as generated, so get_user_description returned '' and their
text was dropped on the next describe. Requiring the header at line start
keeps the leading-content fix and ignores quoted copies.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 187398c

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed the line-start variant myself rather than leave you another round: the unique headers now have to start their own line, so a quoted copy is not read as ours. Your 23 tests still pass and I added four guards.

Thanks for the rework, the hidden marker is the right mechanism and it is what makes this safe going forward.

@IsmaelMartinez
IsmaelMartinez merged commit ba56b92 into The-PR-Agent:main Aug 26, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GitLab: self-recognition of generated descriptions is brittle, any leading content causes unbounded recursive re-embedding

2 participants