Skip to content

feat: add secure per-review model selection - #2818

Closed
elijahchancey wants to merge 6 commits into
The-PR-Agent:mainfrom
elijahchancey:feature/command-model-overrides
Closed

elijahchancey wants to merge 6 commits into
The-PR-Agent:mainfrom
elijahchancey:feature/command-model-overrides

Conversation

@elijahchancey

@elijahchancey elijahchancey commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add concise /review alias+effort syntax, for example /review fable+high
  • resolve one operator-configured alias and apply it through the existing config.model and config.reasoning_effort path
  • keep the existing reviewer constructor, AI handlers, retry loop, fallback models, and run-details behavior unchanged

Scope

Each review accepts at most one selector. The selector changes the primary model and effort for that invocation; the installation's normal configured fallback behavior still applies.

The feature is disabled by default. Alias enablement and mappings are global-only so a reviewed repository cannot redefine operator-managed shorthand. This PR does not change permissions or behavior for the existing config.model and fallback_models settings.

[pr_reviewer]
enable_command_model_aliases = true
command_model_aliases.fable = "anthropic/claude-fable-5"
command_model_aliases.terra = "gpt-5.6-terra"

Explicit non-goals

  • no caller-defined fallback chains
  • no per-attempt ContextVar or AI-handler integration
  • no reviewer-constructor or retry-loop changes
  • no new run-details fields
  • no restriction of the existing model configuration route

Validation

  • 124 focused selector, settings-security, CLI-security, routing, and Claude adaptive-thinking tests passed
  • Ruff passed on all changed Python files
  • pre-commit passed on all changed files
  • git diff --check passed

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Add secure per-review model and effort selection

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Adds allowlisted alias-and-effort selectors with ordered, request-scoped review fallbacks.
• Rejects untrusted overrides before reviewer construction and preserves existing review behavior.
• Propagates successful effort metadata across handlers, run details, documentation, and tests.
Diagram

graph TD
  A["Review command"] --> B["Request handler"] --> C["Selector parser"] --> D["PR reviewer"] --> E["Fallback runner"] --> F["AI handlers"] --> G["Run details"]
  H["Trusted allowlist"] --> C
Loading
High-Level Assessment

The request-scoped typed selection and trusted alias allowlist are the appropriate design. Mutating global model settings would risk cross-request leakage, while accepting raw provider IDs would weaken operator cost controls; both are correctly avoided.

Files changed (18) +782 / -54

Enhancement (9) +294 / -44
pr_agent.pyValidate selectors before review dispatch +42/-1

Validate selectors before review dispatch

• Parses /review selectors before constructing the reviewer, publishes actionable validation errors, and passes valid typed selections only through the review command path. The original constructor path remains unchanged when selectors are absent.

pr_agent/agent/pr_agent.py

langchain_ai_handler.pyForward selected effort through LangChain +14/-6

Forward selected effort through LangChain

• Adds the active request-scoped reasoning effort to OpenAI-compatible LangChain invocations without changing simplified non-OpenAI calls.

pr_agent/algo/ai_handlers/langchain_ai_handler.py

litellm_ai_handler.pyApply command effort across LiteLLM models +22/-4

Apply command effort across LiteLLM models

• Prioritizes the active command effort over configured reasoning settings and forwards it even for allowlisted models outside built-in detection lists. It also prevents conflicting Claude extended-thinking and OpenRouter reasoning configuration during selected attempts.

pr_agent/algo/ai_handlers/litellm_ai_handler.py

openai_ai_handler.pyForward selected effort to OpenAI +10/-3

Forward selected effort to OpenAI

• Adds the active request-scoped reasoning effort to OpenAI chat completion arguments when a review selector is in effect.

pr_agent/algo/ai_handlers/openai_ai_handler.py

pr_processing.pyExecute ordered request-scoped model fallbacks +30/-6

Execute ordered request-scoped model fallbacks

• Extends fallback execution to accept explicit typed selections, activate each selection only around its attempt, and retain the existing configured chain otherwise. Successful model telemetry now includes the paired reasoning effort.

pr_agent/algo/pr_processing.py

review_model_selection.pyAdd typed secure review model selection +139/-0

Add typed secure review model selection

• Introduces immutable model selections, strict alias+effort parsing, actionable validation errors, and ContextVar-based attempt scoping. Only enabled, operator-allowlisted aliases and supported effort values can resolve to provider model IDs.

pr_agent/algo/review_model_selection.py

run_details.pyRecord successful review reasoning effort +6/-1

Record successful review reasoning effort

• Extends run metadata to retain the request-scoped effort associated with the model that produced a successful completion.

pr_agent/algo/run_details.py

utils.pyRender reasoning effort in run details +2/-0

Render reasoning effort in run details

• Displays reasoning effort when selected-command telemetry recorded one, leaving ordinary command output unchanged.

pr_agent/algo/utils.py

pr_reviewer.pyCarry selections into review fallback execution +29/-23

Carry selections into review fallback execution

• Accepts ordered typed model selections on the reviewer and routes them into fallback prediction while preserving the existing execution path when none are provided.

pr_agent/tools/pr_reviewer.py

Tests (3) +405 / -0
test_apply_repo_settings_security.pyTest trusted configuration isolation +54/-0

Test trusted configuration isolation

• Verifies local repositories cannot enable overrides or replace aliases, while organization-level global settings remain authoritative.

tests/unittest/test_apply_repo_settings_security.py

test_review_model_selection.pyCover selector security and execution behavior +341/-0

Cover selector security and execution behavior

• Adds comprehensive tests for parsing, validation, fallback ordering, effort propagation, context isolation, command compatibility, help text, and early error publication. It also confirms comment arguments cannot modify operator controls.

tests/unittest/test_review_model_selection.py

test_show_run_details.pyTest fallback effort rendering +10/-0

Test fallback effort rendering

• Verifies run details show both the successful fallback model and its associated reasoning effort.

tests/unittest/test_show_run_details.py

Documentation (3) +39 / -2
review.mdDocument per-review selector syntax and security model +30/-0

Document per-review selector syntax and security model

• Documents alias+effort syntax, ordered fallback behavior, trusted global configuration, supported effort values, cost implications, and ephemeral scope.

docs/docs/tools/review.md

additional_configurations.mdExplain reasoning effort in run details +2/-1

Explain reasoning effort in run details

• Updates the run-details example and explains that the displayed effort belongs to the model that successfully completed the review, including fallbacks.

docs/docs/usage-guide/additional_configurations.md

help.pyAdvertise review model selectors in help +7/-1

Advertise review model selectors in help

• Updates command help and the review usage guide with ordered alias+effort syntax and operator allowlist requirements.

pr_agent/servers/help.py

Other (3) +44 / -8
cli_args.pyProtect override controls from comment arguments +19/-6

Protect override controls from comment arguments

• Adds model-override enablement and alias settings to the forbidden command configuration list, preventing PR comments from modifying operator controls. The encoded argument list is reformatted for maintainability.

pr_agent/algo/cli_args.py

utils.pyKeep override settings globally controlled +20/-2

Keep override settings globally controlled

• Marks model-override enablement and aliases as global-only settings and filters them from local repository configuration while allowing organization-level global settings.

pr_agent/git_providers/utils.py

configuration.tomlAdd disabled-by-default override configuration +5/-0

Add disabled-by-default override configuration

• Defines global model override enablement and alias mapping defaults, both disabled or empty until explicitly configured by an operator.

pr_agent/settings/configuration.toml

@qodo-code-review

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

Copy link
Copy Markdown
Contributor

Code Review by Qodo

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

⚠️ 3 lower-priority findings omitted to fit the comment size limit; re-run the review or view the findings in the Qodo portal.

Grey Divider


Action required

1. Concurrent reviews swap selected models 📘 Rule violation ☼ Reliability ⭐ New
Description
_run_command snapshots and mutates the get_settings() object before awaiting command execution,
then unconditionally restores its snapshot in finally. When callers run without an installed
request context, overlapping reviews share global_settings, so one task can execute with another
task's selector and the last cleanup can restore a stale model.
Code

pr_agent/agent/pr_agent.py[R340-342]

+                settings.set("CONFIG.MODEL", model_selection.model)
+                settings.set("CONFIG.REASONING_EFFORT", model_selection.reasoning_effort)
+                settings.set("MODEL_ROUTING.ENABLE", False)
Evidence
Compliance rule 3 requires edge cases and errors to be handled gracefully. The changed command path
holds temporary model settings across an await and restores an earlier snapshot, while
get_settings() falls back to a shared global object when no request context exists; no
synchronization prevents overlapping calls from overwriting or restoring each other's values.

Rule 3: Robust Error Handling
pr_agent/agent/pr_agent.py[323-374]
pr_agent/config_loader.py[50-63]

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

## Issue description
Temporary model-selection settings are mutated on a potentially shared settings object across an awaited review, allowing concurrent commands to interfere with execution and cleanup.

## Fix Focus Areas
- pr_agent/agent/pr_agent.py[323-374]
- pr_agent/config_loader.py[50-63]

## Recommended Fix
Give each command invocation an isolated context-local settings copy before applying selector overrides, and keep snapshot restoration within that isolated context. Add an asynchronous overlap test proving two selectors retain their own model and leave the baseline settings unchanged.

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


2. Command dispatch owns unrelated work 📘 Rule violation ⚙ Maintainability ⭐ New
Description
_run_command now parses selector configuration, emits rejection responses and telemetry, scopes
four settings, and dispatches all command classes. A change to selector validation, cleanup, or
ordinary dispatch must edit the same exception path, so these independently evolving behaviors
cannot be tested or changed in isolation.
Code

pr_agent/agent/pr_agent.py[R298-301]

+        model_selection = None
+        if action == "review":
+            try:
+                settings = get_settings()
Evidence
Compliance rule 4 requires each function to perform one cohesive task. The additions place selector
parsing and error publication at the beginning of _run_command, settings mutation and restoration
around its existing command-dispatch responsibility, and telemetry handling within the same control
flow.

Rule 4: Single Responsibility for Functions
pr_agent/agent/pr_agent.py[298-374]

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 command dispatcher now combines selector resolution, rejection handling, temporary settings management, telemetry, and command execution.

## Fix Focus Areas
- pr_agent/agent/pr_agent.py[298-374]

## Recommended Fix
Extract selector resolution and rejection handling into one helper and temporary model settings into a dedicated context manager. Leave `_run_command` responsible for selecting and invoking the command while preserving the existing telemetry and cleanup behavior.

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


3. Minimal Claude reviews ignore effort 🐞 Bug ≡ Correctness ⭐ New
Description
parse_review_model_selection accepts minimal for every alias even though the adaptive Claude
request path cannot transmit that effort. With the shipped fable alias, /review fable+minimal
enables adaptive thinking but sends neither an output effort nor a generic reasoning effort, so the
provider chooses its default instead.
Code

pr_agent/algo/review_model_selection.py[R161-162]

+        try:
+            effort = ReasoningEffort(effort).value
Evidence
minimal is part of the accepted enum and the parser accepts all enum values. The shipped fable
alias resolves to an adaptive Claude model, and dispatch enables adaptive thinking, but the handler
only adds output_config for low, medium, high, xhigh, and max; Fable is also absent from the
generic reasoning-model registry, leaving the selected effort absent from the request.

pr_agent/algo/utils.py[207-214]
pr_agent/settings/configuration.toml[121-124]
pr_agent/agent/pr_agent.py[339-344]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[3563-3579]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[3903-3924]

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 selector accepts `minimal` for adaptive Claude aliases, but the Claude adaptive-thinking handler does not transmit that value. The review therefore runs with provider-default effort rather than the caller's selected effort.

## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[161-171]
- pr_agent/agent/pr_agent.py[339-344]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[3571-3579]

## Recommended Fix
Validate model-specific effort compatibility before executing the review. For recognized adaptive Claude models, reject `minimal` with an actionable selector error unless the handler is changed to support an explicit, semantically equivalent provider value; add an integration test covering `/review fable+minimal`.

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


View high (5)
4. Bad disabled selectors run reviews 📘 Rule violation ≡ Correctness
Description
parse_review_model_selection builds configured_selector_tokens only from tokens whose effort is
already valid, so it skips a configured alias with a malformed effort while aliases are disabled. A
command such as /review fable+extreme reaches reviewer construction as ordinary instructions
instead of the disabled-feature response, despite targeting the operator's known alias.
Code

pr_agent/algo/review_model_selection.py[R103-106]

+        configured_alias_names = _get_configured_alias_names(config.aliases)
+        configured_selector_tokens = [
+            arg for arg in selector_tokens if _split_selector(arg)[0] in configured_alias_names
+        ]
Evidence
Compliance rule 3 requires edge cases to be handled gracefully. The disabled-feature branch filters
candidate tokens through _is_selector_shaped before checking configured alias names, while the
user documentation states that a token whose alias part matches a configured alias produces the
disabled-feature error.

Rule 3: Robust Error Handling
pr_agent/algo/review_model_selection.py[101-112]
docs/docs/tools/review.md[69-71]

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

## Issue description
When command model aliases are disabled, configured aliases are recognized only if their effort is valid. Malformed uses such as `/review fable+extreme` therefore proceed as ordinary review arguments instead of producing the disabled-feature error.
## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[102-112]
- tests/unittest/test_review_model_selection.py[125-143]
## Recommended Fix
In the disabled branch, identify tokens whose alias portion matches a configured alias before filtering by valid effort, and reject those tokens with the disabled-feature error. Add coverage for a configured alias paired with an unsupported effort and malformed separators while preserving unrelated plus-containing arguments.

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


5. Repositories can load attacker aliases 🐞 Bug ⛨ Security
Description
_apply_repo_settings_file protects the two alias keys but still permits a local repository to set
CONFIG.EXTRA_CONFIG_URL, whose target is later merged without the local-key restrictions. When
settings are applied more than once in a request or command sequence, an attacker-controlled
external file can enable aliases and supply model mappings before /review parses its selector.
Code

pr_agent/git_providers/utils.py[R370-373]

+        if category != "global":
+            protected_keys = _LOCAL_REPO_PROTECTED_KEYS_BY_SECTION.get(section.lower(), frozenset())
+            rejected = [key for key in contents if key.lower() in protected_keys]
+            if rejected:
Evidence
The new protection only covers keys in the pr_reviewer section, while repository settings
otherwise merge arbitrary allowed contents. apply_repo_settings reads CONFIG.EXTRA_CONFIG_URL
and merges that external file before selector parsing, and the GitHub Action runner applies
repository settings before invoking commands whose handlers apply them again.

pr_agent/git_providers/utils.py[20-26]
pr_agent/git_providers/utils.py[242-250]
pr_agent/git_providers/utils.py[370-384]
pr_agent/servers/github_action_runner.py[173-177]
pr_agent/agent/pr_agent.py[227-229]

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

## Issue description
Repository-local settings can set `CONFIG.EXTRA_CONFIG_URL`, allowing a later settings application to load attacker-controlled alias controls as trusted external configuration.
## Fix Focus Areas
- pr_agent/git_providers/utils.py[20-26]
- pr_agent/git_providers/utils.py[370-379]
## Recommended Fix
Add `extra_config_url` to the repository-local protected settings and ensure local repository merges cannot retain or replace the operator-provided external configuration source. Add a test that applies settings repeatedly and verifies an external file selected by the repository cannot enable or redefine command model aliases.

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


6. Local checkouts can redefine aliases 🐞 Bug ⛨ Security
Description
_run_command trusts alias controls from get_settings(), but config_loader loads the reviewed
checkout's tool.pr-agent configuration directly into those settings without the repository-key
filter. In local and CLI reviews, a checkout can therefore enable the feature and define its own
alias mapping before a selector is resolved.
Code

pr_agent/agent/pr_agent.py[R301-304]

+                settings = get_settings()
+                selection_config = ReviewModelSelectionConfig(
+                    enabled=settings.get("PR_REVIEWER.ENABLE_COMMAND_MODEL_ALIASES", False),
+                    aliases=settings.get("PR_REVIEWER.COMMAND_MODEL_ALIASES", {}),
Evidence
The loader discovers the current checkout's repository root and loads its pyproject.toml into the
same settings object returned by get_settings. The newly added dispatch code reads both alias
controls from that object and passes them directly to the selector parser.

pr_agent/config_loader.py[50-63]
pr_agent/config_loader.py[81-109]
pr_agent/agent/pr_agent.py[298-306]
pr_agent/algo/review_model_selection.py[94-102]

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 reviewed checkout's `pyproject.toml` can populate the supposedly global-only alias settings because that configuration route bypasses repository-local key filtering.
## Fix Focus Areas
- pr_agent/config_loader.py[81-109]
- pr_agent/agent/pr_agent.py[301-306]
## Recommended Fix
Prevent `tool.pr-agent` configuration loaded from the reviewed checkout from setting `enable_command_model_aliases` or `command_model_aliases`, or source these controls from a separate trusted configuration snapshot that checkout configuration never mutates. Add a local-mode test using a checkout `pyproject.toml` that attempts to define both values.

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


7. Later commands use the prior model 📘 Rule violation ≡ Correctness
Description
_run_command writes the selected model, effort, routing state, and adaptive-thinking flag into the
shared Dynaconf settings object without snapshotting or restoring their previous values. When
auto-command loops, polling, or GitHub Actions execute multiple commands in the same settings
context or global object, a selected review contaminates later selector-free commands with its
model, effort, disabled routing, and potentially Claude thinking instead of their normal
configuration.
Code

pr_agent/agent/pr_agent.py[R320-323]

+            settings.set("CONFIG.MODEL", model_selection.model)
+            settings.set("CONFIG.REASONING_EFFORT", model_selection.reasoning_effort)
+            settings.set("MODEL_ROUTING.ENABLE", False)
+            if "claude" in model_selection.model.lower() and model_selection.reasoning_effort != "none":
Evidence
The selector block mutates the current shared settings and can reach the successful return without
restoring them, despite the documentation promising that selection applies to only one invocation
and later commands use normal configuration. The server and GitHub auto-command and Action loops
repeatedly invoke commands against the same settings context or global settings object,
demonstrating how those mutations persist into later commands rather than being scoped to the
selected review.

Rule 3: Robust Error Handling
pr_agent/agent/pr_agent.py[319-324]
docs/docs/tools/review.md[41-44]
pr_agent/servers/github_app.py[509-513]
pr_agent/servers/gitlab_webhook.py[81-87]
pr_agent/agent/pr_agent.py[319-340]
pr_agent/servers/github_app.py[508-513]
pr_agent/servers/github_action_runner.py[122-127]
pr_agent/config_loader.py[50-63]

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

## Issue description
Per-review model selection mutates shared settings without restoring their previous values, allowing one review's selected model behavior to affect later commands executed by the same request or process.
## Fix Focus Areas
- pr_agent/agent/pr_agent.py[319-340]
- tests/unittest/test_review_model_selection.py[202-245]
## Recommended Fix
Snapshot all four affected settings immediately before applying a selector, including whether each setting was originally absent. Execute reviewer construction and execution inside a `try` block, then restore the exact previous model, effort, routing, and adaptive-thinking values in `finally`, including when construction or execution raises. Add a regression test that runs a selected review followed by a selector-free AI command in the same settings context and verifies that the original values are observed.

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


8. Unbounded selector retry chain ✓ Resolved 🐞 Bug ⛨ Security
Description
parse_review_model_selections appends every caller-supplied selector without a maximum or
duplicate limit, and retry_with_fallback_models attempts the entire chain after failures. An
enabled repository can therefore receive a comment containing thousands of repeated selectors,
multiplying provider retries, latency, and spend during a model outage or consistently failing
alias.
Code

pr_agent/algo/review_model_selection.py[R135-137]

+        selections.append(
+            ReviewModelSelection(alias=alias, model=aliases[alias], reasoning_effort=effort)
+        )
Relevance

●● Moderate

The security concern is plausible, but history provides no close precedent for capping
caller-supplied fallback selector chains.

PR-#2053

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The parser consumes every plus-bearing token and appends each valid selection without a cap; the
retry loop then walks every resulting model, while each LiteLLM and OpenAI attempt has its own retry
decorator. Because command comments are caller-controlled, repeating an allowlisted but failing
selector directly scales the number of attempted provider calls.

pr_agent/algo/review_model_selection.py[85-105]
pr_agent/algo/review_model_selection.py[135-139]
pr_agent/algo/pr_processing.py[341-372]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[563-568]
pr_agent/algo/ai_handlers/openai_ai_handler.py[45-49]

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

## Issue description
Caller-controlled `/review` selector chains are unbounded, so repeated selectors can amplify failed provider attempts, retries, latency, and cost.
## Issue Context
The operator allowlist restricts model identities but does not restrict how many times a commenter can request an allowlisted alias. Enforce a small explicit chain limit before constructing the reviewer, and reject duplicate selections with an actionable `ReviewModelSelectionError`.
## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[102-139]
- tests/unittest/test_review_model_selection.py[96-123]

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



Remediation recommended

9. Plus URLs abort reviews ✓ Resolved 🐞 Bug ≡ Correctness
Description
The new provider_shaped_alias heuristic classifies any token whose text before + contains / or
: as a model selector, even when its effort is unsupported and its alias is not configured. With
overrides enabled, ordinary review text such as https://example.test/C+++guidelines or
C:\src+generated therefore reaches the raw-model error and aborts the review instead of remaining
an argument.
Code

pr_agent/algo/review_model_selection.py[170]

+        provider_shaped_alias = "/" in alias or ":" in alias
Relevance

●●● Strong

The heuristic contradicts documented selector boundaries and creates a deterministic review-aborting
false positive for URL/path arguments.

PR-#2755
PR-#2772

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The added heuristic sets provider_shaped_alias for any slash or colon before +, bypassing the
ordinary-argument branch; the subsequent raw-ID check then raises. The feature documentation
explicitly says tokens are selectors only for known efforts or configured aliases and that other
plus-containing arguments never fail reviews.

pr_agent/algo/review_model_selection.py[169-193]
docs/docs/tools/review.md[70-72]

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 provider-shaped heuristic mistakes ordinary URL/path tokens containing `+` for raw model selectors and aborts `/review`.
## Issue Context
Only known-effort tokens or configured aliases should be treated as selectors; raw model detection must remain precise enough not to consume arbitrary free text.
## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[169-175]
- tests/unittest/test_review_model_selection.py[94-101]

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


10. ReviewModelSelectionConfig docstring not imperative ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The class docstring is a descriptive noun phrase rather than an imperative instruction. This
violates the required imperative phrasing for newly modified docstrings.
Code

pr_agent/algo/review_model_selection.py[34]

+    """Trusted controls loaded at the command-dispatch boundary."""
Relevance

●●● Strong

Recent same-day precedent accepts imperative rewrites for newly modified docstrings under this
repository rule.

PR-#2817

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694688 requires imperative phrasing for modified docstrings. The changed class
docstring at line 34 starts with the descriptive phrase Trusted controls loaded rather than an
imperative verb such as Store or Define.

Rule 2694688: Docstrings and comments must use imperative phrasing
pr_agent/algo/review_model_selection.py[34-34]

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

## Issue description
Rewrite the `ReviewModelSelectionConfig` docstring so its first sentence begins with an imperative verb.
## Issue Context
PR Compliance ID 2694688 requires newly modified docstrings to use imperative phrasing; `Trusted controls loaded...` is descriptive.
## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[34-34]

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


11. Raw model selector bypass ✓ Resolved 🐞 Bug ≡ Correctness
Description
parse_review_model_selections treats a raw provider ID with an unsupported effort, such as
anthropic/claude-opus-5+extreme, as an ordinary argument because the early continue runs before
the raw-ID check. The command therefore constructs and runs the reviewer with the normal model chain
instead of rejecting the prohibited raw selector as promised.
Code

pr_agent/algo/review_model_selection.py[R162-164]

+        if not _is_selector_shaped(arg) and alias not in configured_alias_names:
+            # Treat non-selector-shaped tokens that do not target a configured
+            # alias as ordinary arguments, such as `C++`.
Relevance

●●● Strong

This is a concrete selector-validation bypass contradicting the PR’s explicit promise to reject raw
provider IDs before reviewer construction.

PR-#2755
PR-#2622

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The selector contract says only known efforts or configured aliases are treated as selectors, but
the later code explicitly intends to reject aliases containing / or :. The new early-continue
branch executes first for an unconfigured raw ID whose effort is unknown, making lines 178-180
unreachable; _handle_request then passes the retained argument into the reviewer constructor and
runs it.

pr_agent/algo/review_model_selection.py[122-125]
pr_agent/algo/review_model_selection.py[157-180]
pr_agent/agent/pr_agent.py[230-261]
tests/unittest/test_review_model_selection.py[192-212]

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

## Issue description
Raw provider model identifiers with unknown or malformed effort values bypass selector validation. For example, `anthropic/claude-opus-5+extreme` is currently retained as an ordinary argument, so `/review` proceeds instead of rejecting the prohibited raw selector.
## Issue Context
The parser performs its ordinary-plus-token early return before checking `/` or `:` in the alias portion. Preserve compatibility for prose such as `C++` and `a+b`, but classify provider-shaped alias portions as invalid selectors regardless of whether the effort is recognized.
## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[157-180]
- tests/unittest/test_review_model_selection.py[192-212]
- tests/unittest/test_review_model_selection.py[477-521]

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


View medium (8)
12. _get_configured_alias_names bypasses loader ✓ Resolved 📘 Rule violation ⌂ Architecture
Description
The new helper reads PR_REVIEWER.COMMAND_MODEL_ALIASES from an injected settings object instead of
obtaining configuration through pr_agent.config_loader.get_settings(). This violates the required
single configuration-access path and can make configuration provenance harder to audit.
Code

pr_agent/algo/review_model_selection.py[88]

+    raw_aliases = settings.get("PR_REVIEWER.COMMAND_MODEL_ALIASES", {}) or {}
Relevance

●●● Strong

The PR explicitly promises a single get_settings() configuration path; this helper directly violates
that stated architectural requirement.

PR-#2797

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Rule 2694699 requires modified code to obtain configuration by calling get_settings(). The newly
added helper instead calls settings.get("PR_REVIEWER.COMMAND_MODEL_ALIASES", ...) on its
parameter.

Rule 2694699: Access configuration only via get_settings() from pr_agent.config_loader
pr_agent/algo/review_model_selection.py[87-95]

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

## Issue description
`_get_configured_alias_names` directly accesses an injected settings object rather than using the required `get_settings()` configuration path.
## Issue Context
PR Compliance ID 2694699 requires configuration values to be obtained exclusively through `pr_agent.config_loader.get_settings()`. Preserve testability by mocking the loader or by passing non-configuration data that was loaded at an approved boundary.
## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[87-95]

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


13. Alias example exceeds line limit ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new command_model_aliases documentation example is a single physical line longer than 120
characters. This violates the repository-wide line-length requirement and makes the example harder
to review and maintain.
Code

docs/docs/tools/review.md[56]

+command_model_aliases = { fable = "anthropic/claude-fable-5", opus = "anthropic/claude-opus-5", sonnet = "anthropic/claude-sonnet-5", sol = "gpt-5.6-sol", terra = "gpt-5.6-terra", luna = "gpt-5.6-luna" }
Relevance

●●● Strong

Recent same-file precedent accepted wrapping a documentation line-length violation.

PR-#2797

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694690 requires every non-generated source line to be at most 120 characters,
while the newly added inline TOML mapping at line 56 is substantially longer.

Rule 2694690: Enforce maximum line length of 120 characters
docs/docs/tools/review.md[56-56]

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 `command_model_aliases` documentation example exceeds the 120-character maximum line length.
## Issue Context
Keep the example valid and readable while preserving every documented alias mapping.
## Fix Focus Areas
- docs/docs/tools/review.md[56-56]

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


14. Alias setting exceeds line limit ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new command_model_aliases setting is written on a single physical line longer than 120
characters. This violates the configured maximum and reduces maintainability of the central
configuration file.
Code

pr_agent/settings/configuration.toml[103]

+command_model_aliases = { fable = "anthropic/claude-fable-5", opus = "anthropic/claude-opus-5", sonnet = "anthropic/claude-sonnet-5", sol = "gpt-5.6-sol", terra = "gpt-5.6-terra", luna = "gpt-5.6-luna" }
Relevance

●●● Strong

Recent configuration precedent accepted rewriting a long inline setting to satisfy line-length
rules.

PR-#2796

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694690 applies a 120-character maximum to modified non-generated source files, and
the newly added mapping at line 103 is substantially longer.

Rule 2694690: Enforce maximum line length of 120 characters
pr_agent/settings/configuration.toml[103-103]

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 `command_model_aliases` configuration line exceeds the 120-character maximum line length.
## Issue Context
Reformat the TOML value without changing the aliases or their mapped provider model identifiers.
## Fix Focus Areas
- pr_agent/settings/configuration.toml[103-103]

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


15. Selector typo silently ignored ✓ Resolved 🐞 Bug ≡ Correctness
Description
When the alias map contains both a valid alias and any malformed entry, the broad catch returns
before checking whether an argument such as opus+extreme targets that valid alias. The review then
proceeds with the configured model chain instead of rejecting the unsupported effort, violating the
parser's documented selector behavior and the requirement to reject malformed selectors before
reviewer construction.
Code

pr_agent/algo/review_model_selection.py[R133-136]

+        except ReviewModelSelectionError:
+            # A malformed alias map must not fail a review whose arguments contain
+            # no selector; the config error surfaces when a selector is used.
+            return (), list(args)
Relevance

●●● Strong

Recent accepted precedents fix silent malformed-input bypasses; matches team's pattern of tightening
validation for correctness bugs.

PR-#2755
PR-#2784

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
_get_aliases() raises on the first invalid alias entry, and the new catch immediately returns all
arguments unchanged. This bypasses the later valid-alias near-miss check and unsupported-effort
error, despite the function contract explicitly saying opus+extreme should produce an actionable
error; the unchanged arguments then reach reviewer construction.

pr_agent/algo/review_model_selection.py[59-78]
pr_agent/algo/review_model_selection.py[101-108]
pr_agent/algo/review_model_selection.py[131-150]
pr_agent/agent/pr_agent.py[230-261]

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 entry anywhere in the alias map causes `parse_review_model_selections()` to treat valid-alias near-misses such as `opus+extreme` as ordinary arguments, so the review runs without the requested override instead of returning an actionable selector error.
## Issue Context
Ordinary plus-containing prose must remain unaffected, but a token whose alias matches a valid configured alias must still be recognized even if another alias-map entry is malformed. The parser documentation explicitly identifies `opus+extreme` as an actionable error.
## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[123-136]
- tests/unittest/test_review_model_selection.py[86-96]

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


16. Ordinary plus arguments can fail ✓ Resolved 🐞 Bug ☼ Reliability
Description
With overrides enabled, any /review argument containing + passes this guard and causes the
entire alias map to be validated before the parser knows whether a selector exists. Consequently, an
unrelated malformed alias entry makes ordinary input such as C++ raise ReviewModelSelectionError
and abort the review, despite the documented guarantee that such arguments never fail the command.
Code

pr_agent/algo/review_model_selection.py[110]

+    if not any("+" in arg for arg in args):
Relevance

●●● Strong

Concrete parser guard bug that can break the documented compatibility guarantee for ordinary '+'
arguments.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The early guard only bypasses parsing when no argument contains +; afterward _get_aliases
validates every configured alias and raises on any malformed entry before the loop classifies C++
as ordinary. The command handler catches that error and returns False, while both the parser
contract and user documentation explicitly say ordinary plus-containing arguments retain historical
behavior and never fail review.

pr_agent/algo/review_model_selection.py[59-78]
pr_agent/algo/review_model_selection.py[86-95]
pr_agent/algo/review_model_selection.py[110-142]
pr_agent/agent/pr_agent.py[230-244]
docs/docs/tools/review.md[64-66]

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

## Issue description
Ordinary arguments containing `+`, such as `C++`, currently trigger full alias-map validation whenever overrides are enabled. An unrelated malformed operator alias therefore aborts a review even though no selector was supplied.
## Issue Context
Preserve strict alias validation when a selector-shaped token or a near-miss for a configured alias is actually present, but return untouched ordinary arguments without validating unrelated alias entries.
## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[110-142]
- tests/unittest/test_review_model_selection.py[76-94]

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


17. _encoded_args uses single quotes ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The newly split _encoded_args list introduces many single-quoted Python string literals, contrary
to the required double-quote convention. This makes the changed source noncompliant with the
project's stated literal style.
Code

pr_agent/algo/cli_args.py[R13-16]

+            _encoded_args = ':'.join([
+                'c2hhcmVkX3NlY3JldA==', 'dXNlcg==', 'c3lzdGVt',
+                'ZW5hYmxlX2NvbW1lbnRfYXBwcm92YWw=', 'ZW5hYmxlX21hbnVhbF9hcHByb3ZhbA==',
+                'ZW5hYmxlX2F1dG9fYXBwcm92YWw=', 'YXBwcm92ZV9wcl9vbl9zZWxmX3Jldmlldw==',
Relevance

●●● Strong

Multiple recent precedents accept replacing newly added single-quoted literals with double quotes.

PR-#2693
PR-#2677
PR-#2687

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Rule 2694657 requires double quotes for Python string literals. The changed _encoded_args
construction uses a single-quoted join separator and single-quoted list entries throughout the new
block.

Rule 2694657: Use double quotes for all Python string literals
pr_agent/algo/cli_args.py[13-27]

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 newly added `_encoded_args` literals use single quotes instead of the required double quotes.
## Issue Context
Preserve the encoded values and list behavior while changing only string delimiters.
## Fix Focus Areas
- pr_agent/algo/cli_args.py[13-27]

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


18. First-party import precedes dependencies ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new pr_agent import is placed before the standard-library and third-party import sections,
splitting first-party imports into two disjoint groups. This violates the required standard-library,
third-party, then local import ordering.
Code

pr_agent/algo/ai_handlers/langchain_ai_handler.py[R1-2]

+from pr_agent.algo.review_model_selection import \
+    get_active_review_model_selection
Relevance

●●● Strong

Import ordering is a deterministic repository convention, and the new import visibly precedes
standard and third-party sections.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Rule 2694656 requires contiguous import sections ordered as standard library, third party, then
local. The new first-party import is at lines 1-2, while functools, openai, and tenacity
follow at lines 14-18 and the remaining first-party imports are at lines 20-23.

Rule 2694656: Group Python imports according to isort sections and order
pr_agent/algo/ai_handlers/langchain_ai_handler.py[1-2]
pr_agent/algo/ai_handlers/langchain_ai_handler.py[14-23]

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 first-party model-selection import appears before standard-library and third-party imports.
## Issue Context
Keep optional LangChain imports intact, but place the `pr_agent` import with the other first-party imports after external dependencies.
## Fix Focus Areas
- pr_agent/algo/ai_handlers/langchain_ai_handler.py[1-23]

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


19. Run-details paragraph exceeds limit ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The modified run-details paragraph is a single physical line far longer than 120 characters. It must
be wrapped to satisfy the repository-wide maximum line-length requirement.
Code

docs/docs/usage-guide/additional_configurations.md[44]

+`Model` shows the model that produced the answer, marked `(fallback)` when the primary model failed and a fallback took over. For a `/review alias+effort` invocation, `Reasoning effort` shows the effort paired with that successful model, including the fallback selector's own effort. The `Tokens` line appears only when the model provider reports usage. `AI calls` counts the successful LLM invocations made during the run. The flag is disabled by default.
Relevance

●●● Strong

Recent repository precedents explicitly accept wrapping overlong modified documentation lines.

PR-#2797
PR-#2622

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Rule 2694690 applies a 120-character maximum to modified non-generated source files. The changed
Markdown paragraph at line 44 contains the entire explanation on one substantially longer line.

Rule 2694690: Enforce maximum line length of 120 characters
docs/docs/usage-guide/additional_configurations.md[44-44]

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 modified run-details documentation paragraph exceeds the 120-character line limit.
## Issue Context
Wrap the Markdown source without changing the rendered prose.
## Fix Focus Areas
- docs/docs/usage-guide/additional_configurations.md[44-44]

ⓘ 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
Review mode: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 17/18, lines 832/200; both must reach the floor). Router rationale: This security-sensitive feature spans configuration provenance, command parsing, model routing, settings restoration, and repository isolation, with substantial new logic across multiple independent code paths and a demonstrated history of subtle defects.

Grey Divider

Tip of the day
💡 Did you know, you can hide the parts of a finding you never read, like the evidence or the agent prompt

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread pr_agent/algo/review_model_selection.py Resolved
Comment thread pr_agent/algo/pr_processing.py Fixed

@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.

Off by default, with only an operator able to list the allowed models, is the right way round.

I'd hold this on Qodo's "unbounded chain" finding. Qodo says a comment could trigger it; I checked that it really can. Comment /review followed by opus+high repeated 5000 times and all 5000 reach the reviewer. CliArgs.validate_user_args blocks --pr_reviewer.enable_command_model_overrides=..., but it only looks at arguments starting with --, so plain tokens walk past.

How bad it gets depends on failure. pr_processing.py:373 stops at the first call that works, so normally it's one call. If the model is down or an alias is broken, it tries all 5000, each retried again on top.

Suggested fix inline. I went with rejecting duplicates rather than silently dropping them, since your docs describe the list as "try these in order", so a deliberate repeat is a fair thing to type.

One more worth doing: the new pr_agent import at the top of langchain_ai_handler.py trips a ruff warning main doesn't have. Moving it into the pr_agent group at the bottom of the import block clears it. I'd skip Qodo's "line too long" note on the docs, there's no markdown linter here.

Comment thread pr_agent/algo/review_model_selection.py Resolved
Comment thread pr_agent/algo/review_model_selection.py Resolved
@elijahchancey

Copy link
Copy Markdown
Contributor Author

Addressed all review findings in 19b77b5:

  • bounded caller-controlled selector chains to four entries and reject exact duplicates before reviewer construction or model calls
  • added parser, boundary, routing, and no-provider-call coverage for duplicate and over-limit commands
  • moved the LangChain import into the first-party import group and changed the newly split encoded literals to double quotes
  • wrapped the modified run-details documentation and documented the four-selector limit
  • added an explicit empty-chain RuntimeError and regression test for the CodeQL return-path finding

Verification: scoped pre-commit and flake8 checks pass; 117 focused tests pass; full unit suite passes with 2413 passed, 1 skipped, and 1 xfailed.

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 19b77b5

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 9c35f51

@elijahchancey

Copy link
Copy Markdown
Contributor Author

Addressed the latest review findings in 33ebaf9:

  • Ordinary plus arguments can fail — fixed. The alias map is now validated only when a selector-shaped token is present; with no selectors, a malformed command_model_aliases entry no longer aborts ordinary input like C++, and the config error surfaces on actual selector use. Covered by test_malformed_alias_configuration_does_not_fail_reviews_without_selectors.
  • _is_selector_shaped docstring not imperative — fixed; it now starts with an imperative verb.
  • Narrative-phrasing comment findings (selector comment, LiteLLM handler comments, test comments) — declined. AGENTS.md asks for "imperative phrasing only where necessary"; these comments state provider constraints the code cannot express (Anthropic rejects pinned temperature while thinking is enabled; litellm raises UnsupportedParamsError for models outside its capability map), where descriptive phrasing is the clearer form.

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 33ebaf9

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 6e50207

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 1461134

@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.

Qodo's unbounded-chain finding is closed, checked.

The rebase is now the blocker rather than tidiness: the conflict stops GitHub building a merge ref, so build-and-test has never run on 1461134, which carries only update_release_draft against five green checks on your previous head.

The conflict is one import block, from #2817. Watch MockResponse on the way through, since #2817 removed its last use. This merges, at 2582 passed with only the test_litellm_callback_drain failure main already has:

from pr_agent.algo.ai_handlers.litellm_helpers import (
    _get_azure_ad_token, _handle_streaming_response,
    _process_litellm_extra_body, _response_field)
from pr_agent.algo.review_model_selection import \
    get_active_review_model_selection
from pr_agent.algo.run_details import _as_decimal_cost, record_ai_call

Qodo's 2 and 3 are your call; both lines are 203 characters and those files already carry 28 and 35 over 120. Its finding 4 is real and CodeQL's double import is worth taking, suggestions inline for both.

Comment thread pr_agent/algo/review_model_selection.py Resolved
Comment thread pr_agent/algo/review_model_selection.py Resolved
@elijahchancey

Copy link
Copy Markdown
Contributor Author

Addressed all current review feedback in 50734c03:

  • Merge/build blocker and MockResponse — merged current upstream main without rewriting history. The LiteLLM resolution retains upstream _response_field and _as_decimal_cost, removes obsolete MockResponse, and preserves request-scoped effort selection. It also routes selected OpenRouter effort through the unified reasoning body and overrides conflicting configured effort/token budgets.
  • Qodo findings 2–3 — replaced both overlong inline TOML maps with equivalent dotted-key assignments under 120 characters.
  • Qodo finding 4 and the two alias-map suggestions — malformed unrelated entries no longer hide effort typos against valid aliases, while a typo targeting a malformed configured alias now surfaces the configuration error instead of passing through.
  • CodeQL duplicate import and both suggested test edits — removed the module alias import and patched private helpers by fully qualified string path.
  • Qodo findings 10, 12, and 13 — rewrote the new behavior comments with imperative phrasing. The already-resolved test-comment finding was aligned as well.
  • Previously resolved Qodo findings 1, 5–9, and 11 — retained their fixes and coverage through the merge.

Verification:

  • repository pre-commit hooks passed on the touched files
  • 112 focused model-selection, fallback, OpenRouter, and reasoning tests passed
  • full unit suite passed: 2,615 passed, 1 skipped, 1 expected failure

GitHub now reports the PR as mergeable. Fresh build-and-test and CodeQL checks are running on exact head 50734c03b0bd791a2ade407f6a8290477e53cf76.

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 50734c0

@elijahchancey

Copy link
Copy Markdown
Contributor Author

Follow-up review fixes are now in 61d5814.\n\n- Configuration boundary: command-model configuration is loaded through get_settings() at the dispatcher boundary and passed to the pure parser as a typed ReviewModelSelectionConfig value. The selection helper no longer reaches into injected settings/configuration itself.\n- Raw provider selector validation: provider-shaped values such as anthropic/claude-opus-5+extreme can no longer fall through as ordinary command arguments; they are rejected as raw model identifiers. Added parser and routing regression coverage.\n- Documentation formatting: wrapped both flagged GitLab configuration paragraphs to the repository's 120-character limit.\n\nVerification:\n- pre-commit run --all-files\n- PYTHONPATH=. ../pr-agent/.venv/bin/pytest tests/unittest/test_review_model_selection.py tests/unittest/test_pr_agent_routing.py -q — 57 passed\n- PYTHONPATH=. ../pr-agent/.venv/bin/pytest tests/unittest -q — 2617 passed, 1 skipped, 1 xfailed

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 61d5814

@elijahchancey

Copy link
Copy Markdown
Contributor Author

Addressed the two findings added by Qodo's latest refresh in a7690ff0:

  • ReviewModelSelectionConfig docstring not imperative — rewrote the first sentence to begin with Store.
  • Plus URLs abort reviews — unsupported-effort tokens are treated as prohibited raw selectors only when
    their left side exactly matches an operator-allowlisted model ID. Ordinary URL and Windows-path arguments
    containing + remain untouched, while known-effort raw IDs and configured raw IDs remain rejected.

Verification:

  • pre-commit run --files pr_agent/algo/review_model_selection.py tests/unittest/test_review_model_selection.py
  • focused parser/routing suite: 57 passed
  • full unit suite: 2617 passed, 1 skipped, 1 xfailed

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit a7690ff

@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.

The implementation holds up: rebased and green on a real merge ref, all four suggestions in, both CodeQL alerts clear, and the revert probe goes red across all four surfaces, so the tests genuinely pin the behaviour.

Before it goes further, though, @naorpeled should decide whether this is the direction we want, because it is a second way to do something that already works. /review --config.model=... --config.reasoning_effort=high is permitted from a PR comment today: the denylist in cli_args.py blocks openai.key and api_base but not config.model, and I ran it to confirm. This adds an allowlisted alias syntax alongside that route, at +1118/-61 across 19 files, touching the dispatcher, all three AI handlers and pr_processing. If the worry is that the existing route is unrestricted, putting an allowlist on that route is a much smaller change than adding a syntax.

That is an owner call rather than mine. Sorry I have been too focus on just review review review that sort of missed looking at it at a higher level.

Separately, one defect worth fixing whichever way the call goes. Detail inline.

Comment thread pr_agent/algo/review_model_selection.py Resolved
@elijahchancey

Copy link
Copy Markdown
Contributor Author

I had no idea /review --config.model=... --config.reasoning_effort=high was supported!

That said, I do prefer my simpler human friendly syntax. Open to suggestions on how to help this PR (or a variation of it) move forward. :)

@naorpeled

Copy link
Copy Markdown
Member

Hey @elijahchancey,
First of all thanks for opening this PR!
I appreciate the effort.
I'm wondering if we can cleanup the syntax a bit and make it more explicit that we're giving an alias + effort.
Need to give this some thought 🙏

What I had in mind was a stringified JSON object but that's not intuitive and easy to mistype 🤔

@elijahchancey

Copy link
Copy Markdown
Contributor Author

My opinion is that the syntax is as simple as it possible can be at this time:
/review fable+high

Other possible syntaxes:
/review fable-high
/review fable,high

A syntax I would prefer to avoid:
/review fable high

I would prefer to avoid this because in the future we may want to support something like:
/review fable+high sol+high

What other syntaxes did you have in mind?

@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 doing the security homework unprompted; the protected-keys allowlist is careful work.

My hesitation is scope, and I have not decided. What does this give that config.model and fallback_models do not? I checked: both are already settable from a repo .pr_agent.toml, and --config.model=... passes validate_user_args unblocked today. So the door this guards for aliases stands open beside it, which makes the spend-access argument hard to make as stated.

Parking this with @naorpeled for the scope call rather than holding it on my own view.

…el-overrides

# Conflicts:
#	pr_agent/git_providers/utils.py
#	pr_agent/servers/help.py
@qodo-code-review

qodo-code-review Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

Grey Divider

Sorry, something went wrong

We weren't able to complete the code review on our side. Please try again manually by commenting /agentic_review on this PR.

Grey Divider

Qodo Logo

@elijahchancey

Copy link
Copy Markdown
Contributor Author

@IsmaelMartinez do you know how we can get @naorpeled 's attention? I'd love to not have to maintain a fork of pr-agent for my company. :)

@naorpeled

Copy link
Copy Markdown
Member

Hey,
I'm sorry for the delay, I was a bit less available lately for OSS work.

I'll take a look when I'm back home (in few hours)

@naorpeled

Copy link
Copy Markdown
Member

…el-overrides

# Conflicts:
#	pr_agent/servers/help.py
@elijahchancey

Copy link
Copy Markdown
Contributor Author

okay. I'll keep merging in main and resolving conflicts until you approve. thanks!

Comment thread pr_agent/agent/pr_agent.py Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit c6b92de

@naorpeled

Copy link
Copy Markdown
Member

Hey,
quick question, What's the difference between this and using model and effort flags?

@elijahchancey

Copy link
Copy Markdown
Contributor Author

#2818 (comment)

Comment thread pr_agent/algo/review_model_selection.py Resolved
Comment thread pr_agent/git_providers/utils.py Resolved
Comment thread pr_agent/agent/pr_agent.py Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 1d32121

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 6c0213a

@elijahchancey

Copy link
Copy Markdown
Contributor Author

Addressed the three findings from the review of c6b92dea in commit 1d32121a7c4278b02e3ea0f4756c688f0ee413ea:

  • Later commands use the prior model: restore all four selector settings in finally, including originally absent values. Tests cover successful execution, constructor/run failures, and a subsequent selector-free command.
  • Selector failures lose tracebacks: use exception logging for publication and notification failures and attach the caught publication exception to the structured artifact. Tests cover provider construction, publication, and notification failures.
  • Rejected selectors are not marked failed: mark rejected-selector spans as errors with error.type=invalid_model_selector; include the error message only when the telemetry privacy setting permits it. Tests cover both privacy settings.

CI also exposed a missing generated configuration-reference entry for this PR's alias-enable setting. Commit 6c0213a7efe9caf0e509baa85a2b2433873d1492 updates the reference and expected key count.

Verification: 49 focused model-selection/routing tests and 2 configuration-reference tests passed locally. Build-and-test, pre-commit, and CodeQL pass on final head 6c0213a7efe9caf0e509baa85a2b2433873d1492.

The three newly raised threads about disabled malformed selectors, external configuration, and local checkout configuration remain open pending investigation; this follow-up does not claim those are fixed.

Comment on lines +340 to +342
settings.set("CONFIG.MODEL", model_selection.model)
settings.set("CONFIG.REASONING_EFFORT", model_selection.reasoning_effort)
settings.set("MODEL_ROUTING.ENABLE", False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Action required

1. Concurrent reviews swap selected models 📘 Rule violation ☼ Reliability

_run_command snapshots and mutates the get_settings() object before awaiting command execution,
then unconditionally restores its snapshot in finally. When callers run without an installed
request context, overlapping reviews share global_settings, so one task can execute with another
task's selector and the last cleanup can restore a stale model.
Agent Prompt
## Issue description
Temporary model-selection settings are mutated on a potentially shared settings object across an awaited review, allowing concurrent commands to interfere with execution and cleanup.

## Fix Focus Areas
- pr_agent/agent/pr_agent.py[323-374]
- pr_agent/config_loader.py[50-63]

## Recommended Fix
Give each command invocation an isolated context-local settings copy before applying selector overrides, and keep snapshot restoration within that isolated context. Add an asynchronous overlap test proving two selectors retain their own model and leave the baseline settings unchanged.

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

Comment on lines +298 to +301
model_selection = None
if action == "review":
try:
settings = get_settings()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Action required

2. Command dispatch owns unrelated work 📘 Rule violation ⚙ Maintainability

_run_command now parses selector configuration, emits rejection responses and telemetry, scopes
four settings, and dispatches all command classes. A change to selector validation, cleanup, or
ordinary dispatch must edit the same exception path, so these independently evolving behaviors
cannot be tested or changed in isolation.
Agent Prompt
## Issue description
The command dispatcher now combines selector resolution, rejection handling, temporary settings management, telemetry, and command execution.

## Fix Focus Areas
- pr_agent/agent/pr_agent.py[298-374]

## Recommended Fix
Extract selector resolution and rejection handling into one helper and temporary model settings into a dedicated context manager. Leave `_run_command` responsible for selecting and invoking the command while preserving the existing telemetry and cleanup behavior.

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

Comment on lines +161 to +162
try:
effort = ReasoningEffort(effort).value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Action required

3. Minimal claude reviews ignore effort 🐞 Bug ≡ Correctness

parse_review_model_selection accepts minimal for every alias even though the adaptive Claude
request path cannot transmit that effort. With the shipped fable alias, /review fable+minimal
enables adaptive thinking but sends neither an output effort nor a generic reasoning effort, so the
provider chooses its default instead.
Agent Prompt
## Issue description
The selector accepts `minimal` for adaptive Claude aliases, but the Claude adaptive-thinking handler does not transmit that value. The review therefore runs with provider-default effort rather than the caller's selected effort.

## Fix Focus Areas
- pr_agent/algo/review_model_selection.py[161-171]
- pr_agent/agent/pr_agent.py[339-344]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[3571-3579]

## Recommended Fix
Validate model-specific effort compatibility before executing the review. For recognized adaptive Claude models, reject `minimal` with an actionable selector error unless the handler is changed to support an explicit, semantically equivalent provider value; add an integration test covering `/review fable+minimal`.

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

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 399ed8b

@elijahchancey

Copy link
Copy Markdown
Contributor Author

Follow-up on the latest review: commit 399ed8b fixes both confirmed findings. Disabled malformed selectors now match configured alias names before effort validation; repository-selected external configuration is blocked by protecting CONFIG.EXTRA_CONFIG_URL from local repository overrides. Regression coverage checks malformed selectors, ordinary plus text, case variations, and repeated settings applications with and without an operator-provided external source. All 73 focused tests and pre-commit checks pass locally, and build-and-test plus CodeQL pass on that exact commit. The separate checkout-alias claim was resolved with reproduction evidence: the pinned configuration disables the TOML core loader, so the cited pyproject load does not change alias controls.

@naorpeled

naorpeled commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

First of all, thanks for the work on this.
I've discussed this with the rest of the team internally and we agreed that this is something we feel like does not fit both from maintainance and security POVs.

I appreciate your work on this, but unfortunately we'll have to decline this one 😔❤️

For future work, let's discuss via issues or LinkedIn to make sure no work goes to waste, as I really appreciate the time and effort you put into this 🙏

@naorpeled naorpeled closed this Sep 12, 2026
@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Sorry from my side @elijahchancey. I drove you through weeks of hardening and rebases before the scope call was made, and that ordering was backwards. Thank you for the care you put in and apologies again.

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.

4 participants