Skip to content

Review selection engine - #30

Merged
mohanagy merged 5 commits into
mainfrom
review-selection-engine
May 1, 2026
Merged

mohanagy merged 5 commits into
mainfrom
review-selection-engine

Conversation

@mohanagy

@mohanagy mohanagy commented May 1, 2026 •

Copy link
Copy Markdown
Owner

Summary

Testing

  • npm run test:run
  • npm run typecheck
  • npm run build
  • npm pack --dry-run (if packaging or install behavior changed)

Checklist

  • I updated docs for any user-visible change
  • I added or updated tests when behavior changed
  • I did not commit secrets, private corpora, or accidental generated artifacts
  • I kept this PR focused on a single change or tightly related set of changes

Related issues

Summary by CodeRabbit

  • New Features
    • Added review-compare CLI workflow to generate verbose vs compact PR-impact prompts, run them, save artifacts, and report token/run summaries
    • PR-impact now returns line-aware changed ranges, typed seed_nodes, a budgeted compact review bundle, ranked/top risks, and supports budget/verbose/compact flags
  • Bug Fixes
    • Improved PR-diff discovery in nested repos, output-dir validation, range normalization, and line-metadata fallbacks
    • Reduced compact payload sizes by trimming oversized arrays
  • Documentation
    • Docs and examples updated for review-compare and expanded pr_impact outputs
  • Tests
    • New unit tests for CLI, review-compare, pr-impact, risk-ranking, and source-location behaviors

mohanagy and others added 3 commits May 1, 2026 18:18
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented May 1, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds a new review-compare CLI/workflow that generates verbose and compact pr_impact prompts/artifacts and can run them via a runner; extends pr_impact with line-aware changed ranges, seed selection, token-budgeted review bundles and compaction; refactors risk scoring utilities, exports helpers, updates docs/tests, and bumps version to 0.10.4.

Changes

Cohort / File(s) Summary
Version & Changelog
CHANGELOG.md, package.json
Bumped version to 0.10.4, added changelog entries for 0.10.3/0.10.4 describing review-compare and pr_impact behavior changes.
CLI & Parser
src/cli/main.ts, src/cli/parser.ts, tests/unit/cli.test.ts
Adds review-compare command, ReviewCompareCommandContext, new CLI args parsing (--exec, --output-dir, --base-branch, --budget, --yes), output-dir normalization, and tests for parsing/flow.
Review-Compare Implementation
src/infrastructure/review-compare.ts, tests/unit/review-compare.test.ts
New module to generate verbose/compact pr_impact prompts, persist prompt/answer/report artifacts, run configurable runner templates (placeholder expansion), capture outputs/timings, and return a formatted summary; includes unit tests.
PR Impact Analysis
src/runtime/pr-impact.ts, tests/unit/pr-impact.test.ts
Switches to unified-diff changed_ranges, introduces seed_nodes (line/file match), builds token-budgeted review_bundle via neighborhood expansion, enriches review_context and risk_summary, and adds compactPrImpactResult; large test suite added.
Risk Scoring Utilities
src/runtime/risk-map.ts, tests/unit/risk-map.test.ts
Extracts scoring/ranking into scoreRisk, buildRankedRisk, compareRankedRisks, exposes RiskSeverity and related helpers; tests added for ordering.
Retrieve & Stdio Tools
src/runtime/retrieve.ts, src/runtime/stdio/definitions.ts, src/runtime/stdio/tools.ts, tests/unit/stdio-pr-impact.test.ts
Exports helper functions (estimateRetrieveEntryTokens, readSnippet, collectRelationships), adds budget, verbose, compact params to pr_impact schema, validates inputs, and conditionally returns compact or verbose payloads; tests cover behavior and schema.
Shared Helpers
src/shared/git.ts, src/shared/security.ts, src/shared/source-location.ts, tests/unit/source-location.test.ts
Adds findGitRoot, exports findNearestExistingAncestor, introduces SourceLineRange and lineRangeFromSourceLocation, refactors lineNumberFromSourceLocation, and tests range normalization.
Infrastructure Hooks
src/infrastructure/hooks.ts
Replaces local git-root traversal with shared findGitRoot in install, uninstall, and status, removing local helper.
Docs & Examples
README.md, docs/proof-workflows.md, examples/*
Documents review-compare workflow, updates pr_impact examples and README to reflect compact/verbose behavior, artifact locations, and proof mapping.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as CLI Handler
    participant Parser as Arg Parser
    participant ReviewCompare as ReviewCompare Module
    participant Graph as Knowledge Graph Loader
    participant PrImpact as PR Impact Analyzer
    participant Runner as External Runner
    participant Disk as File System

    CLI->>Parser: parseReviewCompareArgs(args)
    Parser-->>CLI: ReviewCompareCliOptions

    CLI->>ReviewCompare: runReviewCompareCommand(input)
    ReviewCompare->>Graph: load graph.json
    Graph-->>ReviewCompare: KnowledgeGraph

    ReviewCompare->>PrImpact: analyzePrImpact(mode=verbose)
    PrImpact-->>ReviewCompare: verbose result
    ReviewCompare->>Disk: write verbose prompt file

    ReviewCompare->>PrImpact: compactPrImpactResult(verbose)
    PrImpact-->>ReviewCompare: compact result
    ReviewCompare->>Disk: write compact prompt file

    ReviewCompare->>Disk: write initial report.json
    ReviewCompare->>Runner: exec verbose prompt (template)
    Runner-->>ReviewCompare: stdout/stderr, exit code
    ReviewCompare->>Disk: write verbose answer + update report

    ReviewCompare->>Runner: exec compact prompt (template)
    Runner-->>ReviewCompare: stdout/stderr, exit code
    ReviewCompare->>Disk: write compact answer + update report

    ReviewCompare-->>CLI: return formatted summary (tokens, reduction, path)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰
I hopped through diffs with prompts in paw,
Two paths of review that I proudly saw.
Verbose to ponder, compact to skim,
Tokens trimmed neatly — my whiskers grin. 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is entirely empty except for template placeholders. No summary of changes, testing details, or implementation context is provided, making it impossible to understand the purpose or scope of the work. Fill in the Summary section with concrete details about the review selection engine, seed node logic, and review-compare workflow. Complete the Testing section with actual commands run and results. Check relevant checklist items and reference related issues if applicable.
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 (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Review selection engine' is directly related to the PR's core changes—it introduces diff-first PR review selection (seed nodes, changed ranges, line-aware matching) and the review-compare workflow for comparing verbose vs compact PR impact payloads.
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 review-selection-engine

Review rate limit: 9/10 reviews remaining, refill in 6 minutes.

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

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/infrastructure/review-compare.ts (1)

166-193: ⚡ Quick win

Consider adding a timeout to prevent indefinite hangs.

The defaultRunner spawns external commands without a timeout. If the executed command hangs, this will block indefinitely. Consider adding a timeout mechanism similar to how gitDiffPatch in pr-impact.ts uses timeout: 10_000.

Proposed approach using AbortController
 async function defaultRunner(execution: ReviewCompareExecution): Promise<ReviewCompareRunnerResult> {
   const startedAt = Date.now()
+  const timeoutMs = 300_000 // 5 minutes
+  const controller = new AbortController()
+  const timeout = setTimeout(() => controller.abort(), timeoutMs)
+
   return await new Promise<ReviewCompareRunnerResult>((resolveExecution, rejectExecution) => {
     const command =
       process.platform === 'win32'
         ? { file: 'powershell.exe', args: ['-NoProfile', '-Command', execution.command] }
         : { file: '/bin/sh', args: ['-lc', execution.command] }
-    const child = spawn(command.file, command.args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] })
+    const child = spawn(command.file, command.args, { 
+      shell: false, 
+      stdio: ['ignore', 'pipe', 'pipe'],
+      signal: controller.signal,
+    })
     // ... rest of implementation
     child.on('close', (code) => {
+      clearTimeout(timeout)
       resolveExecution({
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/infrastructure/review-compare.ts` around lines 166 - 193, The
defaultRunner currently spawns commands (spawn call in defaultRunner) with no
timeout; add a timeout mechanism (e.g., accept a timeout in
ReviewCompareExecution or use a hard default) and use an AbortController or a
setTimeout to kill the child process when exceeded: start a timer when the child
is spawned, on timeout call child.kill() (or send SIGKILL), clear the timer on
normal close, and ensure you rejectExecution (or resolveExecution with a
specific exitCode like 124) and include elapsedMs, stdout, and stderr; also
remove/cleanup listeners to avoid leaks and handle the child.on('error') path
consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/cli/parser.ts`:
- Around line 854-862: The --budget '=' and separate-arg branches accept any
positive integer and don't enforce the shared maximum; after parsing with
parsePositiveDecimalInteger in both the argument === '--budget' and
argument.startsWith('--budget=') paths, clamp the resulting budget to
MAX_TOKEN_BUDGET (or validate and throw if above) before assigning to the budget
variable so the parsed value cannot exceed the shared MAX_TOKEN_BUDGET; update
the code around parsePositiveDecimalInteger, the budget assignment, and
reference MAX_TOKEN_BUDGET, budget, and the '--budget' handling logic to ensure
both branches behave identically.

In `@src/runtime/risk-map.ts`:
- Around line 122-127: The compareRankedRisks comparator currently orders by
hotspot_count and dependent_count before score, which lets lower-score items
outrank higher-impact ones; update compareRankedRisks so it compares right.score
- left.score first, then hotspot_count (right.hotspot_count -
left.hotspot_count), then dependent_count (right.dependent_count -
left.dependent_count), and finally fall back to label localeCompare for ties so
the "Highest risk" list is driven primarily by total risk score.

In `@src/runtime/stdio/tools.ts`:
- Around line 206-207: The current logic flips the default to compact when
callers send no flags; change it so the legacy full `pr_impact` payload is
returned unless the caller explicitly requests compact mode. Update the
determination of useVerbosePrImpact (used with id, prResult,
compactPrImpactResult, helpers.ok, helpers.textToolResult) to default to true
and only set to false when toolArguments.compact === true (optionally still
allow toolArguments.verbose === true to force verbose), so existing clients keep
fields like changed_nodes and affected_files unless they opt into compact.

---

Nitpick comments:
In `@src/infrastructure/review-compare.ts`:
- Around line 166-193: The defaultRunner currently spawns commands (spawn call
in defaultRunner) with no timeout; add a timeout mechanism (e.g., accept a
timeout in ReviewCompareExecution or use a hard default) and use an
AbortController or a setTimeout to kill the child process when exceeded: start a
timer when the child is spawned, on timeout call child.kill() (or send SIGKILL),
clear the timer on normal close, and ensure you rejectExecution (or
resolveExecution with a specific exitCode like 124) and include elapsedMs,
stdout, and stderr; also remove/cleanup listeners to avoid leaks and handle the
child.on('error') path consistently.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e641d346-64ca-4eff-af75-7627b3df632b

📥 Commits

Reviewing files that changed from the base of the PR and between 0d49f05 and 7cb90d7.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (19)
  • CHANGELOG.md
  • package.json
  • src/cli/main.ts
  • src/cli/parser.ts
  • src/infrastructure/hooks.ts
  • src/infrastructure/review-compare.ts
  • src/runtime/pr-impact.ts
  • src/runtime/retrieve.ts
  • src/runtime/risk-map.ts
  • src/runtime/stdio/definitions.ts
  • src/runtime/stdio/tools.ts
  • src/shared/git.ts
  • src/shared/security.ts
  • src/shared/source-location.ts
  • tests/unit/cli.test.ts
  • tests/unit/pr-impact.test.ts
  • tests/unit/review-compare.test.ts
  • tests/unit/source-location.test.ts
  • tests/unit/stdio-pr-impact.test.ts

Comment thread src/cli/parser.ts Resolved
Comment thread src/runtime/risk-map.ts Resolved
Comment thread src/runtime/stdio/tools.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 the current code and only fix it if needed.

Inline comments:
In `@README.md`:
- Line 140: Replace the phrase "multi-project real repos" with a clearer wording
in the README line that mentions external graph paths and output directories;
update the sentence to use either "real multi-project repositories" or
"real-world multi-project repos" (choose one) so the line reading about
"Supports external graph paths and output directories inside the target graph
workspace's own `graphify-out/`" is more readable and user-facing.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: fe2b4875-9bbe-4478-94b9-11b40d666a56

📥 Commits

Reviewing files that changed from the base of the PR and between 7cb90d7 and 4b8a84b.

📒 Files selected for processing (4)
  • README.md
  • docs/proof-workflows.md
  • examples/mcp-tool-examples.md
  • examples/why-graphify.md

Comment thread README.md Resolved
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 the current code and only fix it if needed.

Inline comments:
In `@src/cli/parser.ts`:
- Around line 256-258: The function validateReviewCompareOutputDir currently
bypasses validateGraphOutputPath for absolute paths; change its logic so both
absolute and relative outputDir values are passed through
validateGraphOutputPath (i.e., always call validateGraphOutputPath for
confinement) while still resolving absolute paths where needed; update the
validateReviewCompareOutputDir implementation and any other similar helper(s)
(see the other occurrence referenced) to ensure the --output-dir for
review-compare is confined to the same graphify-out/ validation as other flows.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 018cd989-0971-4c15-a7f0-719f042c8b56

📥 Commits

Reviewing files that changed from the base of the PR and between 4b8a84b and a5ea8f6.

📒 Files selected for processing (5)
  • README.md
  • src/cli/parser.ts
  • src/runtime/risk-map.ts
  • tests/unit/cli.test.ts
  • tests/unit/risk-map.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/unit/cli.test.ts

Comment thread src/cli/parser.ts Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant