Skip to content

fix(advisor): wait for required PR checks#3977

Merged
cv merged 4 commits into
mainfrom
fix/pr-review-advisor-wait-required
May 21, 2026
Merged

fix(advisor): wait for required PR checks#3977
cv merged 4 commits into
mainfrom
fix/pr-review-advisor-wait-required

Conversation

@cv
Copy link
Copy Markdown
Collaborator

@cv cv commented May 21, 2026

Summary

Make the PR Review Advisor wait for required PR checks and the E2E recommendation before launching model analysis. This should reduce early, low-context reviews where the advisor reports blocked primarily because CI is still pending.

Changes

  • Add a deterministic required-check wait loop to tools/pr-review-advisor/analyze.mts that reads required contexts from repository rulesets, falls back to configured contexts, and excludes the advisor's own check to avoid self-deadlock.
  • Update CI gate derivation to evaluate known required contexts separately from optional pending checks while still reporting non-required pending/failed counts.
  • Configure .github/workflows/pr-review-advisor.yaml with wait timeout/poll settings, the E2E Advisor context, and documentation that the workflow must remain advisory/non-required.
  • Add tests for ruleset extraction, pending required-check detection, and required-context CI gate behavior.

Type of Change

  • Code change (feature, bug fix, or refactor)
  • Code change with doc updates
  • Doc only (prose changes, no code sample modifications)
  • Doc only (includes code sample changes)

Verification

  • npx prek run --all-files passes
  • npm test passes
  • Tests added or updated for new or changed behavior
  • No secrets, API keys, or credentials committed
  • Docs updated for user-facing behavior changes
  • make docs builds without warnings (doc changes only)
  • Doc pages follow the style guide (doc changes only)
  • New doc pages include SPDX header and frontmatter (new pages only)

Signed-off-by: Carlos Villela cvillela@nvidia.com

Summary by CodeRabbit

  • New Features

    • PR Review Advisor now deterministically waits for repository-required status checks (with configurable fallback/additional contexts), polling until completion or timeout before analysis; CI gate logic respects required-check outcomes.
  • Documentation

    • Clarified workflow policy and guidance to avoid making the advisor itself a required check.
  • Tests

    • Expanded tests for required-check discovery, fallback behavior, wait/poll logic, head-staleness aborts, and CI gate outcomes.
  • Chores

    • Increased workflow execution timeout and added related workflow environment settings.

Review Change Stack

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv cv self-assigned this May 21, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 21, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 864058b7-6d24-4340-9e31-bddc1561dc66

📥 Commits

Reviewing files that changed from the base of the PR and between 8c715a5 and 9a47df0.

📒 Files selected for processing (2)
  • test/pr-review-advisor.test.ts
  • tools/pr-review-advisor/analyze.mts

📝 Walkthrough

Walkthrough

Adds an optional deterministic wait for repository-required GitHub status checks before PR Review Advisor runs analysis: ruleset discovery with env fallback, polling of statusCheckRollup, required-context-aware CI gate derivation, workflow timeout/env updates, tests, and README updates.

Changes

Required Status Check Waiting Integration

Layer / File(s) Summary
Required Check Types and Constants
tools/pr-review-advisor/analyze.mts
New polling/timeout constants and regex filters; DeterministicReviewContext extended with requiredStatusCheckContexts and additionalWaitContexts; new internal types (CheckStatusSummary, RequiredCheckWaitState).
Required Check Waiting Implementation
tools/pr-review-advisor/analyze.mts
Adds waitForRequiredChecksBeforeAnalysis invoked from main(): discovers required contexts from rulesets with PR_REVIEW_ADVISOR_REQUIRED_CHECK_FALLBACK_CONTEXTS fallback, appends additional wait contexts, filters advisor contexts, polls GitHub GraphQL statusCheckRollup, tracks pending required contexts and head OID changes, and enforces a wait timeout; integrates required/additional contexts into deterministic output.
CI Gate Status Enhancement
tools/pr-review-advisor/analyze.mts
Refactors CI derivation: deriveGateStatus(..., requiredStatusCheckContexts: string[] = []), extractStatusCheckSummaries, deriveCiGateStatus, and helpers that distinguish required-context failures vs pending/missing while preserving non-required evidence.
Workflow Job Configuration
.github/workflows/pr-review-advisor.yaml
review job timeout-minutes increased and environment variables added: PR_REVIEW_ADVISOR_WAIT_FOR_REQUIRED_CHECKS, PR_REVIEW_ADVISOR_WAIT_TIMEOUT_SECONDS, PR_REVIEW_ADVISOR_WAIT_POLL_INTERVAL_MS, PR_REVIEW_ADVISOR_REQUIRED_CHECK_FALLBACK_CONTEXTS, PR_REVIEW_ADVISOR_WAIT_ADDITIONAL_CONTEXTS.
Test Coverage and YAML Assertions
test/pr-review-advisor.test.ts
Import refactor to multi-line named import, fixture metadata extended with requiredStatusCheckContexts and additionalWaitContexts, restoreEnv helper, and multiple new tests for ruleset extraction, fallback contexts, CI gate outcomes, pending/wait behavior; workflow YAML assertions updated to verify timeout and new env vars.
Documentation
tools/pr-review-advisor/README.md
Documents deterministic wait behavior before model analysis, ruleset discovery fallback to PR_REVIEW_ADVISOR_REQUIRED_CHECK_FALLBACK_CONTEXTS, and guidance that the advisor workflow must not be set as a required status check.

Sequence Diagram(s)

sequenceDiagram
  participant main as main()
  participant waitFunc as waitForRequiredChecksBeforeAnalysis()
  participant ruleset as extractRequiredStatusChecksFromRulesets()
  participant github as GitHub GraphQL
  participant derive as deriveGateStatus()
  main->>waitFunc: headSha
  waitFunc->>ruleset: fetch rulesets(baseBranch)
  ruleset-->>waitFunc: requiredContexts
  loop poll until timeout or all terminal
    waitFunc->>github: query statusCheckRollup(headSha)
    github-->>waitFunc: status summaries
    waitFunc->>waitFunc: compute pendingRequiredContexts()
  end
  waitFunc-->>main: required/additional contexts
  main->>derive: pass requiredStatusCheckContexts
  derive-->>main: gateStatus with required-context evidence
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • NVIDIA/NemoClaw#3834: Introduced the initial PR Review Advisor workflow and analyze.mts module; this change extends it with required-check waiting.

Suggested labels

fix, CI/CD, enhancement: testing

Suggested reviewers

  • ericksoa
  • jyaunches
  • cjagwani

Poem

🐰 I sat by CI's glowing gate,
Counting checks that come and wait,
I polled and hummed until they done,
Then piped the verdict, one by one.
Hoppity code — the review's begun.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'fix(advisor): wait for required PR checks' directly and accurately summarizes the primary change: implementing a wait mechanism for required PR checks in the advisor workflow before model analysis.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/pr-review-advisor-wait-required

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 21, 2026

E2E Advisor Recommendation

Required E2E: None
Optional E2E: None

Workflow run

Full advisor summary

E2E Recommendation Advisor

Base: origin/main
Head: HEAD
Confidence: high

Required E2E

  • None. No NemoClaw product E2E is recommended. This PR changes CI advisory tooling and its unit coverage only; it cannot affect installer/onboarding behavior, sandbox lifecycle, credentials, network policy, inference routing, deployment, or real assistant user flows. Targeted unit/workflow tests for the PR Review Advisor are the appropriate validation.

Optional E2E

  • None.

New E2E recommendations

  • None.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 21, 2026

PR Review Advisor

Recommendation: blocked
Confidence: high
Analyzed HEAD: 9a47df04b5113568d32118fe4302acb73cefc4bf
Findings: 1 blocker(s), 3 warning(s), 0 suggestion(s)

This is an automated advisory review. A human maintainer must make the final merge decision.

Limitations: Automated advisory review only; a human maintainer must make the final merge decision.; CI was still pending for head SHA 9a47df0 in the trusted context.; GitHub reports mergeStateStatus=BLOCKED.; No linked issues were present, so acceptance coverage is based on PR-stated clauses and trusted PR/E2E Advisor comments only.; Review relied on the provided trusted deterministic context and visible diff; no commands or tests were executed.

Workflow run

Full advisor summary

PR Review Advisor

Base: origin/main
Head: HEAD
Analyzed SHA: 9a47df04b5113568d32118fe4302acb73cefc4bf
Recommendation: blocked
Confidence: high

The implementation appears directionally sound and improves stale-run handling, but merge readiness is blocked by pending head-SHA CI, BLOCKED merge state, and unsettled E2E Advisor status for a privileged workflow/enforcement change.

Gate status

  • CI: pending — Trusted context reports 11 pending status context(s) for head SHA 9a47df0; GraphQL shows E2E recommendation, wsl-e2e, PR review advisor, CodeQL jobs, checks, ShellCheck SARIF, unit-vitest-linux, sandbox image builds, and CodeRabbit still in progress/queued/pending.
  • Mergeability: fail — mergeStateStatus=BLOCKED for PR fix(advisor): wait for required PR checks #3977 at head SHA 9a47df0.
  • Review threads: pass — Trusted GraphQL reports 1 review thread and it is resolved.
  • Risky code tested: warning — Risky areas detected (workflow/enforcement); test/pr-review-advisor.test.ts changed substantially, but coverage still needs semantic review and settled CI.

🔴 Blockers

  • Current head SHA gates are not settled: The PR changes workflow/enforcement behavior in a secret-bearing advisory workflow, but trusted status information for the requested head SHA still has pending checks and GitHub reports the PR as blocked. Merging before current-head checks settle would undermine the PR's goal of producing reviews after required checks have stabilized.
    • Recommendation: Wait for all required and relevant status checks for 9a47df0 to complete successfully and for mergeStateStatus to leave BLOCKED before considering merge readiness.
    • Evidence: Trusted gateStatus.ci=pending with 11 pending status contexts; GraphQL statusCheckRollup includes E2E recommendation IN_PROGRESS, PR review advisor IN_PROGRESS, CodeQL IN_PROGRESS, checks IN_PROGRESS, ShellCheck SARIF IN_PROGRESS, unit-vitest-linux QUEUED, build-sandbox-images QUEUED, build-sandbox-images-arm64 QUEUED, and CodeRabbit PENDING; mergeStateStatus=BLOCKED.

🟡 Warnings

  • Secret-bearing write-scoped workflow remains high risk (.github/workflows/pr-review-advisor.yaml:46): The workflow retains write permissions and model/API credentials while adding required-check waiting and increasing timeout. Existing trusted-code-boundary safeguards remain visible, but workflow/enforcement changes in a secret-bearing job are high-risk and require successful head-SHA CI plus human review.
    • Recommendation: Keep the pull_request same-repository guard, avoid pull_request_target, keep actions pinned by full SHA, retain trusted main checkout and persist-credentials=false, keep npm lifecycle scripts disabled, and ensure no PR-controlled strings are executed as shell code.
    • Evidence: Workflow uses pull_request and workflow_dispatch, requests pull-requests:write and issues:write, references PR_REVIEW_ADVISOR_API_KEY/OPENAI_API_KEY/GH_TOKEN, installs a pinned Pi SDK with --ignore-scripts, checks out trusted advisor code from main, and increases timeout-minutes from 20 to 40.
  • Wait-loop behavior is only partially proven by unit tests (test/pr-review-advisor.test.ts:1): The added tests cover important helper and gate behavior, including ruleset extraction, fallback contexts, base-ref normalization, required CI gate pass/fail behavior, pending/missing contexts, and stale-head assertion. However, complete workflow-level behavior is not fully proven, including polling timeout continuation, end-to-end self-check exclusion, stale-run abort behavior through main(), additional E2E wait context inclusion in a real rollup, and trusted workflow invariants under workflow_dispatch.
    • Recommendation: Add focused mocked-GitHub tests or a lightweight workflow-dispatch smoke harness that verifies waiting on configured required contexts, excluding the advisor's own context, aborting stale runs without posting stale analysis, handling timeout paths, and including the E2E recommendation context without executing PR-controlled code.
    • Evidence: E2E Advisor recommends a future pr-review-advisor-ci-integration smoke test; current test additions exercise helpers such as extractRequiredStatusChecksFromRulesets, discoverRequiredStatusCheckContexts, pendingRequiredContexts, deriveGateStatus, and assertPrHeadStillCurrent but do not fully execute the workflow/job path.
  • E2E Advisor recommendation is not settled for the current head SHA: A trusted E2E Advisor comment exists and recommends no product runtime E2E, but the current head SHA's E2E recommendation check is still in progress. For this workflow/enforcement change, the recommendation should be considered not fully verified until the check completes for 9a47df0.
    • Recommendation: Wait for the E2E recommendation check for the current head SHA to finish and confirm it still recommends no required E2E, or that any newly required jobs pass.
    • Evidence: Issue comment contains with Required E2E: None; GraphQL statusCheckRollup for head SHA 9a47df0 shows CheckRun "E2E recommendation" status IN_PROGRESS.

🔵 Suggestions

  • None.

Acceptance coverage

  • partial — Make the PR Review Advisor wait for required PR checks and the E2E recommendation before launching model analysis.: tools/pr-review-advisor/analyze.mts calls waitForRequiredChecksBeforeAnalysis(headSha, baseRef) before diff/model analysis and workflow sets PR_REVIEW_ADVISOR_WAIT_ADDITIONAL_CONTEXTS="E2E recommendation". Partial until current-head required checks and the E2E recommendation check complete successfully.
  • met — Add a deterministic required-check wait loop to tools/pr-review-advisor/analyze.mts that reads required contexts from repository rulesets, falls back to configured contexts, and excludes the advisor's own check to avoid self-deadlock.: Diff adds waitForRequiredChecksBeforeAnalysis, discoverRequiredStatusCheckContexts, fetchRequiredStatusChecks, extractRequiredStatusChecksFromRulesets, pendingRequiredContexts, and isAdvisorCheckContext; workflow configures PR_REVIEW_ADVISOR_REQUIRED_CHECK_FALLBACK_CONTEXTS; derive/wait paths filter advisor contexts.
  • met — Update CI gate derivation to evaluate known required contexts separately from optional pending checks while still reporting non-required pending/failed counts.: deriveGateStatus now accepts requiredStatusCheckContexts, extractStatusCheckSummaries normalizes CheckRun/StatusContext nodes, deriveCiGateStatus reports required failures/pending separately, and tests cover pass with optional pending plus required-context failures/pending.
  • met — Configure .github/workflows/pr-review-advisor.yaml with wait timeout/poll settings, the E2E Advisor context, and documentation that the workflow must remain advisory/non-required.: .github/workflows/pr-review-advisor.yaml sets PR_REVIEW_ADVISOR_WAIT_FOR_REQUIRED_CHECKS=1, PR_REVIEW_ADVISOR_WAIT_TIMEOUT_MS=900000, PR_REVIEW_ADVISOR_WAIT_POLL_MS=30000, PR_REVIEW_ADVISOR_WAIT_ADDITIONAL_CONTEXTS="E2E recommendation", fallback contexts, and comments that the job is advisory and must not be required; README repeats the advisory/non-required warning.
  • met — Add tests for ruleset extraction, pending required-check detection, and required-context CI gate behavior.: test/pr-review-advisor.test.ts adds tests for active branch ruleset extraction, analyzed base ref normalization/discovery, fallback when rulesets cannot be read, required-context CI pass/fail behavior, empty rollups staying pending, and pending/missing required contexts.
  • met — fix(advisor): abort stale wait runs: tools/pr-review-advisor/analyze.mts adds assertPrHeadStillCurrent, StaleAdvisorRunError, and wait-loop logic that throws when GitHub reports a latest headRefOid different from the workflow head SHA; tests assert stale-head detection throws.
  • unknownnpx prek run --all-files passes: The PR body checkbox claims this passed, but PR-provided text is untrusted and trusted statusCheckRollup for the current head SHA still has pending checks.
  • unknownnpm test passes: The PR body checkbox claims this passed, but trusted GraphQL statusCheckRollup shows unit-vitest-linux QUEUED for the current head SHA.
  • met — Tests added or updated for new or changed behavior: test/pr-review-advisor.test.ts increased substantially and covers ruleset extraction, fallback behavior, base-ref normalization/discovery, stale-head detection, required CI gate behavior, workflow env assertions, and pending required contexts.
  • met — No secrets, API keys, or credentials committed: The diff references GitHub secrets and github.token but does not add literal API keys, tokens, passwords, PEM files, or credential JSON. Checkout steps retain persist-credentials=false.
  • met — Docs updated for user-facing behavior changes: tools/pr-review-advisor/README.md documents the new wait step, repository ruleset discovery, fallback contexts, E2E Advisor wait context, and advisory/non-required status requirement.
  • partial — Required E2E: None. No existing runtime E2E should be required. The changes are confined to advisory CI tooling, tests, and documentation and do not affect NemoClaw installer/onboarding, sandbox lifecycle, credentials in runtime flows, network policy, inference routing, deployment, or real assistant user flows. Existing product E2E suites such as nightly-e2e or scenario runner would not provide meaningful coverage for this PR Review Advisor wait logic.: Trusted E2E Advisor comment recommends no product runtime E2E, but the E2E recommendation check is IN_PROGRESS for current head SHA 9a47df0.
  • partial — New E2E recommendations - pr-review-advisor-ci-integration (medium): No existing NemoClaw E2E job validates the PR Review Advisor's GitHub status-check wait behavior, ruleset discovery fallback, or sticky-comment flow in a real pull_request/workflow_dispatch environment. Add a lightweight integration or workflow-dispatch smoke test using mocked GitHub API/status contexts rather than running product runtime E2E.: Unit tests cover helper-level behavior, but no workflow-level integration smoke or full mocked GitHub API/status-rollup harness is shown for complete wait behavior, timeout continuation, advisor-context exclusion, stale-run handling, and sticky-comment flow.
  • missing — Suggested test: Create a PR Review Advisor integration smoke that dispatches the advisory workflow in analysis-disabled or mocked mode and verifies it waits on configured required contexts without executing PR-controlled code.: No new workflow-dispatch smoke or analysis-disabled mocked integration test is present in the changed files; current coverage is in test/pr-review-advisor.test.ts unit tests.

Security review

  • pass — Secrets and Credentials: No hardcoded secrets, API keys, passwords, tokens, PEM files, or credential JSON are introduced. The workflow references credentials through GitHub secrets and github.token/GH_TOKEN; checkout steps use persist-credentials=false.
  • pass — Input Validation and Data Sanitization: New parsing of context lists, ruleset JSON, base refs, and GraphQL status data uses structured accessors and string normalization rather than shell execution. The prior base-branch concern is addressed by threading baseRef into wait/discovery paths and adding normalizeBaseBranch tests.
  • warning — Authentication and Authorization: The workflow retains write-scoped issues and pull-requests permissions to post advisory comments in a secret-bearing job. Same-repository pull_request gating and trusted main checkout mitigate untrusted-code execution, but this remains a privileged workflow path needing human review.
  • pass — Dependencies and Third-Party Libraries: No new dependencies are added. Existing Pi SDK install remains version-pinned via PI_SDK_VERSION and uses --ignore-scripts, --no-save, --package-lock=false, and a --before timestamp.
  • pass — Error Handling and Logging: Ruleset discovery catches failures and falls back to configured contexts; polling failures are logged; timeout continues to analysis with pending-context evidence; stale-head detection aborts stale wait runs. No secret values are newly logged in the visible diff.
  • pass — Cryptography and Data Protection: Not applicable — the change does not add or modify cryptographic operations or data-protection primitives.
  • warning — Configuration and Security Headers: The PR modifies a secret-bearing GitHub Actions workflow with write permissions and increases timeout to 40 minutes. Safeguards remain visible: pull_request rather than pull_request_target, same-repo guard, pinned actions by full SHA, trusted main checkout, disabled npm lifecycle scripts, and advisory/non-required documentation.
  • warning — Security Testing: Security-relevant workflow/enforcement tests were expanded, including ruleset extraction, fallback, base-ref normalization/discovery, stale-head detection, and required-check gate behavior. Complete wait-loop behavior, timeout, self-check exclusion in full workflow context, stale-run behavior through main(), and workflow-level trusted-boundary invariants are not fully proven; CI is still pending.
  • warning — Holistic Security Posture: The design improves advisor posture by waiting for required checks, excluding the advisor's own context to reduce circular waits, and aborting stale runs. Overall merge posture is not ready because current-head CI is pending, mergeStateStatus is BLOCKED, and E2E Advisor status is still in progress.

Test / E2E status

  • Test depth: e2e_required — Runtime/sandbox/infrastructure paths need real execution coverage: .github/workflows/pr-review-advisor.yaml, tools/pr-review-advisor/README.md, tools/pr-review-advisor/analyze.mts. E2E Advisor says no existing product runtime E2E is required, but the E2E recommendation check is pending for the current head and a future pr-review-advisor-ci-integration/mock GitHub harness is recommended for full wait-loop coverage.
  • E2E Advisor: missing
  • Missing for analyzed SHA: E2E recommendation check is IN_PROGRESS for head SHA 9a47df04b5113568d32118fe4302acb73cefc4bf.

✅ What looks good

  • Codebase drift evidence shows the changed files still exist and recent history is related to active PR Review Advisor work; no open PR overlaps were reported.
  • The resolved CodeRabbit thread's base-ref ruleset concern appears addressed by passing baseRef into wait/discovery paths and adding normalizeBaseBranch regression coverage.
  • The workflow continues to use pull_request rather than pull_request_target and restricts secret-bearing pull_request execution to upstream NVIDIA/NemoClaw PRs.
  • Trusted-code boundary is preserved: advisor implementation runs from the trusted main checkout while PR content is checked out as read-only analysis data.
  • Actions remain pinned by full commit SHA and checkout uses persist-credentials=false.
  • The advisor self-context is filtered from required contexts to reduce circular wait risk.
  • The new stale-head assertion reduces the risk of posting stale analysis after the PR head advances during the wait loop.
  • Tests were expanded for ruleset extraction, fallback, base-ref normalization/discovery, required-context CI pass/fail behavior, stale-head detection, workflow env assertions, and pending/missing required contexts.
  • README documentation explicitly warns that the PR Review Advisor must remain advisory and non-required.

Review completeness

  • Automated advisory review only; a human maintainer must make the final merge decision.
  • CI was still pending for head SHA 9a47df0 in the trusted context.
  • GitHub reports mergeStateStatus=BLOCKED.
  • No linked issues were present, so acceptance coverage is based on PR-stated clauses and trusted PR/E2E Advisor comments only.
  • Review relied on the provided trusted deterministic context and visible diff; no commands or tests were executed.
  • Human maintainer review required: yes

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tools/pr-review-advisor/analyze.mts`:
- Around line 413-416: The code sets baseBranch from env defaults which makes
fetchRequiredStatusChecks(repo, token, baseBranch) use "main" on manual runs;
update baseBranch to prefer the analyzed/parsed CLI base value (the variable
computed earlier in the analysis flow, e.g. the parsed "base" or
"analyzedBaseBranch" value) and only fall back to
process.env.PR_REVIEW_ADVISOR_REQUIRED_CHECK_BASE / process.env.GITHUB_BASE_REF
/ "main" if that analyzed base is undefined; apply the same change where
baseBranch is computed again (the similar block around lines 552-555) so both
fetchRequiredStatusChecks calls use the actual analyzed base branch.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 985698f8-272a-42e6-aaf4-d00a39a458d0

📥 Commits

Reviewing files that changed from the base of the PR and between 18c7265 and 6ecab57.

📒 Files selected for processing (4)
  • .github/workflows/pr-review-advisor.yaml
  • test/pr-review-advisor.test.ts
  • tools/pr-review-advisor/README.md
  • tools/pr-review-advisor/analyze.mts

Comment thread tools/pr-review-advisor/analyze.mts Outdated
Signed-off-by: Carlos Villela <cvillela@nvidia.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
tools/pr-review-advisor/analyze.mts (1)

407-416: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use the analyzed base ref for required-context discovery.

This helper still derives baseBranch from env / "main" only, so non-default-base runs can wait on and gate against the wrong ruleset contexts.

💡 Minimal fix
-  await waitForRequiredChecksBeforeAnalysis(headSha);
+  await waitForRequiredChecksBeforeAnalysis(headSha, baseRef);

-async function waitForRequiredChecksBeforeAnalysis(headSha: string): Promise<void> {
+async function waitForRequiredChecksBeforeAnalysis(headSha: string, baseRef: string): Promise<void> {
   ...
-    ...(await discoverRequiredStatusCheckContexts()),
+    ...(await discoverRequiredStatusCheckContexts(baseRef)),
   ...
 }

-export async function discoverRequiredStatusCheckContexts(): Promise<string[]> {
+export async function discoverRequiredStatusCheckContexts(baseRef?: string): Promise<string[]> {
   ...
-  const baseBranch = process.env.PR_REVIEW_ADVISOR_REQUIRED_CHECK_BASE || process.env.GITHUB_BASE_REF || "main";
+  const baseBranch = normalizeBaseBranch(
+    process.env.PR_REVIEW_ADVISOR_REQUIRED_CHECK_BASE ||
+      process.env.GITHUB_BASE_REF ||
+      baseRef ||
+      "main",
+  );
function normalizeBaseBranch(ref: string): string {
  return ref.replace(/^refs\/heads\//, "").replace(/^origin\//, "");
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/pr-review-advisor/analyze.mts` around lines 407 - 416,
discoverRequiredStatusCheckContexts currently builds baseBranch only from env
vars and "main", which ignores the analyzed PR base ref; update it to normalize
and use the actual analyzed base ref before calling fetchRequiredStatusChecks.
Add or reuse a normalizeBaseBranch helper (e.g., normalizeBaseBranch(ref:
string) that strips "refs/heads/" and "origin/") and compute baseBranch from
process.env.PR_REVIEW_ADVISOR_REQUIRED_CHECK_BASE || process.env.GITHUB_BASE_REF
|| analyzedBaseRef || "main" (where analyzedBaseRef is the ref determined
earlier by the analyzer), then pass that normalized baseBranch into
fetchRequiredStatusChecks so required-context discovery uses the correct branch;
reference discoverRequiredStatusCheckContexts, normalizeBaseBranch, and
fetchRequiredStatusChecks when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@tools/pr-review-advisor/analyze.mts`:
- Around line 407-416: discoverRequiredStatusCheckContexts currently builds
baseBranch only from env vars and "main", which ignores the analyzed PR base
ref; update it to normalize and use the actual analyzed base ref before calling
fetchRequiredStatusChecks. Add or reuse a normalizeBaseBranch helper (e.g.,
normalizeBaseBranch(ref: string) that strips "refs/heads/" and "origin/") and
compute baseBranch from process.env.PR_REVIEW_ADVISOR_REQUIRED_CHECK_BASE ||
process.env.GITHUB_BASE_REF || analyzedBaseRef || "main" (where analyzedBaseRef
is the ref determined earlier by the analyzer), then pass that normalized
baseBranch into fetchRequiredStatusChecks so required-context discovery uses the
correct branch; reference discoverRequiredStatusCheckContexts,
normalizeBaseBranch, and fetchRequiredStatusChecks when making the change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 923ec4e6-d1aa-4ac8-849f-9fec6d1ecef9

📥 Commits

Reviewing files that changed from the base of the PR and between 6ecab57 and f53bbaa.

📒 Files selected for processing (2)
  • test/pr-review-advisor.test.ts
  • tools/pr-review-advisor/analyze.mts

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tools/pr-review-advisor/analyze.mts (2)

336-385: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Abort this run if the PR head advances while you are waiting.

When headRefOid changes, the loop only logs the mismatch and then keeps going. That means this job can wait on checks for the newer commit and still analyze the older checkout, which can post a stale review against code that is no longer the PR head.

Suggested fix
       lastState = await fetchRequiredCheckWaitState({ repo, token, prNumber, requiredContexts });
-      const shaNote = lastState.headRefOid && lastState.headRefOid !== headSha
-        ? ` latest PR head is ${lastState.headRefOid.slice(0, 12)}, workflow head is ${headSha.slice(0, 12)}.`
-        : "";
+      if (lastState.headRefOid && lastState.headRefOid !== headSha) {
+        throw new Error(
+          `PR head advanced from ${headSha.slice(0, 12)} to ${lastState.headRefOid.slice(0, 12)}; rerun advisor on the latest commit.`,
+        );
+      }
       if (lastState.pendingContexts.length === 0) {
-        logProgress(`Required-check wait complete.${shaNote}`);
+        logProgress("Required-check wait complete.");
         return;
       }
-      logProgress(`Required-check wait pending: ${lastState.pendingContexts.join(", ")}.${shaNote}`);
+      logProgress(`Required-check wait pending: ${lastState.pendingContexts.join(", ")}.`);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/pr-review-advisor/analyze.mts` around lines 336 - 385, The loop in
waitForRequiredChecksBeforeAnalysis currently only logs when
lastState.headRefOid differs from headSha, allowing analysis to continue against
a stale checkout; change this so the run aborts when the PR head advances by
detecting lastState.headRefOid !== headSha and then immediately stop further
work (e.g., log a clear message and throw an Error or call process.exit with a
non-zero code) instead of continuing; update the branch around where shaNote is
computed (referencing waitForRequiredChecksBeforeAnalysis, lastState.headRefOid,
and headSha) to perform this abort early in the loop so stale analysis cannot be
posted.

552-563: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Keep empty required-check rollups in pending, not unknown.

Now that required contexts are passed into deriveGateStatus, the zero-node path still collapses to unknown. For fresh PRs or wait timeouts, that drops the new “pending or missing” evidence instead of reporting the required contexts as pending.

Suggested fix
 function deriveCiGateStatus(statuses: CheckStatusSummary[], requiredContexts: string[]): GateStatus {
-  if (statuses.length === 0) return { status: "unknown", evidence: "No statusCheckRollup data was available." };
+  if (statuses.length === 0) {
+    return requiredContexts.length > 0
+      ? {
+          status: "pending",
+          evidence: `Required status context(s) pending or missing: ${requiredContexts.join(", ")}. Non-required contexts still pending: 0; failed: 0.`,
+        }
+      : { status: "unknown", evidence: "No statusCheckRollup data was available." };
+  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/pr-review-advisor/analyze.mts` around lines 552 - 563, The gate
computation currently treats an empty requiredStatusCheckContexts rollup as
`unknown`; change the logic so an empty rollup is treated as `pending` (so fresh
PRs / timeouts report "pending or missing" evidence). Update deriveGateStatus to
detect an empty requiredStatusCheckContexts (or adjust the caller in
collectDeterministicContext) and return a gate status that marks required checks
as pending (include a pending evidence entry for requiredStatusCheckContexts)
rather than returning `unknown`; reference the deriveGateStatus function and the
requiredStatusCheckContexts value passed from collectDeterministicContext to
locate where to implement this behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@tools/pr-review-advisor/analyze.mts`:
- Around line 336-385: The loop in waitForRequiredChecksBeforeAnalysis currently
only logs when lastState.headRefOid differs from headSha, allowing analysis to
continue against a stale checkout; change this so the run aborts when the PR
head advances by detecting lastState.headRefOid !== headSha and then immediately
stop further work (e.g., log a clear message and throw an Error or call
process.exit with a non-zero code) instead of continuing; update the branch
around where shaNote is computed (referencing
waitForRequiredChecksBeforeAnalysis, lastState.headRefOid, and headSha) to
perform this abort early in the loop so stale analysis cannot be posted.
- Around line 552-563: The gate computation currently treats an empty
requiredStatusCheckContexts rollup as `unknown`; change the logic so an empty
rollup is treated as `pending` (so fresh PRs / timeouts report "pending or
missing" evidence). Update deriveGateStatus to detect an empty
requiredStatusCheckContexts (or adjust the caller in
collectDeterministicContext) and return a gate status that marks required checks
as pending (include a pending evidence entry for requiredStatusCheckContexts)
rather than returning `unknown`; reference the deriveGateStatus function and the
requiredStatusCheckContexts value passed from collectDeterministicContext to
locate where to implement this behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: b938b6a6-f4d0-42fa-b169-af96b4a169e6

📥 Commits

Reviewing files that changed from the base of the PR and between f53bbaa and 8c715a5.

📒 Files selected for processing (2)
  • test/pr-review-advisor.test.ts
  • tools/pr-review-advisor/analyze.mts

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@wscurran wscurran added CI/CD Use this label to identify issues with NemoClaw CI/CD pipeline or GitHub Actions. E2E End-to-end testing — Brev infrastructure, test cases, nightly failures, and coverage gaps fix labels May 21, 2026
@cv cv merged commit cdccf53 into main May 21, 2026
29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI/CD Use this label to identify issues with NemoClaw CI/CD pipeline or GitHub Actions. E2E End-to-end testing — Brev infrastructure, test cases, nightly failures, and coverage gaps fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants