Perform "context-aware" code review for GitCode PRs.diff is only the entry point, not all the evidence; you must combine the PR title/description, changed files, call chains, adjacent modules, historical implementations, tests, and configuration to judge whether the change is actually correct.
Prerequisites
GitCode Access Token
This skill requires a GitCode access token to obtain PR information and post comments. The token can be configured in one of the following ways:
- Environment variable(recommended):
GITCODE_TOKEN - Git configuration:
git config --global gitcode.token <your-token>
If no token is found, prompt the user to provide one.
Obtain a GitCode token
- Log in to https://gitcode.com
- Click the avatar to enter "Settings"
- Open "Personal Access Tokens"
- Create a new token and grant the following permissions:
pull_requests(read-write)issues(read-write)projects(read-only)
Workflow
1. Parse PR information
When the user provides a GitCode PR link such as https://gitcode.com/Ascend/msprof/pull/109 :
- Extract:
owner=Ascend、repo=msprof、pull_number=109
2. Obtain PR information
Use scripts/fetch_pr_info.py to obtain PR details:
python scripts/fetch_pr_info.py \
--owner <OWNER> --repo <REPO> --pull-number <NUMBER> \
[--token <TOKEN>] [--output-dir <DIR>]
This script will obtain:
- PR metadata, such as title, description, author, and status
- Changed files and their diff contents
- PR comments (optional)
3. Prepare the analysis workspace
Prefer the user's current workspace; if the current directory is already the target repository and the PR's corresponding branch or commit can be obtained, analyze directly in the current repository and do not clone again.
Only clone to a temporary directory when the current workspace is not the target repository, or the PR's corresponding code cannot be obtained:
export GITCODE_TOKEN="your-token"
TEMP_DIR="/tmp/gitcode-review-<REPO>-<TIMESTAMP>"
git clone --depth=50 "https://oauth2:${GITCODE_TOKEN}@gitcode.com/<OWNER>/<REPO>.git" "${TEMP_DIR}"
cd "${TEMP_DIR}"
# 获取 PR 分支
git fetch origin "refs/merge-requests/<NUMBER>/head:pr-<NUMBER>-source"
git checkout "pr-<NUMBER>-source"
4. Build the review context (required)
First read summary.json、pr_metadata.json、pr_files.json、pr_diff.patch, then start looking at the code. You must first answer the following questions:
- What problem is this PR trying to solve
- Infer the goal from the title, description, labels, linked issues, and file distribution: whether it is fixing a bug, adding a feature, refactoring, adding tests, rolling back, or a compatibility fix.
- If the PR description is insufficient, summarize the purpose yourself based on the modified content, and explain the basis for your judgment in the conclusion.
- Which layer of the system the changes fall on
- Identify whether the changed files belong to the entry layer, core logic layer, data model layer, interface/protocol layer, configuration/build layer, test layer, or generated artifacts.
- If they are generated files, lockfiles, or SDK artifacts, continue tracing to the "source files" for review, and do not only comment on the generated results.
- Which implementations in the repository these changes are related to
- Check callers, callees, similar implementations, adapter layers, configuration items, feature flags, schemas, migration scripts, test fixtures, and documentation.
- During review, you must look at the context files of the modified lines, not just the patch hunk.
- What is the baseline behavior
- Confirm the original behavior through the base branch code, commit history, or existing tests, then judge whether this change breaks compatibility or misses branches.
It is recommended to prioritize using these tools to build context:
rg -n "<symbol>|<config>|<endpoint>" .: trace call chains, configuration items, similar implementations, and test coveragegit diff --stat <base_sha>...<head_sha>: quickly identify the scope of high-risk changesgit diff --name-only <base_sha>...<head_sha>: group changed files by modulegit show <base_sha>:<path>: compare against the baseline implementationgit log --follow -- <path>: examine file evolution and historical intentgit blame -L <start>,<end> -- <path>: locate historical context and ownership- Project-provided test/build commands: verify whether the inference holds
If a conclusion relies on inference rather than direct evidence, the conditions must be stated explicitly, for example, "If an empty collection input is allowed here, then the current implementation would...". Do not present guesses as established facts.
5. Review the code in depth
After completing context building, review from the following dimensions, and try to base judgments on the project's actual implementation:
- Goal consistency: whether the implementation truly satisfies the PR goal, and whether it only changes the surface while missing necessary changes in the call chain
- Correctness and regression risk: whether old behavior is unintentionally changed, and whether boundary conditions, exception paths, and state transitions are complete
- Contract compatibility: whether function signatures, interface fields, return values, serialization formats, error codes, and configuration items are compatible with upstream and downstream
- Project consistency: whether it deviates from existing patterns in the repository, increasing future maintenance cost or causing inconsistent behavior
- Performance and resources: whether it introduces unnecessary traversals, repeated I/O, lock contention, cache invalidation, N+1 calls, and other such problems
- Security: risks such as input validation, permission boundaries, sensitive data handling, and command/SQL/path injection
- Testability: whether key branches are supported by tests; if there are no tests, at least point out what kind of test cases should be added
6. Organize the review conclusions
Organize issues by severity:
- Critical: will cause bugs, security issues, or breaking changes
- Suggestion: recommend optimizing code quality, performance, or the implementation approach
- Note: formatting, style, or other optional minor issues
By default, focus on findings that truly affect behavior, reliability, compatibility, and maintainability; do not pile up purely stylistic opinions as the main conclusion.
Each finding must include:
- File path
- Line number
- Severity
- Four-part structure:
- Severity: clearly mark the issue level and keep it consistent with the actual impact
- Issue: specifically point out what problem exists in the current code
- Reason: explain why this is a problem, what risk or impact it will bring, and try to explain which implementation in the repository, which call chain, or which type of existing constraint it is related to
- How to fix: provide actionable modification suggestions, with code examples if necessary
Additional requirements:
- Do not merely restate the surface phenomena of the diff; each important comment should reflect that you have checked the surrounding context
- If the problem comes from 'incomplete changes', explain which files, branches, call sites, or tests are still missing
- If no problems are found, explicitly state which key contexts you checked, rather than just saying 'LGTM'
7. First show the review results to the user
Before formally posting comments, first show the review results to the user:
## 代码审查摘要
**PR**: [标题](URL)
**作者**:@author
**结论**: [通过 / 请求修改]
### 发现的问题
#### 🔴 严重问题(N 个)
1. **文件**:`path/to/file.py`(第 42 行)
- **严重程度**:严重
- **问题**:描述问题
- **原因**:解释原因
- **怎么改**:提供代码示例
#### 🟡 改进建议(N 个)
...
#### 🟢 细节建议(N 个)
...
### 总结
[给出清晰结论及其原因]
In the summary, in addition to listing problems, also add a short 'review coverage' paragraph briefly describing the key contexts you examined, for example 'checked the caller A/B, compared against the baseline implementation C, confirmed the coverage of test D '.
8. Post comments to the PR (optional)
First ask the user: 'Do you want to post these findings as line-by-line comments on the PR?'
If the user confirms, create the comment JSON file and use scripts/post_pr_comment.py to post:
python scripts/post_pr_comment.py \
--owner <OWNER> --repo <REPO> --pull-number <NUMBER> \
--comments-file /tmp/pr_comments.json \
--inline
Comment body example (four-part structure):
**严重程度:** 建议
**问题:** 代码中存在不规范的空格
**原因:** `node = int (node_str)` 不符合 PEP 8 规范,影响可读性
**怎么改:**
```python
# 修改前
node = int (node_str)
# 修改后
node = int(node_str)
```
Prefer using structured fields in comments.json :severity、problem、reason、fix。
scripts/post_pr_comment.py will normalize these fields into a four-part Markdown body before posting, outputting Chinese severity levels by default (严重、建议、提示), and will also be compatible with legacy English values and legacy three-part body content.
9. Clean up the temporary directory
After the review is complete, clean up the temporary repository:
rm -rf /tmp/gitcode-review-<REPO>-<TIMESTAMP>
Review tone requirements
- Remain constructive, professional, and friendly
- Clearly explain why a change is needed
- If giving a passing conclusion, explicitly point out the value of this submission
- Use respectful expression and avoid a commanding tone
- All findings must use thefour-part structure
- One comment should focus on only one problem, and the severity should match the actual risk
- Line-level comments should be as specific and actionable as possible, avoiding conclusions without a direction for changes
- Prioritize pointing out problems that truly affect business or system behavior, and give fewer generic suggestions divorced from project context
Review bottom line
- Do not draw conclusions based only on the diff; the diff is only an entry point for locating issues
- Do not output low-value comments just to make up the numbers
- Do not ignore tests, configuration, call chains, and compatibility impacts
- When uncertain, first supplement with code search and context verification, then decide whether to raise the issue
Script description
fetch_pr_info.py
Used to retrieve PR information from the GitCode API.
python scripts/fetch_pr_info.py \
--owner OWNER \
--repo REPO \
--pull-number NUMBER \
[--token TOKEN] \
[--output-dir DIR] \
[--include-comments]
post_pr_comment.py
Used to post comments to a GitCode PR.
Post line-by-line line-level comments:
python scripts/post_pr_comment.py \
--owner OWNER \
--repo REPO \
--pull-number NUMBER \
--comments-file COMMENTS_JSON \
--inline
Post the overall review conclusion:
python scripts/post_pr_comment.py \
--owner OWNER \
--repo REPO \
--pull-number NUMBER \
--body "审查总结" \
--review-event COMMENT|APPROVE|REQUEST_CHANGES
setup_token.py
Used to configure and verify the GitCode access token.
# 交互式配置
python scripts/setup_token.py
# 仅验证现有令牌
python scripts/setup_token.py --verify-only
Reference materials
- GitCode API documentation: see references/gitcode_api.md
- If you need to view API details, read the corresponding reference files as needed
Technical notes
API versions
GitCode supports both two sets of APIs, v4 (GitLab-compatible) and v5 (GitHub-compatible):
-
v5 API: used to retrieve PR information, file lists, and regular comments
- Base address:
https://api.gitcode.com/api/v5 - Authentication method:
PRIVATE-TOKENrequest header
- Base address:
-
v4 API: used to create line-by-line line-level comments
- Base address:
https://api.gitcode.com/api/v4 - Authentication method:
PRIVATE-TOKENrequest header - Endpoint:
POST /projects/{encoded_project}/merge_requests/{mr_iid}/discussions
- Base address:
Comment JSON format
[
{
"path": "relative/path/to/file.py",
"line": 42,
"severity": "严重",
"problem": "描述问题",
"reason": "解释为什么这是个问题",
"fix": "给出修改建议",
"side": "RIGHT"
}
]
path: file path relative to the repository rootline: Line number in the new fileseverity: Issue level, recommended to use严重、建议、提示; the script is compatible with the legacy valueCritical、Improvement、Nitpickproblem: What exactly is the problem with the current codereason: Why this is a problem, and what impact it will havefix: Suggested fix, optionally with a Markdown code examplebody: Optional legacy input; if provided, the script will normalize it into the four-segment严重程度、问题、原因、怎么改side:"RIGHT"indicates new code,"LEFT"indicates deleted old code