Skip to content

feat: support GitHub organization-level global settings - #2504

Merged
naorpeled merged 16 commits into
The-PR-Agent:mainfrom
naorpeled:feat-github-org-global-settings
Jul 4, 2026
Merged

naorpeled merged 16 commits into
The-PR-Agent:mainfrom
naorpeled:feat-github-org-global-settings

Conversation

@naorpeled

Copy link
Copy Markdown
Member

What & why

Split out from #2387 to keep each change reviewable on its own.

Lets an organization centralize PR-Agent defaults in a shared <org>/pr-agent-settings repository. When enabled, its .pr_agent.toml is loaded and merged beneath each repo's local .pr_agent.toml (local overrides global).

  • GithubProvider.get_repo_settings() now returns an ordered (scope, content) list; apply_repo_settings() merges global -> local.
  • Gated behind the existing use_global_settings_file config flag.
  • Configuration errors originating from the global file report the source without echoing the file's contents into the PR comment (avoids leaking org-wide config/secrets across repos).

⚠️ Note for reviewers

use_global_settings_file already defaults to true in configuration.toml. With this change merged, GitHub flows will make a best-effort extra API call to fetch <org>/pr-agent-settings (silently returns empty if the repo doesn't exist). Please confirm whether that default is desired, or whether this should ship defaulting to false.

Test

  • New tests/unittest/test_github_provider_settings.py and additions to test_git_provider_utils.py cover global/local merge precedence and the redaction-on-error behavior.
  • Full unit suite passes locally; ruff clean.

Original work by @avidspartan1 (commit authorship preserved).

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

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Support GitHub org-level global PR-Agent settings via pr-agent-settings repo

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Load org-wide .pr_agent.toml from /pr-agent-settings and merge beneath repo settings.
• Gate global lookup behind use_global_settings_file; keep local .pr_agent.toml highest
 precedence.
• Redact global config contents in error comments to avoid leaking org-wide secrets.
Diagram

graph TD
  A["PR-Agent run"] --> B["GithubProvider.get_repo_settings"] --> C["GitHub API"] --> D["Global .pr_agent.toml\n(org/pr-agent-settings)"] --> E["Local .pr_agent.toml\n(repo)"] --> F["apply_repo_settings()"] --> G["Merged settings\n(global→local)"]
  D -->|"Invalid TOML → redacted error comment"| G
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Make get_repo_settings always return a typed list (all providers)
  • ➕ Eliminates the current mixed return type (bytes/str vs list), reducing caller complexity
  • ➕ Creates a consistent contract across providers for multi-source settings
  • ➖ Requires updating all git providers and any other callers, increasing scope and churn
  • ➖ Potentially breaking change for downstream integrations expecting bytes/str
2. Use existing extra-config mechanism for org defaults (CONFIG.EXTRA_CONFIG_URL)
  • ➕ Leverages an already-supported “global-ish” layer without provider-specific GitHub API calls
  • ➕ Works uniformly across providers/environments when an org-hosted URL/path is available
  • ➖ Doesn’t naturally express “org/repo-derived” discovery semantics (needs explicit URL management)
  • ➖ Harder to enforce GitHub App permissions and org ownership rules automatically
3. Add caching/ETag support for org settings fetch
  • ➕ Reduces extra GitHub API calls when use_global_settings_file=true (especially high-volume orgs)
  • ➕ Improves latency and avoids rate-limit pressure
  • ➖ Adds statefulness and cache invalidation complexity
  • ➖ Less valuable if settings fetch is already infrequent per PR run

Recommendation: The PR’s approach (best-effort fetch from /pr-agent-settings gated by use_global_settings_file, then merge global→local) is a pragmatic, low-touch way to add org defaults while preserving repo overrides. The most meaningful follow-up improvement would be to standardize the get_repo_settings() return type (e.g., always return an ordered list) to avoid mixed-type contracts; caching can be deferred unless rate limits become a problem.

Files changed (6) +205 / -27

Enhancement (2) +77 / -24
github_provider.pyFetch org-level .pr_agent.toml and return ordered settings sources +31/-3

Fetch org-level .pr_agent.toml and return ordered settings sources

• Enhances 'get_repo_settings()' to optionally include an org-level '.pr_agent.toml' from '<org>/pr-agent-settings' when 'use_global_settings_file' is enabled. Returns an ordered list of '(scope, content)' so global settings can be merged beneath local settings; failures to fetch global settings are logged and treated as empty.

pr_agent/git_providers/github_provider.py

utils.pyMerge multiple settings files and redact global config on error +46/-21

Merge multiple settings files and redact global config on error

• Updates 'apply_repo_settings()' to accept either a single settings blob or an ordered '(scope, content)' list, writing multiple temp TOML files and loading them via Dynaconf with the custom merge loader. Improves configuration error handling so global settings errors mention the source but do not echo global config contents into PR comments.

pr_agent/git_providers/utils.py

Tests (2) +124 / -3
test_git_provider_utils.pyAdd tests for global→local precedence and global redaction behavior +32/-3

Add tests for global→local precedence and global redaction behavior

• Adds a test verifying that global settings load first and local overrides take precedence when applying settings. Updates configuration-error tests to assert global config contents are not printed (preventing secret leakage) while still reporting the global source.

tests/unittest/test_git_provider_utils.py

test_github_provider_settings.pyUnit test GitHub provider global/local settings retrieval and gating +92/-0

Unit test GitHub provider global/local settings retrieval and gating

• Introduces focused tests for 'GithubProvider.get_repo_settings()' covering: global-only, global+local ordering, same-section separation for merge behavior, and skipping global retrieval when 'use_global_settings_file' is disabled.

tests/unittest/test_github_provider_settings.py

Documentation (2) +4 / -0
github.mdDocument GitHub App setup for org-level settings repo +2/-0

Document GitHub App setup for org-level settings repo

• Adds installation guidance for using '<organization>/pr-agent-settings' as an org-wide configuration source. Notes that the GitHub App must be installed on the settings repo and have read access to both settings and PR repos (GitHub.com and GHES).

docs/docs/installation/github.md

configuration_options.mdClarify org-level global config behavior and permissions +2/-0

Clarify org-level global config behavior and permissions

• Extends the global configuration section with GHES notes and explicit permission requirements. Documents that missing access causes PR-Agent to skip global settings and continue with local repo settings.

docs/docs/usage-guide/configuration_options.md

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

qodo-free-for-open-source-projects Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

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

Grey Divider


Action required

1. Bitbucket errors parsed as TOML 🐞 Bug ≡ Correctness
Description
BitbucketProvider.get_repo_settings() treats any HTTP status other than 404 as a found local
.pr_agent.toml and appends response.text for parsing, so 401/403/500 responses can be
misinterpreted as TOML and trigger misleading configuration-error comments. Because local-scope
configuration errors include the file content in the PR comment, this can also echo non-TOML error
bodies back into PRs.
Code

pr_agent/git_providers/bitbucket_provider.py[R86-91]

      url = (f"https://api.bitbucket.org/2.0/repositories/{self.workspace_slug}/{self.repo_slug}/src/"
             f"{self.pr.destination_branch}/.pr_agent.toml")
      response = requests.request("GET", url, headers=self.headers)
-            if response.status_code == 404:  # not found
+            if response.status_code != 404:  # found
+                settings_files.append(("local", response.text.encode('utf-8')))
+        except Exception as e:
Evidence
Bitbucket local settings append the response body for any non-404 status; configuration error
reporting includes local configuration content in PR comments, so non-TOML error bodies can be
surfaced as if they were settings content.

pr_agent/git_providers/bitbucket_provider.py[80-93]
pr_agent/git_providers/utils.py[420-435]

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

## Issue description
`BitbucketProvider.get_repo_settings()` appends `response.text` as TOML whenever `status_code != 404`, meaning auth failures (401/403) and server errors (>=500) are treated as a settings file.
### Issue Context
This causes apply_repo_settings to attempt TOML parsing on non-TOML error bodies; for local-scope errors, the body can be included in the PR comment.
### Fix Focus Areas
- Only treat the response as a settings file on success (e.g., `status_code == 200` / `response.ok`).
- For other non-404 statuses, log an appropriate warning/debug and return empty (skip local settings).
- pr_agent/git_providers/bitbucket_provider.py[80-93]
- pr_agent/git_providers/utils.py[420-435]

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


2. Repo TOML size cap bypass 🐞 Bug ☼ Reliability
Description
_apply_repo_settings_file() parses the repo/global .pr_agent.toml via tomllib.load() before
Dynaconf/custom_merge_loader runs, bypassing the loader’s MAX_TOML_SIZE_IN_BYTES guard. An oversized
settings file can now be fully parsed in-process and cause high CPU/memory usage before it would
have been skipped.
Code

pr_agent/git_providers/utils.py[R331-336]

+    # Validate the file explicitly first: the shared custom_merge_loader runs with silent=True and
+    # would otherwise swallow TOML/security errors, skipping the file without surfacing a scoped
+    # configuration error. Parsing here makes malformed/forbidden config raise so it gets reported.
+    with open(repo_settings_file, "rb") as f:
+        parsed_toml = tomllib.load(f)
+    validate_file_security(parsed_toml, repo_settings_file)
Evidence
The new settings path parses TOML immediately in _apply_repo_settings_file() without checking file
size, while the existing custom loader explicitly checks size before parsing and would skip
oversized files; parsing early removes that protection for repo settings.

pr_agent/git_providers/utils.py[324-336]
pr_agent/custom_merge_loader.py[26-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
`_apply_repo_settings_file()` reads and parses the repo settings TOML (`tomllib.load`) before Dynaconf invokes `pr_agent.custom_merge_loader`, which previously enforced a `MAX_TOML_SIZE_IN_BYTES` check before parsing. This bypass means very large `.pr_agent.toml` files can be parsed eagerly and consume significant resources.
### Issue Context
- The custom Dynaconf loader has an explicit size check (`file_path.stat().st_size > MAX_TOML_SIZE_IN_BYTES`) before calling `tomllib.load`.
- The new pre-parse in `_apply_repo_settings_file()` happens unconditionally and therefore runs before that safeguard.
### Fix Focus Areas
- Add a size check on `repo_settings_file` **before** `tomllib.load()`. Reuse the same limit as `custom_merge_loader` (or define a shared constant) and raise an exception so the scoped error handling path can report it.
- pr_agent/git_providers/utils.py[324-337]

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


3. Repo-less provider crashes 🐞 Bug ≡ Correctness
Description
GithubProvider.get_repo_settings() now always calls _get_global_repo_settings(), which dereferences
self.repo via get_pr_owner_id() and uses self.github_client; when GithubProvider is instantiated
without __init__ (e.g., via __new__ in existing tests/helpers), this can raise AttributeError and
abort settings loading.
Code

pr_agent/git_providers/github_provider.py[R870-879]

+    def _get_global_repo_settings(self):
+        if not get_settings().config.use_global_settings_file:
+            return ""
+
+        try:
+            repo_owner = self.get_pr_owner_id()
+            if not repo_owner:
+                return ""
+            global_settings_repo = self.github_client.get_repo(f"{repo_owner}/pr-agent-settings")
+            return global_settings_repo.get_contents(".pr_agent.toml").decoded_content
Evidence
The new global-settings lookup calls get_pr_owner_id(), which directly reads self.repo, and will
crash if the attribute is missing. Existing unit tests construct GithubProvider via __new__ and do
not set repo, so this new call path is not safe for current usage patterns.

pr_agent/git_providers/github_provider.py[832-892]
pr_agent/git_providers/github_provider.py[803-807]
tests/unittest/test_github_provider_repo_settings.py[9-26]

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

## Issue description
`GithubProvider.get_repo_settings()` now always invokes `_get_global_repo_settings()`. `_get_global_repo_settings()` calls `get_pr_owner_id()` which uses `self.repo` directly, and it uses `self.github_client` without guarding. If the provider instance is created via `__new__` or otherwise partially initialized (common in unit tests and some utilities), `self.repo`/`self.github_client` may not exist, causing an `AttributeError` and preventing settings from being loaded.
### Issue Context
There are existing unit tests that construct `GithubProvider` via `__new__` and only set `repo_obj`; these will start failing once global settings lookup runs.
### Fix Focus Areas
- pr_agent/git_providers/github_provider.py[803-892]
- tests/unittest/test_github_provider_repo_settings.py[9-60]
### Suggested fix
- Make `get_pr_owner_id()` resilient: use `repo = getattr(self, "repo", None)` before accessing.
- In `_get_global_repo_settings()`, short-circuit if `getattr(self, "github_client", None)` or repo owner is missing.
- Optionally, update tests that use `__new__` to set `provider.repo` (and/or `provider.github_client`) explicitly.

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


View more (2)
4. Settings error misattributed 🐞 Bug ☼ Reliability
Description
apply_repo_settings loads all repo settings files (global+local) in one Dynaconf call, so a TOML
error in any file prevents all repo settings from applying; the exception handler then always
reports the *last* file as the failing scope/content. This can incorrectly label a global-file parse
error as "local" (or vice versa) and fails the stated requirement to accurately report global-file
errors without exposing content.
Code

pr_agent/git_providers/utils.py[R311-314]

+                        new_settings = Dynaconf(settings_files=repo_settings_files,
                                 # Disable all dynamic loading features
                                 load_dotenv=False,  # Don't load .env files
                                 envvar_prefix=False,  # Drop DYNACONF for env. variables
Evidence
apply_repo_settings constructs a single Dynaconf instance from all temp files and, on any
exception, derives category and settings_content from the last settings entry rather than the
file that actually failed; meanwhile the PR-comment redaction depends on `err['category'] ==
"global"`.

pr_agent/git_providers/utils.py[288-358]
pr_agent/git_providers/utils.py[379-406]
pr_agent/git_providers/github_provider.py[830-867]

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

## Issue description
`apply_repo_settings()` loads multiple settings files (e.g., `global` then `local`) in a single `Dynaconf(settings_files=[...])` call. If parsing fails for any file, no repo settings are applied at all, and the error is attributed to the last settings entry (`normalized_repo_settings[-1]`), which can misreport the failing scope and break global-error redaction/attribution requirements.
## Issue Context
- GitHub provider can return an ordered list like `[("global", ...), ("local", ...)]`.
- Current error reporting relies on `err['category']` to decide whether to redact (`global`) or show config content.
## Fix Focus Areas
- pr_agent/git_providers/utils.py[288-359]
- pr_agent/git_providers/utils.py[379-406]
- pr_agent/git_providers/github_provider.py[830-880]
## Implementation guidance
- Apply settings files **sequentially** in order (global then local): for each `(category, content)` create a temp file, try to load/merge it, and on failure emit an error tagged with that specific `category`.
- If `global` fails, report it as `global` (redacted) and continue to attempt applying `local` so valid local settings still take effect.
- Remove the `normalized_repo_settings[-1]` heuristic; error attribution should be per-file/scope.

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


5. Settings dict logged 🐞 Bug ⛨ Security
Description
apply_repo_settings logs new_settings.as_dict(), which now includes merged organization-global
settings and can contain secrets (tokens/keys) that should not appear in logs. This contradicts the
file’s own guidance elsewhere to avoid logging merged settings dicts because they may contain
secrets.
Code

pr_agent/git_providers/utils.py[R349-350]

     _reapply_env_overrides()
     get_logger().info(f"Applying repo settings:\n{new_settings.as_dict()}")
Evidence
The module explicitly warns not to log merged settings dictionaries due to secret leakage risk, but
apply_repo_settings still logs the full merged dict after loading repo settings (which now
includes org-global config).

pr_agent/git_providers/utils.py[228-234]
pr_agent/git_providers/utils.py[347-351]
pr_agent/git_providers/github_provider.py[830-867]

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

## Issue description
`apply_repo_settings()` logs `new_settings.as_dict()` after loading repo settings. With org-global settings enabled, this can leak organization-wide secrets into application/CI logs.
## Issue Context
The same module already documents that merged settings dicts must not be logged because they may contain secrets.
## Fix Focus Areas
- pr_agent/git_providers/utils.py[214-234]
- pr_agent/git_providers/utils.py[347-351]
## Implementation guidance
- Replace the `Applying repo settings:\n{new_settings.as_dict()}` log with a safe alternative (e.g., list of merged section names only, or a constant message indicating which scopes were applied).
- Avoid printing values; if debugging is needed, consider redacting known sensitive keys instead of full dict dumps.

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



Remediation recommended

6. TOML parsed twice 🐞 Bug ➹ Performance
Description
_apply_repo_settings_file() parses the settings TOML with tomllib.load() and then constructs a
Dynaconf instance that re-reads and re-parses the same file via pr_agent.custom_merge_loader. This
doubles file I/O and TOML parsing work for each applied scope (e.g., global + local) and can add
avoidable latency in webhook flows.
Code

pr_agent/git_providers/utils.py[R332-360]

+    # Enforce the same size cap as the loader BEFORE parsing, so an oversized file can't be fully
+    # read/parsed in-process (OOM/CPU) by the explicit validation below.
+    if os.path.getsize(repo_settings_file) > MAX_TOML_SIZE_IN_BYTES:
+        get_logger().warning(
+            f"Settings file too large (> {MAX_TOML_SIZE_IN_BYTES} bytes); skipping repo settings file")
+        return
+
+    # Validate the file explicitly first: the shared custom_merge_loader runs with silent=True and
+    # would otherwise swallow TOML/security errors, skipping the file without surfacing a scoped
+    # configuration error. Parsing here makes malformed/forbidden config raise so it gets reported.
+    with open(repo_settings_file, "rb") as f:
+        parsed_toml = tomllib.load(f)
+    # Use a generic name (not the temp path) so a SecurityError message can't leak the server's
+    # internal filesystem path into the PR configuration-error comment.
+    validate_file_security(parsed_toml, ".pr_agent.toml")
+
+    try:
+        dynconf_kwargs = {'core_loaders': [],
+             # Disable default loaders, otherwise TOML files load more than once.
+             'loaders': ['pr_agent.custom_merge_loader'],
+             # Merge sections and overwrite overlapping values without involving environment variables.
+             'merge_enabled': True
+         }
+        new_settings = Dynaconf(settings_files=[repo_settings_file],
+                                # Disable all dynamic loading features
+                                load_dotenv=False,  # Don't load .env files
+                                envvar_prefix=False,  # Drop DYNACONF for env. variables
+                                **dynconf_kwargs
+                                )
Evidence
The new _apply_repo_settings_file() explicitly parses the TOML before constructing Dynaconf, while
the custom Dynaconf loader also parses the TOML again from disk, causing duplicate parsing/I/O per
file.

pr_agent/git_providers/utils.py[332-360]
pr_agent/custom_merge_loader.py[56-82]

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

## Issue description
`_apply_repo_settings_file()` parses the repo settings file twice: once via `tomllib.load()` for validation and again via `Dynaconf(... loaders=['pr_agent.custom_merge_loader'] ...)`, which re-opens and parses the file. This duplicates work on every settings application.
### Issue Context
The pre-parse was added to force TOML/security errors to raise (since `custom_merge_loader` runs with `silent=True`). However, after validation, the already-parsed TOML can be used directly for merging into `get_settings()` without needing Dynaconf to parse again.
### Fix Focus Areas
- pr_agent/git_providers/utils.py[325-399]
- pr_agent/custom_merge_loader.py[55-101]
### Suggested approach
- After `parsed_toml = tomllib.load(f)` and `validate_file_security(parsed_toml, '.pr_agent.toml')`, avoid constructing a Dynaconf instance.
- Instead, treat `parsed_toml` as the settings dict (section -> keys/values), apply the same per-section allowlist filtering, and merge directly into `get_settings()` (preserving current behavior of section/key overriding).
- Keep `_reapply_env_overrides()` and the section-name-only logging.
- Ensure behavior stays identical for allowed/forbidden keys and for empty/invalid sections.

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


7. Global error message misleading 🐞 Bug ≡ Correctness
Description
handle_configurations_errors() hardcodes that invalid 'global' settings came from the
"organization's" global settings file, but global settings are group-level on GitLab.com and
workspace-level on Bitbucket Cloud. This can misdirect users on non-GitHub platforms when trying to
remediate a global settings failure.
Code

pr_agent/git_providers/utils.py[R423-425]

+                if config_type == "global":
+                    # Global content is redacted, so we never render it — skip decoding it entirely.
+                    body += "\n\nThe invalid configuration came from the organization's global settings file."
Evidence
The error message explicitly says "organization" for all global settings errors, while both provider
code and documentation describe global settings as group-level (GitLab) and workspace-level
(Bitbucket).

pr_agent/git_providers/utils.py[413-426]
pr_agent/git_providers/gitlab_provider.py[814-826]
pr_agent/git_providers/bitbucket_provider.py[98-106]
docs/docs/usage-guide/configuration_options.md[85-97]

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 `config_type == 'global'`, the configuration error comment states the invalid configuration came from the "organization's" global settings file. This is inaccurate for providers where the global scope is a GitLab top-level group or Bitbucket workspace.
### Issue Context
The PR adds global settings support across GitHub/GitLab(Bitbucket), and the repository/docs now explicitly describe different global scopes. The error message should not be GitHub-specific.
### Fix Focus Areas
- pr_agent/git_providers/utils.py[408-451]
- pr_agent/git_providers/gitlab_provider.py[814-826]
- pr_agent/git_providers/bitbucket_provider.py[98-106]
### Suggested approach
- Replace the hardcoded string with provider-neutral wording, e.g. "The invalid configuration came from the global settings repository (pr-agent-settings)."
- If you want to keep provider-specific phrasing, add a small provider hook (e.g. `git_provider.get_global_settings_scope_label()` returning `organization`/`group`/`workspace`) and format the message accordingly.

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


8. Bitbucket 403 not cached 🐞 Bug ➹ Performance
Description
BitbucketProvider._fetch_global_repo_settings() calls raise_for_status() for any non-404 response,
so a stable 403 (no access to <workspace>/pr-agent-settings) becomes an exception and is therefore
not cached by get_cached_global_settings(). This causes repeated Bitbucket API calls and warning
logs on every webhook event instead of quietly skipping global settings as documented.
Code

pr_agent/git_providers/bitbucket_provider.py[R108-116]

+    def _fetch_global_repo_settings(self, workspace):
+        # A missing settings repo/file (404) is an expected fallback -> return "" (cached). Other
+        # errors raise (via raise_for_status) so the caller does not cache a transient failure.
+        repo_url = f"https://api.bitbucket.org/2.0/repositories/{workspace}/pr-agent-settings"
+        repo_resp = requests.request("GET", repo_url, headers=self.headers)
+        if repo_resp.status_code == 404:  # no global settings repo
+            return ""
+        repo_resp.raise_for_status()
+        main_branch = (repo_resp.json().get('mainbranch') or {}).get('name')
Evidence
Bitbucket’s global-settings fetch only special-cases 404 before calling raise_for_status(), so 403
becomes an exception. The shared cache explicitly does not cache exceptions, meaning the same 403
will be retried on every call. This conflicts with the documented behavior that lack of access
should skip global settings and continue with local settings.

pr_agent/git_providers/bitbucket_provider.py[108-116]
pr_agent/git_providers/git_provider.py[24-56]
docs/docs/usage-guide/configuration_options.md[89-100]

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

## Issue description
`BitbucketProvider._fetch_global_repo_settings()` raises on HTTP 403, which `get_cached_global_settings()` intentionally does **not** cache. In the expected “token/app lacks read access to pr-agent-settings” case, this leads to repeated failed lookups and warning noise on every webhook event.
## Issue Context
Docs state that when PR-Agent lacks access to the `pr-agent-settings` repo, it should skip global configuration and continue with repo-local settings. For Bitbucket cloud, that stable fallback should be cached similarly to GitHub’s 403/404 behavior.
## Fix Focus Areas
- pr_agent/git_providers/bitbucket_provider.py[108-124]
- Treat `403` like `404` for both the repo lookup and the `.pr_agent.toml` fetch (return `""` so the empty result is cached).
- Avoid raising/logging warnings for this expected fallback path (optional; keep logging at debug if needed).

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


View more (9)
9. Caches transient global failures 🐞 Bug ☼ Reliability
Description
get_cached_global_settings() caches empty results, but providers return "" on transient
global-settings fetch errors (e.g., 5xx), so a temporary outage can disable global settings for the
full TTL (15 minutes) for that org/group/workspace. This can silently apply only repo-local settings
until cache expiry even after the provider/API recovers.
Code

pr_agent/git_providers/git_provider.py[R24-45]

+def get_cached_global_settings(cache_key, fetch_fn):
+    """Return the org/group/workspace global .pr_agent.toml via a bounded TTL cache.
+
+    Global settings change rarely, so caching avoids a provider API lookup (and repeated
+    403/404 fallbacks) on every webhook event. Empty/"not found" results are cached too, to
+    prevent repeated failed lookups. Oversized values are returned but not cached (to bound
+    memory). Pass a falsy cache_key to bypass the cache.
+    """
+    if not cache_key:
+        return fetch_fn()
+    now = time.monotonic()
+    entry = _GLOBAL_SETTINGS_CACHE.get(cache_key)
+    if entry is not None and entry[1] > now:
+        return entry[0]
+    value = fetch_fn()
+    value_size = len(value) if isinstance(value, (bytes, str)) else 0
+    if value_size <= _GLOBAL_SETTINGS_CACHE_MAX_VALUE_BYTES:
+        _GLOBAL_SETTINGS_CACHE[cache_key] = (value, now + _GLOBAL_SETTINGS_CACHE_TTL_SECONDS)
+        while len(_GLOBAL_SETTINGS_CACHE) > _GLOBAL_SETTINGS_CACHE_MAX_SIZE:
+            oldest_key = min(_GLOBAL_SETTINGS_CACHE, key=lambda k: _GLOBAL_SETTINGS_CACHE[k][1])
+            _GLOBAL_SETTINGS_CACHE.pop(oldest_key, None)
+    return value
Evidence
The cache stores any bytes/str value (including empty strings) until TTL expiry, and the GitHub
global-settings fetch returns an empty string for both expected (403/404) and unexpected exceptions;
therefore transient errors are cached as “no global settings.”

pr_agent/git_providers/git_provider.py[24-45]
pr_agent/git_providers/github_provider.py[894-910]

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_cached_global_settings()` currently caches empty results (`""`) the same way it caches “not found”, which can convert transient upstream/API failures into a persistent (TTL-length) loss of global settings.
### Issue Context
Providers (e.g., GitHub) return `""` for both expected fallbacks (403/404) and unexpected/transient errors. Because `get_cached_global_settings()` caches empty values, unexpected failures can suppress global settings until the cache expires.
### Fix Focus Areas
- pr_agent/git_providers/git_provider.py[24-45]
- pr_agent/git_providers/github_provider.py[894-910]
### Suggested fix approach
- Distinguish “negative cacheable” outcomes (e.g., 403/404 not found/inaccessible) from transient failures.
- Option A: allow `fetch_fn` to return `(value, cacheable: bool)`.
- Option B: treat `None` as “do not cache” and have providers return `None` on transient errors.
- Option C: add a separate shorter TTL for empty/error results, or only cache empty results when the provider explicitly indicates 403/404.

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


10. Config-branch errors masked 🐞 Bug ≡ Correctness
Description
GithubProvider.get_repo_settings() claims unexpected config-branch errors should propagate, but it
catches all GithubException from the CONFIG_BRANCH fetch and falls back to the default branch. This
can mask real API/permission failures for the config branch and cause unintended settings to be
applied.
Code

pr_agent/git_providers/github_provider.py[R846-858]

         # reason to fall back to the default branch. Unexpected errors are
         # left to propagate so they aren't masked by a silent fallback.
         try:
-                return self.repo_obj.get_contents(".pr_agent.toml", ref=config_branch).decoded_content
+                contents = self.repo_obj.get_contents(".pr_agent.toml", ref=config_branch).decoded_content
+                if settings_files:
+                    settings_files.append(("local", contents))
+                    return settings_files
+                return contents
         except GithubException as e:
             get_logger().warning(
                 f"Failed to load .pr_agent.toml from branch '{config_branch}', falling back to default branch",
                 artifact={"status": e.status, "error": str(e)},
             )
Evidence
The function’s comment states only missing branch/file should fall back and unexpected errors should
propagate, but the code catches any GithubException and proceeds to the default-branch load path.

pr_agent/git_providers/github_provider.py[844-865]

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 CONFIG_BRANCH read path in `GithubProvider.get_repo_settings()` catches all `GithubException` and falls back, contradicting the inline comment and potentially masking real errors (e.g., permission/rate-limit/server errors).
### Issue Context
The code comment says unexpected errors should propagate, but the `except GithubException` block triggers for any status.
### Fix Focus Areas
- pr_agent/git_providers/github_provider.py[844-859]
### Suggested fix approach
- Narrow the fallback to expected “missing” cases only:
- `except GithubException as e: if e.status == 404: ... fallback ... else: raise`
- Alternatively, if fallback is desired for more statuses, update the comment and ensure logging/telemetry clearly distinguishes expected missing vs unexpected failures.

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


11. Temp path leak 🐞 Bug ⛨ Security
Description
_apply_repo_settings_file() passes the temporary file path into validate_file_security(), and the
resulting exception string is embedded into the PR comment error message. This can leak internal
server filesystem paths (e.g., /tmp/...) to PR users when settings contain forbidden directives.
Code

pr_agent/git_providers/utils.py[R342-345]

+    with open(repo_settings_file, "rb") as f:
+        parsed_toml = tomllib.load(f)
+    validate_file_security(parsed_toml, repo_settings_file)
+
Evidence
The validation error message includes the supplied filename, and this filename is the
mkstemp-generated temp path; the error string is then rendered into the PR comment body verbatim.

pr_agent/custom_merge_loader.py[161-165]
pr_agent/git_providers/utils.py[294-307]
pr_agent/git_providers/utils.py[342-345]
pr_agent/git_providers/utils.py[415-424]

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

## Issue description
Repo/global settings are written to a temporary file and validated via `validate_file_security(parsed_toml, repo_settings_file)`. `validate_file_security` includes the provided `filename` in its `SecurityError` message, and `handle_configurations_errors` publishes that error message to PR comments. This leaks internal temp paths.
## Issue Context
Temp paths come from `tempfile.mkstemp(...)` and are not meaningful to users; they also disclose internal filesystem layout.
## Fix Focus Areas
- pr_agent/git_providers/utils.py[289-307]
- pr_agent/git_providers/utils.py[325-345]
- pr_agent/git_providers/utils.py[406-451]
- pr_agent/custom_merge_loader.py[103-170]
## Suggested fix approach
- Change `_apply_repo_settings_file` to accept a `scope`/`label` (e.g., "global"/"local").
- Call `validate_file_security(parsed_toml, f"{scope} repo settings")` (or similar) instead of passing the temp path.
- Ensure any surfaced exception message used in PR comments does not include the temp filename/path (either by changing the validation input label as above or by sanitizing the error string before publishing).

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


12. GitLab host check wrong 🐞 Bug ≡ Correctness
Description
GitLabProvider._get_global_repo_settings() treats any GITLAB.URL containing the substring
"gitlab.com" as GitLab.com, so a self-hosted GitLab instance whose hostname includes that substring
can incorrectly load and apply group-level global settings. This breaks the intended “GitLab.com
only” behavior and can silently change settings precedence on self-hosted deployments.
Code

pr_agent/git_providers/gitlab_provider.py[R823-824]

+        if not group or not self.gitlab_url or 'gitlab.com' not in self.gitlab_url:
+            return ""
Evidence
gitlab_url is a user-configured base URL, and _get_global_repo_settings() currently enables
global settings based on a substring check rather than hostname equality, which can incorrectly
treat some self-hosted URLs as GitLab.com.

pr_agent/git_providers/gitlab_provider.py[33-41]
pr_agent/git_providers/gitlab_provider.py[814-826]

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

## Issue description
`GitLabProvider._get_global_repo_settings()` uses a substring check (`'gitlab.com' in self.gitlab_url`) to decide whether the instance is GitLab.com. This can misclassify some self-hosted GitLab URLs and incorrectly enable global group settings.
### Issue Context
GitLab URL is configured via `GITLAB.URL`, and global settings are intended to apply only on GitLab.com.
### Fix Focus Areas
- pr_agent/git_providers/gitlab_provider.py[823-824]
### Proposed fix
Parse the URL and compare the hostname strictly (case-insensitive), e.g.:
- `host = urlparse(self.gitlab_url).hostname or ""`
- require `host.lower() == "gitlab.com"` (or an allowlist if needed)
Then gate `_get_global_repo_settings()` on that boolean instead of substring membership.

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


13. Cache may retain huge blobs 🐞 Bug ☼ Reliability
Description
get_cached_global_settings() stores the fetched global .pr_agent.toml content verbatim in a
process-wide cache that is bounded only by entry count (256), while settings files are allowed up to
100MB; in a long-running, multi-tenant webhook server this can retain large amounts of memory and
lead to OOM/instability. This is exacerbated by caching even when the file will later be skipped by
size checks during application.
Code

pr_agent/git_providers/git_provider.py[R16-39]

+_GLOBAL_SETTINGS_CACHE: dict = {}
+_GLOBAL_SETTINGS_CACHE_TTL_SECONDS = 15 * 60
+_GLOBAL_SETTINGS_CACHE_MAX_SIZE = 256
+
+
+def get_cached_global_settings(cache_key, fetch_fn):
+    """Return the org/group/workspace global .pr_agent.toml via a bounded TTL cache.
+
+    Global settings change rarely, so caching avoids a provider API lookup (and repeated
+    403/404 fallbacks) on every webhook event. Empty/"not found" results are cached too, to
+    prevent repeated failed lookups. Pass a falsy cache_key to bypass the cache.
+    """
+    if not cache_key:
+        return fetch_fn()
+    now = time.monotonic()
+    entry = _GLOBAL_SETTINGS_CACHE.get(cache_key)
+    if entry is not None and entry[1] > now:
+        return entry[0]
+    value = fetch_fn()
+    _GLOBAL_SETTINGS_CACHE[cache_key] = (value, now + _GLOBAL_SETTINGS_CACHE_TTL_SECONDS)
+    while len(_GLOBAL_SETTINGS_CACHE) > _GLOBAL_SETTINGS_CACHE_MAX_SIZE:
+        oldest_key = min(_GLOBAL_SETTINGS_CACHE, key=lambda k: _GLOBAL_SETTINGS_CACHE[k][1])
+        _GLOBAL_SETTINGS_CACHE.pop(oldest_key, None)
+    return value
Evidence
The cache stores the fetched settings value directly and allows up to 256 entries, while the
settings loader allows settings files up to 100MB, so the cache can retain large byte blobs in
memory for long-running processes.

pr_agent/git_providers/git_provider.py[16-39]
pr_agent/custom_merge_loader.py[8-10]
pr_agent/custom_merge_loader.py[68-70]

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_cached_global_settings()` caches global settings content in-process, but the cache is bounded only by number of keys (256) and stores full file bytes. Since settings files are allowed up to 100MB, the cache can retain very large blobs across multiple orgs/groups/workspaces in a long-running process.
### Issue Context
- The loader permits up to 100MB settings files.
- The cache retains values for 15 minutes and can hold up to 256 entries.
### Fix Focus Areas
- Add a byte-size bound (per-entry and/or total) for the cache and/or refuse to cache values over a safe threshold.
- Optionally: cache only negative lookups ("not found") and re-fetch positives, or reduce `_GLOBAL_SETTINGS_CACHE_MAX_SIZE`.
- pr_agent/git_providers/git_provider.py[16-39]
- pr_agent/custom_merge_loader.py[8-10]

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


14. Uncached global settings fetch 🐞 Bug ➹ Performance
Description
GithubProvider.get_repo_settings() now invokes _get_global_repo_settings() whenever
use_global_settings_file is enabled (it defaults to true), which performs a GitHub API lookup for
<owner>/pr-agent-settings each time settings are applied. In GitHub App flows that call
apply_repo_settings per webhook event, this adds repeated network calls (including repeated 403/404
fallbacks) increasing latency and rate-limit pressure.
Code

pr_agent/git_providers/github_provider.py[R833-837]

+        settings_files = []
+        global_settings = self._get_global_repo_settings()
+        if global_settings:
+            settings_files.append(("global", global_settings))
+
Evidence
The new GitHub provider logic always attempts to load org global settings first, and the global
settings helper performs live GitHub API calls. Separately, the GitHub App server calls
apply_repo_settings on every PR event (and explicitly notes it is expensive), and the default
configuration enables use_global_settings_file, making the repeated lookup the default behavior
unless explicitly disabled.

pr_agent/git_providers/github_provider.py[832-904]
pr_agent/servers/github_app.py[124-157]
pr_agent/settings/configuration.toml[5-26]

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

## Issue description
`GithubProvider.get_repo_settings()` calls `_get_global_repo_settings()` on every invocation when `config.use_global_settings_file` is true (default), and `_get_global_repo_settings()` performs GitHub API calls (`get_repo(...)/get_contents(...)`). In GitHub App/server flows, `apply_repo_settings()` is invoked per webhook event, so this can repeatedly hit the API (even for expected 403/404) and add avoidable latency/rate-limit pressure.
### Issue Context
- This is an intentional feature path, but it is currently uncached.
- A lightweight cache (including negative caching for 403/404) would substantially reduce repeated lookups for organizations that don’t have `pr-agent-settings` or where the App isn’t installed on it.
### Fix Focus Areas
- pr_agent/git_providers/github_provider.py[832-904]

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


15. Test leaks global config 🐞 Bug ☼ Reliability
Description
test_get_repo_settings_missing_local_file_logged_quietly mutates the global Dynaconf setting
CONFIG.CONFIG_BRANCH and does not restore it, so later tests can observe a modified global
configuration. This can make the unit suite order-dependent/flaky.
Code

tests/unittest/test_github_provider_settings.py[R62-82]

+def test_get_repo_settings_missing_local_file_logged_quietly(monkeypatch):
+    # A missing local .pr_agent.toml (404) is expected for most repos; it must be logged at debug,
+    # not warning.
+    from unittest.mock import patch
+
+    provider = _provider()  # no local .pr_agent.toml -> get_contents raises GithubException(404)
+    settings = get_settings()
+    original = settings.config.use_global_settings_file
+    settings.config.use_global_settings_file = False  # isolate the local-load path
+    monkeypatch.delenv("PR_AGENT_CONFIG_BRANCH", raising=False)
+    settings.set("CONFIG.CONFIG_BRANCH", "")  # ensure the default-branch load path runs
+    try:
+        with patch("pr_agent.git_providers.github_provider.get_logger") as mock_get_logger:
+            logger = mock_get_logger.return_value
+            result = provider.get_repo_settings()
+
+        assert result == ""
+        logger.warning.assert_not_called()
+    finally:
+        settings.config.use_global_settings_file = original
+
Evidence
The test sets CONFIG.CONFIG_BRANCH but does not restore it; since get_settings() returns a
shared singleton (global_settings) outside request context, this change persists beyond the test
and can affect later tests.

tests/unittest/test_github_provider_settings.py[62-82]
pr_agent/config_loader.py[47-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
A unit test mutates shared global settings (`settings.set("CONFIG.CONFIG_BRANCH", "")`) and only restores `use_global_settings_file` in `finally`, leaving `CONFIG.CONFIG_BRANCH` modified for subsequent tests.
### Issue Context
`get_settings()` returns a process-global singleton (`global_settings`) when no request context is active, so mutations persist across tests.
### Fix Focus Areas
- tests/unittest/test_github_provider_settings.py[62-82]
- pr_agent/config_loader.py[47-60]
### Suggested fix
In `test_get_repo_settings_missing_local_file_logged_quietly`, save the original value of `CONFIG.CONFIG_BRANCH` (via `settings.get("CONFIG.CONFIG_BRANCH", None)` or similar) and restore it in the `finally` block, or use `monkeypatch`/a fixture to scope the setting change to the test.

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


16. Local settings 404 warns 🐞 Bug ◔ Observability
Description
GithubProvider.get_repo_settings() now logs a warning for any exception when loading the local
.pr_agent.toml from the default branch; a missing file (404) is an expected condition for many
repos, so this change can create high-volume warning noise.
Code

pr_agent/git_providers/github_provider.py[R859-868]

try:
+            # more logical to take 'pr_agent.toml' from the default branch
 contents = self.repo_obj.get_contents(".pr_agent.toml").decoded_content
-            return contents
-        except Exception:
+            if config_branch and not settings_files:
+                return contents
+            settings_files.append(("local", contents))
+        except Exception as e:
+            get_logger().warning(f"Failed to load .pr_agent.toml file, error: {e}")
+
+        return settings_files if settings_files else ""
Evidence
The new default-branch settings load logs a warning for any exception, while another file-fetching
path in the same provider treats 404 as expected and returns empty content without warning; this
indicates missing files are normal and should not produce warnings.

pr_agent/git_providers/github_provider.py[859-868]
pr_agent/git_providers/github_provider.py[911-917]

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 the local `.pr_agent.toml` is missing on the default branch, PyGithub typically raises `GithubException(404)`. The new code catches `Exception` and logs a `warning` for all failures, which will be noisy in normal operation because repo settings are optional.
### Issue Context
Elsewhere in the same provider, missing files are treated as expected and handled silently.
### Fix Focus Areas
- pr_agent/git_providers/github_provider.py[859-868]
- pr_agent/git_providers/github_provider.py[911-917]
### Suggested fix
- Catch `GithubException` explicitly when reading the default-branch `.pr_agent.toml`.
- For `e.status == 404`, return `settings_files` (if global exists) or `""` without warning (or log at debug).
- Keep `warning` for unexpected statuses/errors (e.g., 500s, timeouts).

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


17. Config decode may crash 🐞 Bug ☼ Reliability
Description
handle_configurations_errors() decodes err['settings'] bytes with a strict default decode; if the
stored bytes are not UTF-8 decodable, this raises UnicodeDecodeError and prevents posting the
configuration-error comment.
Code

pr_agent/git_providers/utils.py[R405-408]

+                settings_content = err['settings']
+                configuration_file_content = (
+                    settings_content.decode() if isinstance(settings_content, bytes) else settings_content
+                )
Evidence
The error handler unconditionally decodes bytes with the default codec, and apply_repo_settings
propagates raw bytes into err['settings']; this combination can cause the reporting path itself to
fail. A safer decode pattern already exists elsewhere in the GitHub provider (errors='replace').

pr_agent/git_providers/utils.py[270-310]
pr_agent/git_providers/utils.py[403-408]
pr_agent/git_providers/github_provider.py[908-910]

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

## Issue description
`handle_configurations_errors()` does `settings_content.decode()` when `settings_content` is `bytes`. If the bytes are not valid UTF-8, the error handler crashes (UnicodeDecodeError) and the user never receives the configuration-error report.
### Issue Context
`apply_repo_settings()` stores raw bytes into `err['settings']` (it writes provider-returned bytes directly to a temp file), so the error handler must be robust to arbitrary bytes.
### Fix Focus Areas
- pr_agent/git_providers/utils.py[270-310]
- pr_agent/git_providers/utils.py[398-440]
### Suggested fix
- Decode using `settings_content.decode("utf-8", errors="replace")`.
- Alternatively, wrap decode in `try/except UnicodeDecodeError` and fall back to a redacted placeholder.
- Also consider skipping decoding entirely for `config_type == "global"` since the content is intentionally not displayed.

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


Grey Divider

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

Qodo Logo

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

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 0a753ee

avidspartan1 and others added 3 commits July 4, 2026 16:34
Load a shared .pr_agent.toml from an <org>/pr-agent-settings repository
(gated behind use_global_settings_file) and merge it beneath the repo's
local settings so organizations can centralize defaults. get_repo_settings
now returns an ordered (scope, content) list, and apply_repo_settings
merges global -> local. Configuration errors from the global file report
the source without echoing its contents into the PR.
…ution

apply_repo_settings loaded global+local settings in a single Dynaconf call,
so a parse/apply error in any file failed all of them and reported the error
against the last source (mis-labeling e.g. a global-file error as 'local' and
breaking global redaction). Apply each source independently and in order via
_apply_repo_settings_file(); a failing source is reported against its own scope
and no longer prevents the other valid sources from taking effect.
@naorpeled
naorpeled force-pushed the feat-github-org-global-settings branch from 0a753ee to 2fc3ff7 Compare July 4, 2026 13:40
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 2fc3ff7

… test fakes)

- handle_configurations_errors: name the persistent comment/check run per scope
  (config-errors-<scope>) so multiple settings errors don't overwrite each other
  in GitHub check-run mode
- _get_global_repo_settings: treat a missing/inaccessible <owner>/pr-agent-settings
  (GithubException 403/404) as an expected fallback logged at debug, not warning
- test fakes: FakeRepo.get_contents accepts ref= and raises GithubException(404)
  like PyGithub, so tests don't break when PR_AGENT_CONFIG_BRANCH is set
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 8c8b3d1

… them

The shared custom_merge_loader runs with silent=True, so malformed TOML and
forbidden-directive SecurityErrors were logged and swallowed — meaning the new
per-scope error reporting never fired for the most common bad-config cases.
_apply_repo_settings_file now parses and security-validates the file explicitly
first, so invalid global/local .pr_agent.toml raises and is reported against the
correct scope (global redacted). Removes two xfail markers that documented this
gap and were verifying the now-fixed behavior.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 590bc32

…, decode)

- _get_global_repo_settings: guard providers built via __new__ (no repo/client)
  so global-settings loading can't raise AttributeError and abort settings
- get_repo_settings: treat a missing local .pr_agent.toml (404) as an expected
  condition logged at debug, not a warning (avoids high-volume log noise)
- handle_configurations_errors: decode settings bytes with errors=replace so
  non-UTF-8 content can't crash the configuration-error comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 980e620

_apply_repo_settings_file parses the file with tomllib before Dynaconf runs, which
bypassed the loader's MAX_TOML_SIZE_IN_BYTES guard — an oversized .pr_agent.toml
could be fully parsed in-process (OOM/CPU) before being skipped. Promote the cap to
a module-level constant in custom_merge_loader and check the file size first.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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

- test_get_repo_settings_missing_local_file_logged_quietly: save/restore
  CONFIG.CONFIG_BRANCH so it doesn't leak global config and make the suite flaky
- apply_repo_settings cleanup: include the exception reason in the error log message
  (loguru does not render an exception passed as an extra positional arg)
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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

The org-level global settings feature (<org>/pr-agent-settings) is implemented
only for GitHub in this project; the section previously claimed GitLab/Bitbucket
cloud support it does not have. Also clarify the file is read from the settings
repo's default branch and merged beneath the repo-local config.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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

Extend <org>/pr-agent-settings global configuration beyond GitHub:
- GitLab (cloud): read <top-level-group>/pr-agent-settings (GitLab.com only)
- Bitbucket (cloud): read <workspace>/pr-agent-settings

Add a shared in-process TTL cache (get_cached_global_settings) so long-running
webhook/app deployments don't re-fetch the global settings (and repeated 403/404
fallbacks) on every event — addressing the uncached-fetch concern. CLI/CI runs are
short-lived and fetch once per invocation. Docs updated to reflect platform support
and the in-process caching scope.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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

…s cache value size

- bitbucket get_repo_settings: only treat a 200 response as a found local .pr_agent.toml;
  a 401/403/500 body must not be parsed as TOML (or echoed into a config-error comment)
- get_cached_global_settings: skip caching oversized values (>1MB) so the process-wide
  cache can't retain large blobs (bounded independently of the 100MB apply-time cap)
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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

…ings

- gitlab: match the host exactly (urlparse hostname == 'gitlab.com') instead of a
  substring check, so self-hosted instances like 'mygitlab.com' don't load group settings
- handle_configurations_errors: only decode settings content when it will be shown
  (non-global scope); global content is redacted, so skip the decode
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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

_apply_repo_settings_file passed the temporary file path to validate_file_security,
whose SecurityError message is surfaced in the PR configuration-error comment — leaking
an internal /tmp path to PR users on forbidden directives. Pass a generic '.pr_agent.toml'
name instead so the error identifies the file without the server path.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 5fcc685

…h errors, verify temp write

- get_cached_global_settings + providers: fetch functions return "" only for expected
  not-found (404/403); transient/unexpected errors raise and are NOT cached, so a temporary
  outage no longer disables global settings for the full TTL
- github get_repo_settings: only fall back to the default branch on a 404 config-branch
  error; other errors propagate instead of silently applying unintended settings
- apply_repo_settings: write the temp settings file via os.fdopen so a partial os.write
  can't silently truncate it
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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

…-settings outcome

Align Bitbucket with GitHub: a 403 to the pr-agent-settings repo/file is a stable
'no access' condition, not a transient error, so return "" (cached) instead of
raising and re-fetching on every event. Other statuses still raise (not cached).
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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

…se); neutral global error text

- _apply_repo_settings_file: apply the dict already parsed by tomllib instead of re-reading
  the file through a second Dynaconf/custom_merge_loader pass — avoids double file I/O and
  TOML parsing per scope (and drops the phantom LOAD_DOTENV section). Section merge/host-key
  behavior is preserved (case-insensitive lookup; list/dict values replace)
- handle_configurations_errors: global settings are org/group/workspace-scoped across
  providers, so the error text now names the 'pr-agent-settings' repository instead of
  GitHub-specific 'organization'
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants