Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:46:23 +08:00
commit 9e5d835a1f
8 changed files with 761 additions and 0 deletions

194
commands/address-reviews.md Normal file
View File

@@ -0,0 +1,194 @@
---
description: Fetch and address all PR review comments
argument-hint: [PR number (optional - uses current branch if omitted)]
---
## Name
utils:address-reviews
## Synopsis
/utils:address-reviews [PR number (optional - uses current branch if omitted)]
## Description
This command automates the process of addressing PR review comments by fetching all comments from a pull request, categorizing them by priority (blocking, change requests, questions, suggestions), and systematically addressing each one. It intelligently filters out outdated comments, bot-generated content, and oversized responses to optimize context usage. The command handles code changes, posts replies to reviewers, and maintains a clean git history by amending relevant commits rather than creating unnecessary new ones.
## Implementation
### Step 0: Checkout the PR Branch
1. **Determine PR number**: Use $ARGUMENTS if provided, otherwise `gh pr list --head <current-branch>`
2. **Checkout**: Use `gh pr checkout <PR_NUMBER>` if not already on the branch, then `git pull`
3. **Verify clean working tree**: Run `git status`. If uncommitted changes exist, ask user how to proceed
### Step 1: Fetch PR Context
1. **Fetch PR metadata with selective filtering**:
a. **First pass - Get metadata only** (IDs, authors, lengths, URLs):
```bash
# Get issue comments (general PR comments - main conversation)
gh pr view <PR_NUMBER> --json comments --jq '.comments | map({
id,
author: .author.login,
length: (.body | length),
url,
createdAt,
type: "issue_comment"
})'
# Get reviews (need REST API for numeric IDs)
gh api repos/{owner}/{repo}/pulls/<PR_NUMBER>/reviews --jq 'map({
id,
author: .user.login,
length: (.body | length),
state,
submitted_at,
type: "review"
})'
# Get review comments (inline code comments)
gh api repos/{owner}/{repo}/pulls/<PR_NUMBER>/comments --jq 'map({
id,
author: .user.login,
length: (.body | length),
path,
line,
created_at,
type: "review_comment"
})'
```
b. **Apply filtering logic** (DO NOT fetch full body yet):
- Filter out: `line == null` (outdated review comments)
- Filter out: `length > 5000`
- Filter out: CI/automation bots `author in ["openshift-ci-robot", "openshift-ci"]` (keep coderabbitai for code review insights)
- Keep track of filtered items and stats for reporting
c. **Second pass - Fetch ONLY essential fields for kept items**:
```bash
# For issue comments - fetch only body and minimal metadata:
gh api repos/{owner}/{repo}/issues/comments/<comment_id> --jq '{id, body, user: .user.login, created_at, url}'
# For reviews - fetch only body and state:
gh api repos/{owner}/{repo}/pulls/<PR_NUMBER>/reviews/<review_id> --jq '{id, body, user: .user.login, state, submitted_at}'
# For review comments - fetch only body and code context:
gh api repos/{owner}/{repo}/pulls/comments/<comment_id> --jq '{id, body, user: .user.login, path, position, diff_hunk, created_at}'
```
**Note**: Using `--jq` to select only needed fields minimizes context usage. Avoid fetching full API responses with all metadata.
d. **Log filtering results**:
```
Fetched N/M comments (filtered out K large/bot comments saving ~X chars)
```
2. **Fetch commit messages**: `gh pr view <PR_NUMBER> --json commits -q '.commits[] | "\(.messageHeadline)\n\n\(.messageBody)"'`
3. Store ONLY the kept (filtered) comments for analysis
### Step 2: Categorize and Prioritize Comments
**Note**: Most filtering already happened in Step 1 to save context window space.
1. **Additional filtering** (for remaining fetched comments):
- Already resolved comments
- Pure acknowledgments ("LGTM", "Thanks!", etc.)
2. **Categorize**:
- **BLOCKING**: Critical changes (security, bugs, breaking issues)
- **CHANGE_REQUEST**: Code improvements or refactoring
- **QUESTION**: Requests for clarification
- **SUGGESTION**: Optional improvements (nits, non-critical)
3. **Group by context**: Group by file, then by proximity (within 10 lines)
4. **Prioritize**: BLOCKING → CHANGE_REQUEST → QUESTION → SUGGESTION
5. **Present summary**: Show counts by category and file groupings, ask user to confirm
### Step 3: Address Comments
#### Grouped Comments
When multiple comments relate to the same concern/fix:
- Make the code change once
- Reply to EACH comment individually (don't copy-paste, tailor each reply)
- Optional reference: `Done. (Also addresses feedback from @user)`
#### Code Change Requests
**a. Validate**: Thoroughly analyze if the change is valid and fixes an issue or improves code. Don't be afraid to reject the change if it doesn't make sense.
**b. If requested change is valid**:
- Plan and implement changes
- Commit and Push
1. **Review changes**: `git diff`
2. **Analyze commit structure**: `git log --oneline origin/main..HEAD`
- Identify which commit the changes relate to
3. **Commit strategy**:
**DEFAULT: Amend the relevant commit**
- ✅ **AMEND**: Review fixes, bug fixes, style improvements, refactoring, docs, tests within PR scope
- ❌ **NEW COMMIT**: Only for substantial new features beyond PR's original scope
- **When unsure**: Amend (keep git history clean)
- **Multiple commits**: Use `git rebase -i origin/main` to amend the specific relevant commit
4. **Create and push commit**:
- Follow [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) format
- Always include body explaining "why"
- **Amend**: `git commit --amend --no-edit && git push --force-with-lease` (or update message if scope changed)
- **New commit**: Standard commit with message
- **Concise Reply template**: `Done. [1-line what changed]. [Optional 1-line why]`
- Max 2 sentences + attribution footer
- Post reply:
```
gh api repos/{owner}/{repo}/pulls/<PR_NUMBER>/comments/<comment_id>/replies -f body="<reply>"
```
If fails: `gh pr comment <PR_NUMBER> --body="@<author> <reply>"`
**c. If declining change**:
- **Reply with technical explanation** (3-5 sentences):
- Why current implementation is correct
- Specific reasoning with file:line references
- Use same posting method as (b)
**d. If unsure**: Ask user for clarification
#### Clarification Requests
- Provide clear, detailed answer (2-4 sentences)
- Include file:line references when applicable
- Post using same method as code changes
#### Informational Comments
- No action unless response is courteous
**All replies must include**: `---\n*AI-assisted response via Claude Code*`
### Step 4: Summary
Show user:
- Total comments found (raw count from API)
- Comments filtered out (with reason: outdated/large/bot-generated)
- Comments addressed with code changes
- Comments replied to
- Comments requiring user input
## Guidelines
- Be thorough but efficient
- Maintain professional tone in all replies
- Prioritize code quality over quick fixes
- Ensure code builds and passes tests after changes
- When in doubt, ask the user
- Use TodoWrite to track progress through multiple comments
## Arguments:
- $1: [PR number to address reviews (optional - uses current branch if omitted)]

View File

@@ -0,0 +1,143 @@
---
description: Automate approving Konflux bot PRs for the given repository by adding /lgtm and /approve
argument-hint: <target-repository>
---
## Name
utils:auto-approve-konflux-prs
## Synopsis
/utils:auto-approve-konflux-prs <target-repository>
## Description
The command automates the approval of open PRs created by the `red-hat-konflux[bot]` for the given repository.
It filters all open PRs from the given repository, checks whether the PR already has `/lgtm` and `/approve` comments, verifies that all required checks (CI jobs or other mandatory checks) have passed, and if any labels/comments are missing and all checks succeed, posts `/lgtm` and `/approve` comments to trigger approval.
This ensures that PRs are only auto-approved if all required checks succeed and the author is `red-hat-konflux[bot]`, reducing the risk of approving failing or unauthorized changes.
## Arguments
- **$1 target-repositories** *(required)*: GitHub repository in `OWNER/REPO` format.
- Example: openshift/multiarch-tuning-operator.
## Implementation
The command executes the following workflow:
### 1. Restrict Author
The command only processes PRs authored by `red-hat-konflux[bot]`. If a PR from any other author is encountered, it reports an error such as below:
```
⚠️ Only PRs from red-hat-konflux[bot] can be automatically processed
```
and exits.
### 2. Get Open PRs
Fetch all open PRs authored by `red-hat-konflux[bot]` for the specified repository:
```bash
gh pr list --repo <target-repository> --author app/red-hat-konflux --state open --json number,title,baseRefName,labels
```
- Extract: number,title,baseRefName,labels
### 3. Check CI Status and Labels
#### **For Each PR:**:
1. Fetch detailed PR information:
```bash
gh pr view <PR_NUMBER> --repo <target-repository> --json statusCheckRollup,labels
```
- Extract: statusCheckRollup,labels
- Handle errors: If PR is inaccessible, log warning and skip
2. Verify all required checks:
- Verify all required checks have "conclusion": "SUCCESS"
- If any check has failed or is pending(except one pending tide job), skip adding /lgtm or /approve and log:
```
⚠️ Skipping PR #<PR_NUMBER>: CI checks not all passed
```
3. Inspect labels:
- Check for lgtm label
- Check for approved label
4. Add missing labels via comments:
- If /lgtm is missing, post a comment /lgtm
- If /approve is missing, post a comment /approve
- If both are missing, post a single comment containing both commands.
5. Log each action:
```
✅ Added /lgtm and/or /approve to PR #<PR_NUMBER>: <PR_TITLE> (merge into <MERGE_BRANCH>)
```
## Return Value
- **Claude agent text**: Summary of processed PRs and actions taken.
- **Side effects**:
- Comments posted to PRs to trigger /lgtm and /approve.
- Progress updates for multiple PRs.
## Examples
1. **Process all open PRs from `red-hat-konflux[bot]` in a repository**:
```
/utils:auto-approve-konflux-prs openshift/multiarch-tuning-operator
```
Output:
```
Processing 3 open Konflux PRs...
[1/3] PR #84 - chore(deps): update konflux references (merge into main)
✅ Added /lgtm and /approve (all CI passed)
[2/3] PR #83 - chore(deps): update konflux references (merge into v1.x)
⚠️ Skipping: CI checks not all passed
[3/3] PR #82 - chore(deps): update konflux references (merge into fbc)
✅ Added /lgtm (already had /approve, all CI passed)
Summary:
✅ Processed 2 PRs successfully, 1 skipped due to CI failures
```
## Prerequisites
### Required Tools
1. **GitHub CLI (`gh`)**: Must be installed and authenticated
- Install: `brew install gh` (macOS) or see [GitHub CLI docs](https://cli.github.com/)
- Authenticate: `gh auth login`
- Verify: `gh auth status`
2. **Access to GitHub Repositories**: Must have read access to repos where PRs are located
- PRs in private repos require appropriate GitHub permissions
- Public repos should work without additional configuration
### Required Permissions
1. **GitHub Permissions**:
- Read access to pull requests
- Write access to create comments on pull requests
## Error Handling
- **Repository inaccessible**: Reports error and exits.
- **PRs authored by someone other than `red-hat-konflux[bot]`**: Reports error and exits.
- **No open PRs from Konflux bot**: Logs "No PRs to process".
- **GitHub authentication failure**: Suggests re-login with `gh auth login`.
- **Comment posting failure**: Logs PR number and error for manual review.
## Notes
- The command only processes open PRs authored by `app/red-hat-konflux`.
- Compatible with repositories in which the user has write permission to post PR comments.
- Designed to minimize manual PR review effort and maintain consistent approvals.

View File

@@ -0,0 +1,114 @@
---
description: Generate test steps for one or more related PRs
argument-hint: [GitHub PR URLs]
---
## Name
utils:generate-test-plan
## Synopsis
/utils:generate-test-plan [GitHub PR URLs]
## Description
The 'utils:generate-test-plan' command takes one or more GitHub PR URLs, fetches the PR details including description, commits, and file changes, analyzes the changes to understand what features/fixes were implemented, and generates a comprehensive testing guide with step-by-step instructions. When multiple PRs are provided, it analyzes them collectively to understand how they work together to fix a bug or implement a feature.
**PR Testing Guide Generator**
## Implementation
- The command uses `gh pr view` to fetch PR data for one or more PRs
- Analyzes PR descriptions, commits, and changed files across all provided PRs
- Identifies relationships and dependencies between multiple PRs
- Generates test scenarios based on the collective changes
- Creates a comprehensive testing guide with prerequisites and verification steps
## Process Flow:
1. **PR Analysis**: Parse GitHub URLs and fetch PR details:
- Extract PR numbers from all provided URLs (supports multiple PRs)
- For each PR, use `gh pr view {PR_NUMBER} --json title,body,commits,files,labels` to fetch:
- PR title and description
- Commit messages and history
- Changed files and their diffs
- PR labels (bug, enhancement, etc.)
- Read the changed files to understand the implementation
- When multiple PRs are provided:
- Identify common JIRA issues or bug references across PRs
- Analyze how changes in different PRs complement each other
- Determine the order in which PRs should be tested (if dependencies exist)
2. **Change Analysis**: Understand what was changed:
- For single PR:
- Identify the type of change (feature, bug fix, refactor, etc.)
- Determine affected components (API, CLI, operator, control-plane, etc.)
- Find related platform-specific changes (AWS, Azure, KubeVirt, etc.)
- For multiple PRs:
- Identify the overall objective (complete bug fix, multi-component feature, etc.)
- Map which PR addresses which component or aspect of the fix
- Identify overlapping or complementary changes
- Determine if PRs target different repositories or components
- Review test files to understand expected behavior
- Use Grep and Glob tools to:
- Find related configuration or documentation
- Locate example usage in existing tests
- Identify dependencies or related features
3. **Test Scenario Generation**: Create comprehensive test plan:
- Analyze the PR description(s) for:
- Feature requirements and acceptance criteria
- Bug reproduction steps
- Related JIRA issues or issue references
- For multiple PRs, create integrated test scenarios that:
- Test the complete fix/feature with all PRs applied
- Verify each PR's contribution to the overall solution
- Ensure PRs work correctly together without conflicts
- Generate test scenarios covering:
- Happy path scenarios
- Edge cases and error handling
- Platform-specific variations if applicable
- Upgrade/downgrade scenarios if relevant
- Performance impact if significant changes
4. **Test Guide Creation**: Create detailed manual testing document:
- For single PR: Save to `test-pr-{PR_NUMBER}.md`
- For multiple PRs: Save to `test-pr-{PR_NUMBER1}-{PR_NUMBER2}-{PR_NUMBERN}.md` (e.g., `test-pr-6888-6889-6890.md`)
- Include the following sections:
- **PR Summary**:
- For single PR: Title, description, and key changes
- For multiple PRs: List all PRs with their titles, show the common objective, and explain how they work together
- **Prerequisites**:
- Required infrastructure (AWS account, S3 bucket, etc.)
- Tools and CLI versions needed
- Environment setup steps
- **Test Scenarios**:
- Numbered test cases with clear steps
- Expected results for each step
- Verification commands and their expected output
- For multiple PRs: Include integration test scenarios
- **Regression Testing**:
- Suggestions for related features to verify
- **Notes**:
- Known limitations or areas requiring special attention
- Links to related PRs or documentation
- For multiple PRs: Dependencies between PRs and recommended testing order
5. **Output**: Display the testing guide:
- Show the file path where the guide was saved
- Provide a brief summary of the test scenarios
- Highlight any critical test cases or prerequisites
- Ask if the user would like any modifications to the test guide
## Examples:
1. **Generate test steps for a single PR**:
`/utils:generate-test-plan https://github.com/openshift/hypershift/pull/6888`
2. **Generate test steps for multiple related PRs**:
`/utils:generate-test-plan https://github.com/openshift/hypershift/pull/6888 https://github.com/openshift/hypershift/pull/6889 https://github.com/openshift/hypershift/pull/6890`
## Arguments:
- $1, $2, $3, ..., $N: One or more GitHub PR URLs (at least one required)
- Single PR: `/utils:generate-test-plan https://github.com/openshift/hypershift/pull/6888`
- Multiple PRs: `/utils:generate-test-plan https://github.com/openshift/hypershift/pull/6888 https://github.com/openshift/hypershift/pull/6889`
The command will provide a comprehensive manual testing guide that can be used by QE or developers to thoroughly test the PR changes. When multiple PRs are provided, the guide will include integrated test scenarios that verify the PRs work correctly together.

26
commands/placeholder.md Normal file
View File

@@ -0,0 +1,26 @@
---
description: Placeholder command for the utils plugin
---
## Name
utils:placeholder
## Synopsis
```
/utils:placeholder
```
## Description
This is a placeholder command for the utils plugin. The utils plugin serves as a catch-all location for introducing new generic commands. Once enough related commands are accumulated, they can be segregated into more targeted, specialized plugins.
This placeholder exists to maintain the plugin structure and will be replaced with actual utility commands as they are developed.
## Implementation
The utils plugin provides a home for:
- Generic helper commands that don't fit into existing specialized plugins
- Experimental commands that may later be moved to dedicated plugins
- Common utilities that benefit multiple workflows
- Commands that are waiting to be grouped with similar functionality
## Arguments:
None

View File

@@ -0,0 +1,209 @@
---
description: Process Renovate dependency PR(s) to meet repository contribution standards
argument-hint: <PR_NUMBER|open> [JIRA_PROJECT] [COMPONENT]
---
## Name
utils:process-renovate-pr
## Synopsis
```
/utils:process-renovate-pr <PR_NUMBER|open> [JIRA_PROJECT] [COMPONENT]
```
## Description
The `utils:process-renovate-pr` command automates the processing of Renovate/Konflux dependency update pull requests to meet repository contribution standards. It analyzes dependencies, creates comprehensive Jira tickets, and updates PR titles with proper references.
This command significantly reduces manual PR processing time from approximately 15 minutes to 2 minutes by automating:
- Dependency analysis (direct vs indirect)
- OpenShift version detection from release branches
- Jira ticket creation with comprehensive details
- PR title updates with Jira references
- Testing strategy identification
The command can process either a single PR by number or all open dependency PRs from the Konflux bot.
## Implementation
The command executes the following workflow:
### 1. Validation
- Verifies the PR is from `red-hat-konflux[bot]`
- Checks PR title matches pattern: `chore(deps): update * digest to * (main)`
- Filters out "Pipelines as Code configuration" PRs
- If argument is "open", fetches all open dependency PRs
### 2. Target Version Determination
- Fetches latest state: `git fetch origin`
- Gets commit hash for `origin/main`
- Finds all release branches matching main's commit: `origin/release-*`
- Selects the lowest version number (e.g., if both 4.21 and 4.22 match, uses 4.21)
### 3. Dependency Analysis
From the PR diff (go.mod changes):
**Type Classification:**
- Checks for `// indirect` comment in go.mod
- For indirect: uses `go mod why <package>` to identify parent dependency
**Usage Analysis:**
- Direct dependencies: Searches codebase for import statements
- Identifies importing files
- Determines purpose (e.g., "OpenStack image management", "AWS integration")
- Distinguishes runtime code vs tooling (check hack/tools/)
- Indirect dependencies: Documents parent dependency usage
**Version Changes:**
- Extracts old and new pseudo-versions from go.mod
- Fetches upstream commit messages via GitHub API
- Categorizes as patch/minor/major or digest update
**Testing Strategy:**
- hack/tools dependencies: Identifies Makefile targets
- Runtime dependencies: Suggests component testing
### 4. Jira Ticket Management
- Checks existing PR comments for Jira references
- Creates new ticket if none exists with:
- **Summary**: `{Package name} ({Brief purpose})`
- **Type**: Task
- **Components**: From $3 or default "HyperShift"
- **Labels**: ["dependencies", "renovate", "ai-generated"] plus context labels
- **Description**: Comprehensive details including:
- Dependency information (type, versions, location)
- Usage in repository
- Changes in update
- Step-by-step testing instructions
- **Target Version**: Sets customfield_12319940 to openshift-X.Y
### 5. PR Title Update
Posts comment with `/retitle` command and processing summary:
```
/retitle [PROJECT-XXXX](https://issues.redhat.com/browse/PROJECT-XXXX): {Package name} ({Brief description})
```
Includes checklist of completed actions and link to Jira ticket.
## Return Value
- **Claude agent text**: Processing status and summary
- **Side effects**:
- Jira ticket created or referenced
- PR comment posted with /retitle command
- Progress updates for multiple PRs
## Examples
1. **Process a single PR**:
```
/utils:process-renovate-pr 7051
```
Output:
```
✅ Processed PR #7051
- Dependency: github.com/go-logr/logr
- Type: Direct
- Jira: CNTRLPLANE-1234
- Target Version: openshift-4.21
- PR title updated with Jira reference
```
2. **Process with custom Jira project**:
```
/utils:process-renovate-pr 7051 OCPBUGS
```
Creates ticket in OCPBUGS project instead of default CNTRLPLANE.
3. **Process with custom component**:
```
/utils:process-renovate-pr 7051 CNTRLPLANE "Control Plane Operator"
```
Creates ticket with specified component name.
4. **Process all open dependency PRs**:
```
/utils:process-renovate-pr open
```
Output:
```
Processing 3 dependency PRs...
[1/3] Processing PR #7051...
✅ Completed PR #7051
- Dependency: github.com/go-logr/logr
- Jira: CNTRLPLANE-1234
[2/3] Processing PR #7049...
✅ Completed PR #7049
- Dependency: golang.org/x/net
- Jira: CNTRLPLANE-1235
[3/3] Processing PR #7048...
✅ Completed PR #7048
- Dependency: k8s.io/api
- Jira: CNTRLPLANE-1236
Summary:
✅ Processed 3 PRs successfully
- Jira project: CNTRLPLANE
- Component: HyperShift
- Target Version: openshift-4.21
```
5. **Process all open PRs with custom settings**:
```
/utils:process-renovate-pr open OCPBUGS Infrastructure
```
## Arguments
- **$1** (required): PR number (e.g., `7051`) or `open` to process all open dependency PRs from Konflux bot
- When `open`: Automatically fetches and filters dependency PRs, excluding "Pipelines as Code configuration" PRs
- **$2** (optional): Jira project key (default: `CNTRLPLANE`)
- Examples: `CNTRLPLANE`, `OCPBUGS`, `HOSTEDCP`
- **$3** (optional): Jira component name (default: `HyperShift`)
- Use quotes for multi-word components: `"Control Plane Operator"`
## Error Handling
The command handles common error cases:
- **PR not from Konflux bot**: Explains requirement and exits
- **Pipeline configuration PR**: Explains this command only handles dependency updates
- **Jira creation failure**: Provides ticket content for manual creation
- **Version field update failure**: Notes it may need manual setting
- **Invalid PR number**: Validates PR exists before processing
## Notes
- Repository name is automatically detected from `git remote -v` (non-fork remote)
- Direct dependencies include file-level usage analysis
- Indirect dependencies focus on dependency chain documentation
- Testing instructions are tailored to dependency type (tooling vs runtime)
- All Jira tickets are labeled with "ai-generated" for tracking