CI Integration Flow for Extracting Knowledge from Merge Requests in TeamAI
The teamai ci extract-mr command automates AI-driven knowledge extraction from Merge Requests, posting insights as idempotent comments and persisting learnings to your team's knowledge repository through a multi-stage pipeline.
The Tencent/teamai-cli repository provides a sophisticated CI integration that transforms Merge Request reviews into persistent, queryable team knowledge. By orchestrating AI analysis, git operations, and graph persistence in src/ci/extract-mr.ts, the tool ensures every code change contributes to an evolving organizational knowledge base.
Step-by-Step Breakdown of the CI Integration Flow
The CI integration follows a rigorous nine-stage pipeline. Each stage handles specific concerns from validation to persistence, with clear separation of responsibilities across the codebase.
1. Parameter Validation and Mode Selection
The pipeline begins by validating runtime requirements. The ciExtractMr function checks that a teamRepo path is supplied when the mode includes writing operations. If validation fails, the process throws immediately (lines 95-97 in src/ci/extract-mr.ts).
The command supports three primary modes:
- comment: Posts analysis results as MR comments only
- write: Persists knowledge to the repository without commenting
- both: Executes comment publication and knowledge writing sequentially
2. AI-Driven Learning Extraction
After validation, the system invokes importFromMR with dryRun: true (lines 100-108) to prevent premature file writes. This stage parses the MR diff, collects changed files, and runs AI summarization to generate two key artifacts:
- A
LearningDraftcontaining educational content about the changes - Optional
CodebaseSuggestionobjects capturing improvement recommendations
3. Idempotent Comment Publication
Depending on the configured opts.mode, the tool publishes feedback through two distinct strategies in src/ci/mr-comment.ts:
postOrUpdateMrComment: Handles single combined comments with idempotent updates (lines 122-133)postIndividualComments: Creates per-item comments with unique HTML markers (lines 75-84)
The idempotency mechanism relies on hidden HTML markers like <!-- teamai:ci-extract -->. Repeated CI runs locate existing comments by these markers and update content rather than creating duplicates.
4. Codebase Graph Extraction and Analysis
Parallel to learning extraction, the pipeline executes the codebase-graph workflow. The diff logic (lines 44-62 in src/ci/extract-mr.ts) identifies changed source files, while the graph builder (lines 68-74) extracts facts and constructs knowledge graph nodes representing modified modules.
If graph nodes are added, postCodebaseGraphComment (lines 35-44 in src/ci/mr-comment.ts) publishes a dedicated "Codebase Graph Change" comment showing added nodes (e.g., module:AuthService) and previews of TeamWiki modules scheduled for incremental updates.
5. Knowledge Persistence and Git Operations
When mode includes write, the writeKnowledgeToRepo function (lines 93-120) executes the persistence layer:
- Creates markdown files under the
learnings/directory - Appends entries to pending-review storage via
src/review-store.tswhenwriteModeis set topending-review - Configures the git user identity through
configureGitUser(lines 46-86) - Pushes changes via
pushRepoDirectlyfromsrc/utils/git.ts
6. Graph Aggregation and Deep Enrichment
Following successful knowledge writes, the pipeline handles graph persistence (lines 13-75 in src/ci/extract-mr.ts):
- Copies generated evidence and graph files into the team repository's
teamwiki/directory - Invokes
src/graph-aggregate.tsto perform global graph aggregation across the entire knowledge base - Calls
src/deep-enrich.tsfor AI-driven enrichment of updated TeamWiki content
7. Artifact Export and Pipeline Completion
If an output directory is specified, writeArtifacts (lines 65-83) exports raw learning markdown and suggestion JSON for downstream CI consumption. The pipeline resolves only after all side effects—comments, repository pushes, and artifact writes—complete successfully.
Idempotency and Rejection Handling
The CI integration implements robust safeguards against noise and unwanted persistence. The marker-based logic in src/ci/mr-comment.ts ensures repeated executions update existing comments rather than spamming the MR with duplicates.
Rejection handling operates through reaction parsing. The readRejections function in src/ci/read-rejections.ts scans for 👍 and 👎 reactions on comments. Before any write operation, shouldWrite filters out items that reviewers have explicitly rejected, respecting team consensus and preventing unwanted knowledge base pollution.
Implementing the CI Integration in Your Pipeline
CLI Usage in CI/CD Pipelines
Integrate the extraction flow into GitHub Actions or GitLab CI using the following pattern:
teamai ci extract-mr \
--url https://github.com/owner/repo/pull/42 \
--mode both \
--team-repo /path/to/team/repo \
--write-mode pending-review \
--dry-run # remove for production
Remove the --dry-run flag after validating your configuration to enable live operations.
Programmatic Integration
For custom automation scripts, import the core function directly:
import { ciExtractMr } from 'teamai-cli/src/ci/extract-mr.js';
await ciExtractMr({
url: 'https://git.woa.com/group/project/merge_requests/17',
mode: 'both',
teamRepo: '/mnt/team-repo',
commentMarker: '<!-- my-marker -->',
writeMode: 'direct',
dryRun: false,
});
Resulting Comment Format
The tool generates structured markdown comments with collapsible sections:
<!-- teamai:ci-extract -->
## TeamAI 知识提炼
### Learning
**Improve cache strategy**
<details><summary>展开完整内容</summary>
```markdown
... learning details ...
MR 合入后将自动应用以上建议到团队知识库.
Auto-generated byteamai ci extract-mr
Graph change comments follow a distinct format with visualization indicators:
```markdown
## 📊 Codebase 知识图谱变更
本次 MR 触发了以下代码知识更新:
### 新增节点 (3)
- `module:AuthService` (auth-service)
- `module:PaymentGateway` (payment-gateway)
- `module:UserProfile` (user-profile)
**📚 Teamwiki 知识库将增量更新以下模块:**
- `auth` (evidence + G-document)
- `payment` (evidence + G-document)
---
> 👎 对本条 comment 添加 reaction 将阻止本次图谱更新写入团队知识库
<!-- teamai:ci-extract:codebase-graph -->
Summary
- The CI integration flow centers on the
teamai ci extract-mrcommand, orchestrating AI extraction, commenting, and persistence across nine distinct stages. - Idempotency is achieved through HTML comment markers that enable update-in-place behavior for repeated CI runs, implemented in
src/ci/mr-comment.ts. - Rejection handling respects reviewer 👍/👎 reactions via
src/ci/read-rejections.tsto prevent unwanted knowledge base updates. - The pipeline supports three operation modes (
comment,write,both) and two write strategies (directvspending-review). - Core source files include
src/ci/extract-mr.tsfor orchestration,src/graph-aggregate.tsfor knowledge graph updates, andsrc/utils/git.tsfor repository operations.
Frequently Asked Questions
How does TeamAI prevent duplicate comments when re-running CI pipelines?
TeamAI implements marker-based idempotency through the postOrUpdateMrComment and postIndividualComments functions in src/ci/mr-comment.ts. Each comment includes a unique HTML marker (e.g., <!-- teamai:ci-extract -->). Before creating new comments, the tool searches existing MR comments for these markers and updates the content in-place rather than creating duplicates.
What is the difference between 'comment', 'write', and 'both' modes?
The comment mode publishes analysis results as MR comments without persisting to the repository. The write mode commits learnings and suggestions to the team repository (under learnings/ and teamwiki/) without posting comments. The both mode executes sequentially, first posting comments for visibility, then persisting approved knowledge to the git repository.
How does the rejection handling mechanism work?
Before writing any knowledge, the readRejections function in src/ci/read-rejections.ts scans MR comments for 👎 reactions on specific items. The shouldWrite utility then filters out rejected learnings or suggestions. This prevents controversial or incorrect AI suggestions from entering the permanent knowledge base while allowing teams to approve valuable contributions with 👍 reactions.
Can I use TeamAI CI integration with both GitHub and GitLab repositories?
Yes, the ciExtractMr function accepts any standard Merge Request or Pull Request URL via the --url parameter. The tool parses the URL structure to interact with the respective platform's API for comment posting and reaction reading. Both GitHub Pull Requests and GitLab Merge Requests are supported through the same command interface.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →