Designing Context for AI Code Review (Part 18)

This article explains how to construct and manage various context data—such as historical review feedback, code diffs, file types, developer experience, commit messages, business scenarios, framework knowledge, and Git logs—to improve the quality of AI‑driven code reviews, and provides a concrete TypeScript implementation with modular context providers, prompt engineering, and integration with GitLab and OpenAI APIs.

Ubiquitous Tech
Ubiquitous Tech
Ubiquitous Tech
Designing Context for AI Code Review (Part 18)

In previous installments the author introduced prompt design and several ways to improve AI code‑review results. This part focuses on building the essential "context capability" for AI code review, because the model lacks awareness of the surrounding environment and may produce irrelevant or overly verbose feedback without sufficient context.

Eight Context Construction Ideas

Historical review suggestion context – Store each review comment with its handling status (fixed, ignored, pending) and associate it with file and line numbers. During a new review, query this data to avoid repeating resolved issues and to prioritize unresolved problems. Implementation can use a database or PR/Issue records in the version‑control system.

New code after change context – Extract only the changed portions via git diff or similar tools and feed them to the AI, allowing it to focus on newly introduced risks. Static analysis or AST parsing can be used to enrich the diff information.

File‑type‑specific context – Detect the file type (e.g., Java, HTML, SQL) and select a corresponding rule set. For HTML, check structure and semantics; for SQL, evaluate query efficiency and security. Existing static analysis tools such as SonarQube can be integrated.

Developer‑level context – Analyze a developer's commit history, project complexity, and bug‑fix count to estimate skill level. Provide detailed style guidance for beginners and focus on optimization for senior developers. Data can be gathered from Git logs or project‑management tools.

Commit‑message context – Parse commit messages with NLP to extract intent (e.g., "fix bug", "add feature") and verify that the code changes match the description, then include this information in the prompt.

Business‑scenario context – Pull requirements, user stories, or JIRA tickets to understand the domain (payment, user management, etc.) and tailor review suggestions (e.g., emphasize transaction safety in payment scenarios).

Framework‑knowledge context – Detect frameworks such as Spring or Hibernate, build a knowledge base of best practices, and let the AI evaluate framework‑specific patterns (e.g., correct dependency injection, transaction management).

Git‑log history context – Extract author, timestamp, changed files, and line numbers from Git logs to reveal evolution trends and frequently modified areas, then feed this data to the model.

Modular Context Management Architecture

The design introduces a Context Manager that coordinates multiple Context Providers . Each provider implements a specific context type (e.g., GitContextProvider, DeveloperContextProvider) and returns a structured XML snippet such as <history> or <code>. This modular approach mirrors factory and strategy patterns.

Core Implementation Steps

Create a context folder under src and define an abstract provider class with methods supportProvider and executeProvideContext.

Implement GitlogContextProvider to fetch Git log data via the GitLab API and format it as XML.

Implement FileFullDataContextProvider to supply the complete file content.

Use XML tags to delimit each context segment, which improves the LLM's ability to parse and prioritize information.

Key Code Snippets

/**
 * 获取文件内容
 */
async getFileSourceCodeData(mergeData:any, change:any) {
    const response = await this.httpclient.get(`/projects/${this.projectId}/repository/files/${encodeURIComponent(change.new_path)}/raw?ref=${mergeData.source_branch}`);
    return response?.data || '';
}

/**
 * 调用 discussions 完成评审结果写入
 */
async addFileReviewComment(result:string) {
    let requestBody:any = { body: result };
    const response = await this.httpclient.post(`/projects/${this.projectId}/merge_requests/${this.mergeId}/discussions`, requestBody);
    return response.data;
}

After adding the context manager, the main execution script ( index.ts) parses command‑line arguments, retrieves merge request data and changes from GitLab, and calls executeDiffFile to perform diff‑based reviews. It also demonstrates sending a Feishu notification with merge details.

async function executeStart() {
  console.log("AI大模型代码评审程序开始执行");
  const { gitlabApiUrl, gitlabAccessToken, openaiApiUrl, openaiAccessToken, projectId, mergeRequestId } = program.opts();
  const openai = new OpenAI(openaiApiUrl, openaiAccessToken);
  const gitlab = new Gitlab({ gitlabApiUrl, gitlabAccessToken, projectId, mergeRequestId });
  const mergeData = await gitlab.getMergeRequestData();
  const changes = await gitlab.getMergeRequestChanges();
  console.log("gitlab获取变更文件数量:" + changes.length);
  await executeDiffFile(mergeData, changes, openai, gitlab);
  // Feishu notification omitted for brevity
}
executeStart();

Prompt Engineering Example

export const prompt4 = `
# 角色
你是一个高度先进的AI代码评审系统,具备深度技术洞察力,能够对代码进行全面评审,确保代码的高性能、可维护性和安全性,具备以下能力和职责:
# 技能
语言理解:你能够理解和分析多种编程语言,包括但不限于Python, Java, C++, JavaScript等。
缺陷检测:识别逻辑错误、内存泄漏、安全漏洞、边界处理、注释完整、魔法值、if 判断和多重嵌套、空指针、异常处理、函数方法长度不超过100行等。
代码优化:提供性能和可扩展性改进建议,同时保持可读性。
最佳实践:遵循当前的最佳编程实践和行业规范。
反馈详细:包含行号、问题描述、影响及解决方案。
代码理解:解析 Git Diff,区分新增 (+) 与删除 (-) 行,并结合提供的文件内容。
业务分析:理解代码业务意图和上下文限制。
# 任务
1、接收用户提交的 Git Diff 代码片段和文件内容,深入分析影响并进行审查。
2、识别不规范、不高效或错误的编码模式。
3、提供清晰的、步骤性的改进建议及代码示例。
4、结构化反馈,包含问题分类、影响评估、解决方案和示例代码。
5、对重点评审内容返回 CheckList,使用 ✅ 表示通过,❌ 表示未通过。
`;

Two review result screenshots (included as images) show that adding file‑content context yields more precise feedback with line numbers, demonstrating a quality improvement.

Conclusion

The article presents a systematic approach to enriching AI code‑review prompts with diverse context sources, outlines a modular architecture for context generation, and provides concrete TypeScript implementations that integrate GitLab, OpenAI, and notification services. Future work may combine knowledge bases and Retrieval‑Augmented Generation (RAG) to further enhance review quality.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

software architectureTypeScriptprompt engineeringGitLabAI code reviewcontext management
Ubiquitous Tech
Written by

Ubiquitous Tech

A ubiquitous public account for pirate enthusiasts, regularly sharing curated experiences, tech learning, and growth insights. Currently publishing articles on AI RAG customer service, AI MCP technology, and open-source design. Personal free Knowledge Planet: Awakening New World Programmer.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.