gitlab-mr-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GitLab MR Review Workflow Skill

GitLab MR评审工作流技能

Purpose

目的

The purpose of this skill is to provide constructive and comprehensive feedback on code changes. The primary goals are:
  • Quality Assurance: Identify bugs, potential logic errors, and edge cases.
  • Maintainability: Ensure code is readable, modular, and consistent with the existing architecture.
  • Security: Detect common security vulnerabilities and privacy risks. Validate against OWASP Top 10 where applicable.
  • Education: Provide explanations and context for suggested changes to help the author grow.
This workflow is read-first and non-invasive:
  • Do not modify repository files.
  • Analyze MR content and discussions.
  • Post comments only when explicitly requested.
本技能旨在为代码变更提供具有建设性的全面反馈。主要目标包括:
  • 质量保障:识别bug、潜在逻辑错误及边缘场景。
  • 可维护性:确保代码可读性强、模块化且与现有架构保持一致。
  • 安全性:检测常见安全漏洞和隐私风险。适用时对照OWASP Top 10进行验证。
  • 教育性:为建议的变更提供解释和背景信息,帮助代码作者提升能力。
本工作流遵循先阅读、无侵入原则:
  • 请勿修改仓库文件。
  • 分析MR内容及讨论记录。
  • 仅在明确要求时发布评论。

Inputs Required

所需输入

  1. MR identifiers: Either an MR URL or
    {project_id, merge_request_iid}
  2. Desired action (to be confirmed in Step 6 report):
    • Option 1: Report only (show findings, no GitLab action).
    • Option 2: Discuss, (re)validate or update/delete a specific finding by ID.
    • Option 3: Post + Approve (comments + approval).
    • Option 4: Post + Request Changes (signal that changes are required).
  1. MR标识符:MR链接或
    {project_id, merge_request_iid}
  2. 期望操作(将在第6步报告中确认):
    • 选项1:仅报告(展示评审结果,不执行GitLab操作)。
    • 选项2:讨论、(重新)验证或更新/删除特定ID的评审结果。
    • 选项3:发布评论 + 批准(发布评论并批准MR)。
    • 选项4:发布评论 + 请求变更(表明需要进行修改)。

Required Tools

所需工具

Before starting, verify the following tools are available. If any tool is unavailable, stop and ask the user to install the Gitlab MCP (https://github.com/zereight/gitlab-mcp/tree/main) server.
ToolPurposeStep
mcp_gitlab_get_merge_request
Fetch MR metadata (title, branches, diff refs)Step 2
mcp_gitlab_mr_discussions
Retrieve existing review threadsStep 2
mcp_gitlab_get_branch_diffs
Retrieve diff between branchesStep 4
file_search
/
semantic_search
/
read_file
Explore codebase conventionsStep 1
run_in_terminal
Execute git worktree commandsStep 3, 7-F
mcp_gitlab_create_draft_note
Create inline review commentsStep 7-A
mcp_gitlab_list_draft_notes
Verify draft notes createdStep 7-A
mcp_gitlab_update_draft_note
Correct missing draft notesStep 7-A
mcp_gitlab_bulk_publish_draft_notes
Publish all drafts at onceStep 7-A
mcp_gitlab_approve_merge_request
Approve the MRStep 7-B
mcp_gitlab_execute_graphql
Request changes via GraphQL mutationStep 7-C
mcp_gitlab_update_merge_request
Add current user as reviewer (if needed)Step 7-C
Prohibited: Do not use raw
curl
or
git
CLI commands for API interactions.

开始前,请确认以下工具可用。若任何工具不可用,请停止操作并要求用户安装Gitlab MCP服务器(https://github.com/zereight/gitlab-mcp/tree/main)。
工具用途步骤
mcp_gitlab_get_merge_request
获取MR元数据(标题、分支、diff引用)第2步
mcp_gitlab_mr_discussions
获取现有评审线程第2步
mcp_gitlab_get_branch_diffs
获取分支间的diff第4步
file_search
/
semantic_search
/
read_file
探索代码库约定第1步
run_in_terminal
执行git worktree命令第3步、第7-F步
mcp_gitlab_create_draft_note
创建行内评审评论第7-A步
mcp_gitlab_list_draft_notes
验证草稿评论是否创建成功第7-A步
mcp_gitlab_update_draft_note
修正缺失的草稿评论第7-A步
mcp_gitlab_bulk_publish_draft_notes
批量发布所有草稿评论第7-A步
mcp_gitlab_approve_merge_request
批准MR第7-B步
mcp_gitlab_execute_graphql
通过GraphQL变更请求变更第7-C步
mcp_gitlab_update_merge_request
添加当前用户为评审人(如需)第7-C步
禁止:请勿使用原生
curl
git
CLI命令进行API交互。

Workflow

工作流

Follow these steps in order. Do not skip a step.
按以下步骤依次执行,请勿跳过任何步骤。

Step 1 — Gather Codebase Context

步骤1 — 收集代码库上下文

Quickly identify the project's conventions and architecture:
  1. Search for key structural files (framework config,
    README
    , linting configs).
  2. Read project-level instructions (
    .github/copilot-instructions.md
    ,
    AGENTS.md
    ,
    CLAUD.md
    development docs).
  3. Document: language, framework, architectural patterns, naming conventions, test strategy.
  4. Store these observations as your review baseline for code analysis.
Fallback if conventions are unclear: Infer standards from the detected language/framework:
  • PHP: PSR-12, PSR-4 (autoloading).
  • Python: PEP 8, type hints (PEP 484).
  • JavaScript/TypeScript: ESLint, Google/Airbnb style guides.
  • Go:
    gofmt
    , idiomatic Go patterns.
  • If still unclear, note this assumption in the final report and apply general best practices (SOLID, DRY, KISS).

快速识别项目的约定和架构:
  1. 搜索关键结构文件(框架配置、
    README
    、代码检查配置)。
  2. 阅读项目级说明文档(
    .github/copilot-instructions.md
    AGENTS.md
    CLAUD.md
    等开发文档)。
  3. 记录:编程语言、框架、架构模式、命名约定、测试策略。
  4. 将这些观察结果作为代码分析的评审基准
若约定不明确的备选方案:从检测到的语言/框架推断标准:
  • PHP:PSR-12、PSR-4(自动加载)。
  • Python:PEP 8、类型提示(PEP 484)。
  • JavaScript/TypeScript:ESLint、Google/Airbnb风格指南。
  • Go
    gofmt
    、Go语言惯用模式。
  • 若仍不明确,在最终报告中注明此假设并应用通用最佳实践(SOLID、DRY、KISS)。

Step 2 — Fetch GitLab MR Details

步骤2 — 获取GitLab MR详情

Retrieve all MR metadata needed for the review.
  1. Call
    mcp_gitlab_get_merge_request
    with
    {project_id, merge_request_iid}
    .
    • Extract: title, description, source/target branches, author, labels, milestone, diff refs (
      base_sha
      ,
      start_sha
      ,
      head_sha
      ).
    • Note diff refs: These are required in Step 7-A for inline comment positioning.
  2. Call
    mcp_gitlab_mr_discussions
    to load existing review threads.
    • Note all open and resolved threads to avoid posting duplicate feedback.
  3. Note the MR description for stated intent, linked issues, and breaking-change flags.

获取评审所需的所有MR元数据。
  1. 使用
    {project_id, merge_request_iid}
    调用
    mcp_gitlab_get_merge_request
    • 提取:标题、描述、源/目标分支、作者、标签、里程碑、diff引用(
      base_sha
      start_sha
      head_sha
      )。
    • 注意diff引用:这些是第7-A步中行内评论定位所需的参数。
  2. 调用
    mcp_gitlab_mr_discussions
    加载现有评审线程。
    • 记录所有未关闭和已解决的线程,避免发布重复反馈。
  3. 查看MR描述中注明的变更意图、关联问题及破坏性变更标记。

Step 3 — Checkout MR Branch

步骤3 — 检出MR分支

Create an isolated, read-only worktree for file access:
bash
undefined
创建一个隔离的只读worktree用于文件访问:
bash
undefined

Sanity check: prune orphaned worktrees from previous runs

完整性检查:清理之前运行留下的孤立worktree

git worktree prune
git worktree prune

Fetch the source branch to ensure it exists locally

获取源分支以确保其在本地存在

git fetch origin {source_branch}:{source_branch} 2>/dev/null || true
git fetch origin {source_branch}:{source_branch} 2>/dev/null || true

Create isolated worktree in detached state

创建处于分离HEAD状态的隔离worktree

REPO_ROOT=$(git rev-parse --show-toplevel) WORKTREE_PATH="${REPO_ROOT}/.tmp/mr-review-{merge_request_iid}" git worktree add --detach "${WORKTREE_PATH}" {source_branch}
REPO_ROOT=$(git rev-parse --show-toplevel) WORKTREE_PATH="${REPO_ROOT}/.tmp/mr-review-{merge_request_iid}" git worktree add --detach "${WORKTREE_PATH}" {source_branch}

Lock worktree to prevent accidental modifications

锁定worktree以防止意外修改

git worktree lock "${WORKTREE_PATH}"

Store `worktree_path = "${REPO_ROOT}/.tmp/mr-review-{merge_request_iid}"` for Steps 4–5. **Read-only enforced** — the worktree is locked to prevent file modifications.

---
git worktree lock "${WORKTREE_PATH}"

保存`worktree_path = "${REPO_ROOT}/.tmp/mr-review-{merge_request_iid}"`供第4–5步使用。**强制只读** — worktree已锁定,防止文件被修改。

---

Step 4 — Retrieve and Parse the Diff

步骤4 — 获取并解析Diff

  1. Call
    mcp_gitlab_get_branch_diffs
    using the source and target branches.
  2. Build a file-change inventory: list each changed file with its change type (added / modified / deleted).
  3. Prioritise files for review:
    • High priority: core business logic, security-sensitive code, public APIs, data models.
    • Lower priority: generated files, lock files, migration snapshots, test fixtures.
  4. Constraint: If the diff exceeds 20 files, focus on high-priority files first and note skipped files in the report.
    • Option to user: If >20 files are detected, ask the user whether they want a full review despite the scope; flag this in the report if high-priority files are skipped.

  1. 使用源分支和目标分支调用
    mcp_gitlab_get_branch_diffs
  2. 构建文件变更清单:列出每个变更文件及其变更类型(新增/修改/删除)。
  3. 优先评审以下文件:
    • 高优先级:核心业务逻辑、安全敏感代码、公共API、数据模型。
    • 低优先级:生成文件、锁文件、迁移快照、测试夹具。
  4. 约束:若diff包含超过20个文件,先专注于高优先级文件,并在报告中注明跳过的文件。
    • 用户可选:若检测到超过20个文件,询问用户是否要忽略范围限制进行全面评审;若跳过高优先级文件,需在报告中标记。

Step 5 — Analyze & Classify Findings

步骤5 — 分析并分类评审结果

Analyse each prioritised file against the review baseline. For each changed section, check:
  • Correctness — logic errors, edge cases, incorrect conditionals.
  • Maintainability — architecture adherence, DRY, SOLID, readability, clarity.
  • Security — OWASP Top 10, injection risks, exposed secrets, PII.
  • Consistency — coding standards, naming conventions, codebase patterns (from Step 1 baseline).
  • Scope / Description alignment (if MR description is available) — validate that the actual diff matches the stated intent in the MR description:
    • Identify any changed files or logic that are not mentioned in the description (scope creep or unintended changes).
    • Identify any requirements stated in the description that appear to be missing from the diff.
    • Flag discrepancies as 🟡 Request for Change findings with an explanation of what was expected vs. what was found.
    • If the MR description is empty or absent, skip this check and note its absence in the report.
Determine exact line numbers using the worktree (
read_file
from
{worktree_path}/{file_path}
):
  • For added/modified lines: extract
    new_line
    from the diff API hunk.
  • For deleted lines: extract
    old_line
    from the diff API hunk.
Record each issue:
  • File path and exact line number(s).
  • Short description.
  • Risk/impact.
  • Suggested fix (pseudo code).
Classify by severity:
Use the following guidance table to categorize findings:
SeverityCategoryExamplesAction
🔵 OptionalStyle, naming, minor formattingWhitespace inconsistency, code comments, doc formattingCan be addressed in a follow-up or ignored
🟡 Request for ChangeLogic errors, architectural issues, configuration gapsIncorrect conditionals, missing error handling, data consistency issues, missing translations, naming convention, typos in labels, unused imports, performance concerns, architectural inconsistency, breaking changes, API contract violationsMust be addressed before merge
🔴 Request for ChangeSecurity vulnerabilities, severe bugsSQL injection, XSS vulnerability, exposed secrets/credentials, authentication bypass, buffer overflow, data loss risk, race conditions, privilege escalationMust be addressed before merge
Note on Critical findings: When a finding is a security vulnerability or severe bug, prefix the title with 🔴 (e.g., 🔴 Request for Change — SQL injection vulnerability) Always flag critical findings explicitly to the user before approval.
Before compiling the report: Every finding must use the Comment Template structure
  • READ FIRST: "Comment Template" section below
  • Title with severity and short topic
  • Relevant lines — file path and line number(s)
  • Issue — what is problematic
  • Why it matters — risk/maintenance impact
  • Suggested fix (code and or configuration example)
Do not invent alternative formats or omit any field.
Compile report grouped by severity with totals.

对照评审基准分析每个优先级文件。对每个变更部分,检查:
  • 正确性 — 逻辑错误、边缘场景、条件判断错误。
  • 可维护性 — 架构一致性、DRY原则、SOLID原则、可读性、清晰度。
  • 安全性 — OWASP Top 10、注入风险、敏感信息泄露、PII数据。
  • 一致性 — 编码标准、命名约定、代码库模式(来自步骤1的基准)。
  • 范围/描述匹配 (若MR描述可用) — 验证实际diff是否与MR描述中声明的意图一致:
    • 识别MR描述中未提及的变更文件或逻辑(范围蔓延或意外变更)。
    • 识别MR描述中要求但diff中缺失的内容。
    • 将差异标记为🟡 需要修改的评审结果,并解释预期内容与实际发现的差异。
    • 若MR描述为空或缺失,跳过此检查并在报告中注明。
使用worktree确定准确行号(从
{worktree_path}/{file_path}
调用
read_file
):
  • 对于新增/修改的行:从diff API块中提取
    new_line
  • 对于删除的行:从diff API块中提取
    old_line
记录每个问题:
  • 文件路径和准确行号。
  • 简短描述。
  • 风险/影响。
  • 建议修复方案(伪代码)。
按严重程度分类:
使用以下指南对评审结果进行分类:
严重程度类别示例操作
🔵 可选优化风格、命名、轻微格式问题空格不一致、代码注释、文档格式可在后续迭代中处理或忽略
🟡 需要修改逻辑错误、架构问题、配置缺失条件判断错误、缺少错误处理、数据一致性问题、缺少翻译、命名约定不符、标签拼写错误、未使用的导入、性能问题、架构不一致、破坏性变更、API契约违反合并前必须修复
🔴 需要修改安全漏洞、严重bugSQL注入、XSS漏洞、敏感信息/凭证泄露、身份验证绕过、缓冲区溢出、数据丢失风险、竞态条件、权限提升合并前必须修复
关于严重评审结果的注意事项:当评审结果为安全漏洞或严重bug时,在标题前添加🔴前缀(例如:🔴 需要修改 — SQL注入漏洞)。在批准前必须向用户明确标记严重评审结果。
编译报告前:每个评审结果必须使用评论模板结构
  • 先阅读:下方的"评论模板"部分
  • 包含严重程度和简短主题的标题
  • 相关行 — 文件路径和行号
  • 问题 — 存在的问题
  • 影响 — 风险/维护影响
  • 建议修复方案(代码或配置示例)
请勿使用其他格式或遗漏任何字段。
按严重程度分组并统计总数后编译报告。

Step 6 — Present Findings to the User

步骤6 — 向用户展示评审结果

Present the full findings report to the user before taking any action.
The report must include:
  • MR title, source → target branch, author.
  • Finding totals per severity.
  • Each finding formatted exactly using the Comment Template structure defined above. Prefix each finding with a sequential number (e.g.,
    **Finding #1**
    ) for easy reference in the chat.
Pause here and await user confirmation. Ask the user to choose one of the following actions:
What would you like me to do next?
  1. Report only — no GitLab action, findings are shown above.
  2. Discuss / Refine — discuss, (re)validate or update/delete a specific finding by ID.
  3. Post + Approve — publish all findings and approve the MR.
  4. Post + Request Changes — publish all findings on the MR (signals changes are required).
Do not call any posting, approval, or state-change tool until the user selects one of the options above.

在执行任何操作前,先向用户展示完整的评审结果报告。
报告必须包含:
  • MR标题、源→目标分支、作者。
  • 各严重程度的评审结果总数。
  • 每个评审结果严格按照上述评论模板结构格式化。在聊天报告中,每个评审结果前添加序号前缀(例如:
    **评审结果 #1**
    )以便在聊天中引用。
在此暂停并等待用户确认。请用户选择以下操作之一:
接下来您希望我执行什么操作?
  1. 仅报告 — 不执行GitLab操作,仅展示上述评审结果。
  2. 讨论/优化 — 讨论、(重新)验证或更新/删除特定ID的评审结果。
  3. 发布评论 + 批准 — 发布所有评审结果并批准MR。
  4. 发布评论 + 请求修改 — 在MR上发布所有评审结果(表明需要修改)。
在用户选择上述选项前,请勿调用任何发布、批准或状态变更工具。

Step 7 — Execute Chosen Action (Only When Confirmed)

步骤7 — 执行选定操作(仅在确认后)

Based on the user's choice from Step 6, follow the matching sub-procedure below.
根据用户在步骤6中的选择,执行对应的子流程。

7-A: Post Comments (options 3 and 4)

7-A: 发布评论(选项3和4)

Post all findings as inline draft notes, then publish them in a single batch.
  1. Create draft notes — for each finding, call
    mcp_gitlab_create_draft_note
    :
    • Provide
      project_id
      ,
      merge_request_iid
      .
    • Set
      body
      to the rendered Comment Template output from Step 7. Important: Strip the sequential finding number before posting; numbers are for the report only.
    • Provide a
      position
      object (inline diff comment):
      • position_type: "text"
        for code diffs (use
        "file"
        only if diff positioning fails).
      • base_sha
        ,
        head_sha
        ,
        start_sha
        from Step 2 diff refs.
      • File path: Use
        new_path
        for added/modified files; use
        old_path
        for deleted files.
      • Line numbers from diff API: Use
        new_line
        (for added/modified lines) or
        old_line
        (for deleted lines) as extracted and validated in Step 5. These MUST correspond to actual hunk boundaries from
        mcp_gitlab_get_branch_diffs
        .
    • Save each returned
      draft_note_id
      for verification.
  2. Positioning Fallbacks (if inline positioning fails):
    • Hunk mismatch or stale diff: If the diff positioning is rejected by the API, the diff may be stale or the repository state has changed.
      • Retry with
        position_type: "file"
        on the relevant file path.
      • Include exact file path and line references inside the comment body using the Comment Template structure.
    • Renamed or moved files: For files that have been renamed/moved in the MR:
      • Use
        new_path
        for new sections; use
        old_path
        for removed sections.
      • If GitLab rejects the position, fallback to file-level comment.
    • GitLab API error (e.g.,
      line_code can't be blank
      , invalid position object):
      • Log the error and file path.
      • Retry with
        position_type: "file"
        on the relevant file path.
      • Include exact file path and line references inside the comment body using the Comment Template structure.
  3. Proceed to draft verification
  4. Proceed to draft verification — verify all draft notes were created successfully.
  5. Verify drafts — call
    mcp_gitlab_list_draft_notes
    with
    {project_id, merge_request_iid}
    .
    • Confirm the number of draft notes matches the number of findings.
    • Correct any missing notes using
      mcp_gitlab_update_draft_note
      before publishing.
  6. Publish — call
    mcp_gitlab_bulk_publish_draft_notes
    with
    {project_id, merge_request_iid}
    .
    • All drafts become visible on the MR simultaneously.
将所有评审结果发布为行内草稿评论,然后批量发布。
  1. 创建草稿评论 — 对每个评审结果,调用
    mcp_gitlab_create_draft_note
    • 提供
      project_id
      merge_request_iid
    • body
      设置为步骤7中生成的评论模板内容。重要:发布前移除序号前缀;序号仅用于报告。
    • 提供
      position
      对象(行内diff评论):
      • 对于代码diff,设置
        position_type: "text"
        (仅当diff定位失败时使用
        "file"
        )。
      • 步骤2中获取的diff引用
        base_sha
        head_sha
        start_sha
      • 文件路径:新增/修改的文件使用
        new_path
        ;删除的文件使用
        old_path
      • 来自diff API的行号:使用步骤5中提取并验证的
        new_line
        (新增/修改的行)或
        old_line
        (删除的行)。这些行号必须与
        mcp_gitlab_get_branch_diffs
        返回的实际块边界对应。
    • 保存每个返回的
      draft_note_id
      用于验证。
  2. 定位备选方案(若行内定位失败):
    • 块不匹配或diff过期:若API拒绝diff定位,可能是diff已过期或仓库状态已变更。
      • 使用
        position_type: "file"
        重试,对应相关文件路径。
      • 在评论正文中使用评论模板结构包含准确的文件路径和行号引用。
    • 重命名或移动的文件:对于MR中重命名/移动的文件:
      • 新增部分使用
        new_path
        ;删除部分使用
        old_path
      • 若GitLab拒绝定位,降级为文件级评论。
    • GitLab API错误(例如:
      line_code can't be blank
      、无效的position对象):
      • 记录错误和文件路径。
      • 使用
        position_type: "file"
        重试,对应相关文件路径。
      • 在评论正文中使用评论模板结构包含准确的文件路径和行号引用。
  3. 进入草稿验证环节
  4. 进入草稿验证环节 — 验证所有草稿评论是否创建成功。
  5. 验证草稿 — 使用
    {project_id, merge_request_iid}
    调用
    mcp_gitlab_list_draft_notes
    • 确认草稿评论数量与评审结果数量一致。
    • 发布前使用
      mcp_gitlab_update_draft_note
      修正缺失的评论。
  6. 发布 — 使用
    {project_id, merge_request_iid}
    调用
    mcp_gitlab_bulk_publish_draft_notes
    • 所有草稿将同时在MR上显示。

7-B: Approve (option 3 only)

7-B: 批准MR(仅选项3)

After all draft notes are published (7-A complete):
  1. Call
    mcp_gitlab_approve_merge_request
    with
    {project_id, merge_request_iid}
    .
  2. Confirm approval was recorded (check response for approval state).
  3. Only approve when no 🔴 critical findings were posted. If critical security or severe bug findings exist, warn the user and ask to confirm they still want to approve despite the issues.
完成7-A的草稿评论发布后:
  1. 使用
    {project_id, merge_request_iid}
    调用
    mcp_gitlab_approve_merge_request
  2. 确认已记录批准状态(检查响应中的批准状态)。
  3. 仅当没有🔴严重评审结果时才能批准。若存在严重安全漏洞或bug,警告用户并询问是否仍要批准。

7-C: Request Changes (option 4 only)

7-C: 请求修改(仅选项4)

After all draft notes are published (7-A complete):
  1. Validate reviewer assignment — Before attempting the Request Changes mutation:
    • Retrieve the current MR state using
      mcp_gitlab_get_merge_request
      with
      {project_id, merge_request_iid}
      .
    • Extract the
      reviewers
      array from the response.
    • Check if the current user (typically identified by GitLab session context) is listed in the reviewers.
    • If the current user is NOT a reviewer: Call
      mcp_gitlab_update_merge_request
      to add yourself as a reviewer:
      Parameters:
      - project_id: the project identifier
      - merge_request_iid: the MR IID
      - reviewer_ids: array containing the ID of the current user (retrieve from GitLab user context)
    • Confirm the update was successful before proceeding to step 2.
  2. Submit a formal "Request Changes" review using the GitLab GraphQL mutation
    mergeRequestRequestChanges
    :
    graphql
    mutation RequestChanges($projectPath: ID!, $iid: String!) {
      mergeRequestRequestChanges(input: { projectPath: $projectPath, iid: $iid }) {
        mergeRequest {
          iid
          title
          reviewers {
            nodes {
              username
              mergeRequestInteraction {
                reviewState
              }
            }
          }
        }
        errors
      }
    }
    Call
    mcp_gitlab_execute_graphql
    with the query above and variables:
    • projectPath
      : the full project path (e.g.
      "group/project"
      ) — derived from the project identifier used in Step 2.
    • iid
      : the merge request IID as a string.
  3. Verify the response:
    • Confirm
      errors
      is empty.
    • Check that the current user's
      reviewState
      in the response is
      REQUESTED_CHANGES
      .
    • If the mutation returns errors (e.g., GitLab API issue), inform the user with the error details — the published inline comments still communicate the required changes.
  4. Post an Overall Summary Comment on the MR:
    • You must explicitly post a general comment/note on the MR containing a high-level summary of the key findings.
完成7-A的草稿评论发布后:
  1. 验证评审人分配 — 在尝试请求变更的mutation前:
    • 使用
      {project_id, merge_request_iid}
      调用
      mcp_gitlab_get_merge_request
      获取当前MR状态。
    • 从响应中提取
      reviewers
      数组。
    • 检查当前用户(通常由GitLab会话上下文标识)是否在评审人列表中。
    • 若当前用户不是评审人:调用
      mcp_gitlab_update_merge_request
      将自己添加为评审人:
      参数:
      - project_id: 项目标识符
      - merge_request_iid: MR的IID
      - reviewer_ids: 包含当前用户ID的数组(从GitLab用户上下文获取)
    • 继续步骤2前确认更新成功。
  2. 使用GitLab GraphQL mutation
    mergeRequestRequestChanges
    提交正式的"请求修改"评审
    graphql
    mutation RequestChanges($projectPath: ID!, $iid: String!) {
      mergeRequestRequestChanges(input: { projectPath: $projectPath, iid: $iid }) {
        mergeRequest {
          iid
          title
          reviewers {
            nodes {
              username
              mergeRequestInteraction {
                reviewState
              }
            }
          }
        }
        errors
      }
    }
    使用上述查询和变量调用
    mcp_gitlab_execute_graphql
    • projectPath
      : 完整项目路径(例如
      "group/project"
      ) — 从步骤2使用的项目标识符推导。
    • iid
      : 合并请求的IID(字符串格式)。
  3. 验证响应
    • 确认
      errors
      为空。
    • 检查响应中当前用户的
      reviewState
      是否为
      REQUESTED_CHANGES
    • 若mutation返回错误(例如GitLab API问题),向用户告知错误详情 — 已发布的行内评论仍会传达需要修改的内容。
  4. 在MR上发布整体总结评论
    • 必须在MR上发布一条包含关键评审结果摘要的通用评论/备注。

7-D: Report Only (option 1)

7-D: 仅报告(选项1)

If the user chose "Report only" (no GitLab action):
  1. Skip Steps 7-A, 7-B, and 7-C.
  2. Proceed directly to 7-F cleanup (worktree removal below).
  3. Summary to user: Provide the findings report and note that no draft notes were posted.
若用户选择**"仅报告"**(不执行GitLab操作):
  1. 跳过步骤7-A、7-B和7-C。
  2. 直接进入7-F的清理环节(移除worktree)。
  3. 向用户总结:展示评审结果并说明未发布草稿评论。

7-E: Discuss / Refine Finding (option 2)

7-E: 讨论/优化评审结果(选项2)

If the user chose "Discuss / Refine":
  1. Ask the user which Finding ID they want to discuss or refine.
  2. Discuss the specifics with the user. Update the finding text, severity, or suggested fix based on the consensus.
  3. Remove or keep the finding based on the discussion.
  4. Return directly to Step 6: Summarize the updated findings and present the action options again. Do not proceed to Clean Up yet.
若用户选择**"讨论/优化"**:
  1. 询问用户要讨论或优化的评审结果ID。
  2. 与用户讨论细节。根据共识更新评审结果的文本、严重程度或建议修复方案。
  3. 根据讨论决定保留或删除该评审结果。
  4. 直接返回步骤6:总结更新后的评审结果并再次展示操作选项。暂不进入清理环节。

7-F: Clean Up

7-F: 清理

After all actions are complete (or if option 1 was chosen):
  1. Remove the git worktree with verification:
    bash
    REPO_ROOT=$(git rev-parse --show-toplevel)
    WORKTREE_PATH="${REPO_ROOT}/.tmp/mr-review-{merge_request_iid}"
    
    # Unlock before removal
    git worktree unlock "${WORKTREE_PATH}" 2>/dev/null || true
    
    # Attempt removal with error handling
    if git worktree remove "${WORKTREE_PATH}"; then
      echo "Worktree cleaned up successfully."
    else
      echo "WARNING: Failed to remove worktree at ${WORKTREE_PATH}"
      echo "Run 'git worktree prune' manually to clean orphaned entries."
    fi
  2. Report back to the user:
    • For Report only (option 1): Confirm findings were presented; no actions taken.
    • For Posted comments/approval/request-changes: Draft note IDs that were published, approval state (if applicable), MR state change (if applicable) and include summary with key findings.
    • If any fallback path was used, explain why in one sentence.
    • If worktree cleanup failed, notify the user to run
      git worktree prune
      manually.

完成所有操作后(或选择选项1时):
  1. 移除git worktree并验证
    bash
    REPO_ROOT=$(git rev-parse --show-toplevel)
    WORKTREE_PATH="${REPO_ROOT}/.tmp/mr-review-{merge_request_iid}"
    
    # 移除前先解锁
    git worktree unlock "${WORKTREE_PATH}" 2>/dev/null || true
    
    # 尝试移除并处理错误
    if git worktree remove "${WORKTREE_PATH}"; then
      echo "Worktree清理成功。"
    else
      echo "警告:无法移除${WORKTREE_PATH}的worktree"
      echo "请手动运行'git worktree prune'清理孤立条目。"
    fi
  2. 向用户反馈
    • 仅报告(选项1):确认已展示评审结果;未执行任何操作。
    • 已发布评论/批准/请求修改:说明已发布的草稿评论ID、批准状态(若适用)、MR状态变更(若适用)并包含关键评审结果的摘要。
    • 若使用了备选方案,用一句话说明原因。
    • 若worktree清理失败,告知用户需手动运行
      git worktree prune

Comment Template Example

评论模板示例

Refer to the Comment Template structure defined in Step 5. Here is a concrete example (in the chat report, prefix this with
**Finding #N**
):
text
🟡 Request for Change — avoid repeated magic string

Relevant lines
- path/file.twig around line 108
- path/partial.twig around line 99

Issue
- Repeated literal condition in multiple files.

Why this matters
- Rename risk and inconsistent behavior.

Suggested fix (example)
{# parent #}
set boolean once
pass boolean to include

{# child #}
branch on boolean
参考步骤5中定义的评论模板结构。以下是具体示例(在聊天报告中,需在前面添加
**评审结果 #N**
):
text
🟡 需要修改 — 避免重复的魔法字符串

相关行
- path/file.twig 第108行附近
- path/partial.twig 第99行附近

问题
- 多个文件中存在重复的字面量条件判断。

影响
- 存在重命名风险和行为不一致问题。

建议修复方案(示例)
{# 父模板 #}
统一设置布尔值
将布尔值传递给include标签

{# 子模板 #}
根据布尔值分支处理

Output Style for User

面向用户的输出风格

  • Keep summary concise.
  • State exactly what was posted (thread IDs/note IDs when available).
  • If a fallback path was used, explain why in one sentence.
  • 总结保持简洁。
  • 明确说明已发布的内容(可用时提供线程ID/评论ID)。
  • 若使用了备选方案,用一句话说明原因。

Guardrails

约束规则

  • Post comments only when user selects option 3 or 4 at the end of Step 6 (do not post for option 1).
  • Only approve (option 3) if no 🔴 critical findings — otherwise ask user re-confirmation.
  • Option 4 (request changes) relies on published review comments; no additional MR state change is required.
  • Never merge, alter code, or use alternate providers (GitHub, Jira, etc.).
  • Keep findings tied to concrete diff evidence from the branch worktree.
  • If the workflow is interrupted (user cancels, agent crashes), manually run
    git worktree prune
    to clean orphaned entries and recover disk space.
  • 仅当用户在步骤6选择选项3或4时才发布评论(选项1不发布)。
  • 仅当没有🔴严重评审结果时才能批准(选项3) — 否则需用户重新确认。
  • 选项4(请求修改)依赖已发布的评审评论;无需额外的MR状态变更。
  • 切勿执行合并、修改代码或使用其他平台(GitHub、Jira等)的操作。
  • 评审结果必须基于分支worktree中的具体diff证据。
  • 若工作流被中断(用户取消、代理崩溃),需手动运行
    git worktree prune
    清理孤立条目并回收磁盘空间。

Completion Checklist

完成检查清单

  • Step 1: Codebase context gathered, conventions documented
  • Step 2: MR metadata fetched (title, branches, diffs refs, author), discussions loaded
  • Step 3: Worktree created at
    .tmp/mr-review-{merge_request_iid}
  • Step 4: Diff parsed, files prioritised, high/low priority files identified
  • Step 5: Code analysed, findings classified by severity, description alignment validated (if available), Comment Template fields populated
  • Step 6: Report presented to user, action confirmed (options 1–4 selected)
  • Step 7: Appropriate sub-procedure executed (7-A/B/C/D/E/F), worktree removed, summary reported
  • 步骤1:已收集代码库上下文,记录约定
  • 步骤2:已获取MR元数据(标题、分支、diff引用、作者),加载讨论记录
  • 步骤3:已在
    .tmp/mr-review-{merge_request_iid}
    创建worktree
  • 步骤4:已解析diff,确定文件优先级,识别高/低优先级文件
  • 步骤5:已分析代码,按严重程度分类评审结果,验证描述匹配(若可用),填充评论模板字段
  • 步骤6:已向用户展示报告,确认操作(选择选项1–4)
  • 步骤7:已执行对应的子流程(7-A/B/C/D/E/F),移除worktree,反馈总结