SuperAPI AI Directory

team-wiki-codebase

General & other

View repository

Updated 10-16 09:54

About this skill

team-wiki-codebase — AI cognition engineering for large codebases

The methodology and scripts are located in this skill's references/、scripts/(teamai pull then appears in .cursor/skills/team-wiki-codebase/ or .codebuddy/skills/team-wiki-codebase/). For a human-readable overview, see README.md. Phase 0 structural baseline uses teamai codebase --extract。TeamAI does not ship a separate team-wiki CLI. No extra plugin is required.

What problem it solves: Large projects (10+ repositories, dozens of microservices, evolved over many years) make it impossible for AI to achieve global understanding—the context window cannot hold all the code, component relationships are scattered everywhere, and business rules are hidden in deep call chains. Letting AI read the code directly is both slow (massive tokens) and inaccurate (lack of a global perspective).

How it solves it: Through architecture reverse engineering, massive amounts of code are systematically compressed into astructured, verifiable, AI-Native deep knowledge base—every conclusion can be traced back to a line of code, every relationship is annotated with a confidence level, and every update has incremental verification. AI reads the knowledge base instead of the source code, using about 1/50 of the tokens to gain global architectural cognition.

How to use

/team-wiki-codebase                         # 默认:Standard(单 session 核心路径)
/team-wiki-codebase --deep                  # Deep:完整 K1~K4 + G1~G9
/team-wiki-codebase --update                # 增量更新已有 knowledge/
/team-wiki-codebase continue                # 从 _review/progress.json 断点继续

Agent architecture

Agent File Startup timing
Knowledge base document generation Agent references/agents/kb-doc-generator.md Phase K2 each batch of components
Graph RAG Agent references/agents/graph-rag-agent.md Phase K3

Main Agent responsibilities: process orchestration, confirmation point management, progress.json maintenance, quality report aggregation.


Entry determination

This determination must be executed first on every activation.

IF 用户输入包含 "--update" 或 "增量更新":
  → Update 模式
ELSE IF 用户输入包含 "continue" 或 "继续":
  → Continue 模式
ELSE:
  → 检查用户指定目录下是否有 _review/progress.json
  IF 存在 → 告知状态,等待"继续上次"或"重新开始"
  ELSE    → Phase 0

Continue mode

Step 1:定位 progress.json
Step 2:读取解析,展示恢复摘要
Step 3:根据 current_phase 跳转:
  "phase0_done"              → Phase K1
  "phasek1_waiting_confirm"  → 展示 k1-architecture-map.md,等待确认①
  "phasek1_confirmed"        → Phase K2
  "phasek2_batch_N"          → Phase K2 第 N 批继续(跳过已完成)
  "phasek2_waiting_confirm"  → 等待确认②
  "phasek2_confirmed"        → Phase K3
  "phasek3_done"             → Phase K4
  "phasek4_done"/"completed" → 告知完成,询问是否 --update 或重跑某组件

Update mode (incremental update)

Trigger:/team-wiki-codebase --update or "incremental update". Prerequisite: there is already a progress.json in completed status.

Step 1:读取 progress.json,获取 file_hash_cache
Step 2:扫描 project_root,计算各文件当前 SHA256
Step 3:对比 hash,分类:新增 / 修改 / 删除
Step 4:展示变更摘要,等待用户确认:
  ┌────────────────────────────────────┐
  │ 变更摘要                            │
  │ 新增: N 个文件                      │
  │ 修改: N 个文件(含 Aurora.py 等)   │
  │ 删除: N 个文件                      │
  │ 受影响组件: [列表]                  │
  │ 受影响图谱文档: G1/G2/G6/G7        │
  └────────────────────────────────────┘
Step 5:仅重跑受影响范围:
  - Phase K2:重新生成受影响组件的 Type-4 文档(覆盖写入)
  - Phase K3 局部:更新涉及变更组件的图谱文档(G1/G2/G6/G7)
  - Phase K4:重新运行 validate_kb.py
Step 6:更新 file_hash_cache + metadata.json commit SHA
Step 7:组件级 diff(处理新增/删除仓库或组件)
  IF repos 列表与上次不同:
    新增的仓库 → 对新仓库执行完整 K1 扫描,补充到组件清单,生成 Type-4 文档
    删除的仓库 → 对应组件文档顶部加 `⚠️ [DEPRECATED] 此组件对应仓库已移除`
    → 更新 k1-architecture-map.md 的组件清单
    → 更新 G1 矩阵(移除已删除组件的行列,新增新组件行列)

progress.json specification

Path:<output_dir>/../_review/progress.json

{
  "version": "5",
  "repos": [
    {"name": "repo-a", "path": "/absolute/path/to/repo-a", "language": "go"},
    {"name": "repo-b", "path": "/absolute/path/to/repo-b", "language": "python"}
  ],
  "output_dir": "/absolute/path/to/knowledge",
  "primary_language": "go",
  "project_name": "ProjectName",
  "scan_time": "2026-01-01T10:00:00Z",
  "current_phase": "phasek2_batch_2",
  "confirmed_phases": ["phase0", "phasek1"],

  "service_map": {
    "描述": "Phase K1 Step 3 构建的服务名→仓库映射表",
    "ServiceA": {"repo": "repo-a", "entry": "cmd/serviceA/main.go"},
    "ServiceB": {"repo": "repo-b", "entry": "app/main.py"}
  },

  "kb_progress": {
    "component_total": 12,
    "components_done": ["Aurora", "Frame"],
    "components_pending": ["CCDB", "Dispatcher"],
    "type1_done": false,
    "type2_done": false,
    "type3_done": false,
    "bridge_docs_done": false,
    "graph_rag_done": false
  },

  "accuracy_stats": {
    "total_claims": 0,
    "verified": 0,
    "unverified": 0,
    "ambiguous_relations": 0
  },

  "interface_coverage": {
    "描述": "接口数量对账结果,由 Phase K2 自校验填充",
    "ComponentA": {"type": "HTTP", "scanned": 13, "documented": 0, "gap": 13},
    "ComponentB": {"type": "MQ",   "scanned": 5,  "documented": 0, "gap": 5}
  },

  "consistency_check": {
    "描述": "Phase K3 Step 3 跨文档一致性校验结果",
    "contradictions": 0,
    "missing_refs": 0,
    "g1_deviations": 0,
    "consistency_rate": 0.0
  },

  "e2e_validation": {
    "描述": "Phase K4 Step 4 AI 端到端验证结果",
    "total_questions": 0,
    "correct": 0,
    "partial": 0,
    "incorrect": 0,
    "boundary_ok": 0,
    "boundary_fail": 0,
    "accuracy_rate": 0.0
  },

  "file_hash_cache": {
    "relative/path/to/file.go": "sha256_hex"
  }
}

accuracy_stats is accumulated after each batch of Phase K2 is completed, and is a global indicator of the knowledge base's credibility.


Core principles (accuracy first)

  1. Code is the only source of truth: every conclusion must have a code file:line number as evidence; those that cannot be verified are marked [UNVERIFIED]
  2. Mandatory three-state confidence: every relationship in the graph is marked EXTRACTED(1.0) / INFERRED(0.6~0.9) / AMBIGUOUS(0.1~0.3); inventing out of thin air is prohibited, and using the default value 0.5 is prohibited
  3. Two-level accuracy verification: in Phase K2, each document is self-verified immediately after generation; in Phase K4, full-library quality inspection
  4. Two human-in-the-loop confirmations: architectural understanding (K①) and component document quality (K②) must be manually confirmed to prevent the spread of systemic errors
  5. Parallel generation + resumable processing: Type-4 component documents are distributed in parallel (all Agent calls are sent in the same message); progress.json is persisted after each batch
  6. Token streamlining:Glob → Grep → Read three-step method; full directory scanning is prohibited
  7. Honest audit:[UNVERIFIED] must not be hidden; quality numbers are displayed in full; when uncertain, use AMBIGUOUS rather than deleting
  8. Declaration of cognitive boundaries: The knowledge base README must explicitly declare its coverage and non-coverage scope, so the AI knows when it should say "uncertain"
  9. Cross-document consistency: Phase K3 enforces cross-comparison of inter-component relationship descriptions; contradictory items must be fixed before being counted as "consistent"
  10. End-to-end verifiability: Phase K4 uses standardized questions to test the knowledge base's actual answering capability; the E2E accuracy target is ≥ 80%

Phase 0: Initialization

Ask the user for the following information all at once (same message, no step splitting):

  1. Paths to all code repositories in the project(the user lists all repository addresses involved in the entire project):
    • Format: one absolute path per line, or comma-separated
    • Example:
      /path/to/api-gateway
      /path/to/order-service
      /path/to/user-service
      /path/to/common-lib
      
    • Note: This is the most critical step. In large projects, code is scattered across multiple repositories, andall must be providedto build a complete architectural understanding. Missing repositories = knowledge base blind spots.
  2. Project name(used for document naming, e.g. "CVM", "E-commerce Platform")
  3. Product documentation sources(optional; if provided, generate Type-5/6 bridge documents):
    • API documentation directory path
    • Usage restrictions / FAQ documentation path
  4. Output path(default: under the parent directory of the first repository's knowledge/)

Step 0A: Repository inventory organization

After receiving the repository list provided by the user, build the repository inventory:

FOR 每个用户提供的路径:
  1. 验证路径存在且可访问
  2. 检测是否为 git 仓库(是否有 .git 目录)
  3. 检测主要语言(按文件扩展名分布)
  4. 统计代码规模(文件数 + 估算行数)
  5. 记录 git commit SHA + tag

结果写入 _review/repo-manifest.json:
{
  "repos": [
    {
      "path": "/absolute/path/to/repo-a",
      "name": "repo-a",
      "language": "go",
      "files": 320,
      "lines_estimate": 45000,
      "commit": "abc123",
      "tag": "v1.2.0",
      "accessible": true
    },
    ...
  ],
  "total_repos": N,
  "inaccessible": ["path/to/repo-x(权限不足)"]
}

Show to the user for confirmation:

已识别 {N} 个仓库:
  ✅ repo-a (Go, ~45K 行)
  ✅ repo-b (Python, ~12K 行)
  ✅ repo-c (Go, ~28K 行)
  ❌ repo-x (路径不存在或无法访问)

总计: ~{N}K 行代码,{N} 个仓库
确认无误后回复"继续",或补充遗漏的仓库。

Step 0B: Automatic primary language detection(aggregated by repository list, does not block the process):

检测方法:汇总所有仓库的文件扩展名分布
  .go 文件占比最高         → language: "go"
  .py 文件占比最高         → language: "python"
  .java 文件占比最高       → language: "java"
  .ts/.js 文件占比最高     → language: "typescript"
  .rs 文件占比最高         → language: "rust"
  多语言混合(无明显主导)  → language: "mixed"
备注:language 字段用于接口扫描时选择 grep 模式(详见 Phase K1 Step 5)

Step 0C: Record baseline version:

# 对每个仓库分别记录
FOR repo in repos:
  git -C <repo.path> rev-parse HEAD 2>/dev/null
  git -C <repo.path> describe --tags --always 2>/dev/null

Write to _review/metadata.json:

{
  "project_name": "CVM",
  "scan_time": "<ISO8601>",
  "repos": [
    {"name": "repo-a", "commit": "<sha>", "tag": "<tag>"},
    {"name": "repo-b", "commit": "<sha>", "tag": "<tag>"}
  ]
}

Step 0D: CLI structure baseline (per code repository, recommended)

Before K1 deep reading, use TeamAI to extract evidence-based import/call structural edges (Python/Go/TS, etc.,code-ast) and merge them with the regex baseline (code-heuristic):

# For each repo. Writes <repo>/teamwiki/ (evidence pages + .indices/graph-index.json).
# Existing flags only: --extract [path], optional --project <slug>, optional --incremental.
teamai codebase --extract <repo_abs_path> --project <project_slug>
  • Output: teamwiki/evidence/code/<project>/ pages; teamwiki/.indices/graph-index.json (structural edges).
  • When K1/K2/K3 write _manifest.json 's edges[] :prioritize citing extract's code-ast edges + evidenceRefs(path:line), Agent inferences are marked INFERRED/AMBIGUOUS。
  • After Phase K3, skip any extra graph compile / merge step that is not a teamai command. TeamAI does not ship a separate team-wiki CLI. Continue with this skill using teamai and the files under this skill directory. No extra plugin is required.

Write the initial progress.json (current_phase: "phase0_done"), proceed to Phase K1。


Phase K1: Architecture reverse engineering and source material collection

Methodology:references/methodology/phase0-collection.md + references/methodology/phase1-reverse-engineering.md

Step 1: Optionally run the scanning script (recommended)

python3 scripts/scan_repo.py <project_root> --depth 2 --top 10

Output: file statistics + key file discovery report + language distribution.

Step 2: Key file extraction

Scan by priority (see phase0-collection.md for details):

  • P0 Must-have: entry files, routes/Handlers, process orchestration configuration, Proto/IDL
  • P1 Important: database Schema (DDL), constant/error code definitions
  • P2 Enhancement: configuration files, test files (to understand expected behavior)

Step 3: Architecture reverse engineering (see phase1-reverse-engineering.md for details)

  • Bottom-up layering: leaf nodes (DB/MQ) → intermediate nodes (orchestration/scheduling) → root nodes (API entry points)
  • Three-layer penetration tracing: complete full-chain tracing from API entry → orchestration layer → service execution layer for ≥5 core APIs
  • Build an N×N component relationship matrix (annotating communication methods: RPC/MQ/DB)

Step 4: Generate architecture analysis report

Write to _review/k1-architecture-map.md:

## 架构分层(≥4层)
| 层级 | 组件列表 | 核心职责 | 代码仓库 |

## 组件清单
| 组件名 | 架构层级 | **所属仓库** | 语言 | 核心度(P0/P1/P2) | 入口文件 | **接口校验类型** |

接口校验类型取值(在确认点①请用户核对此列):
  - `HTTP`    → API 接入层,有 HTTP/gRPC 路由注册,需做接口数对账
  - `MQ`      → 消息处理层,有 MQ Consumer/Exchange 声明,以 Topic 数做基准
  - `RPC`     → 内部服务层,有 .proto / .thrift / IDL 文件,以 Method 数做基准
  - `NONE`    → 调度/执行/数据层,无对外接口,不做接口数校验

## N×N 组件通信矩阵
(值:RPC/MQ/DB/—,标注置信度 [E]EXTRACTED/[I]INFERRED/[A]AMBIGUOUS)

## 核心调用链路(≥5条)
(格式:API(file:line) → 编排层(config:line) → 服务层(handler:line) → DB(table))

## 术语表
| 内部术语 | 外部/产品术语 | 说明 |

## 不确定项(供人工确认)
(标注 [A] 的关系和推断,说明不确定原因)
(接口校验类型不确定的组件,标注 [?] 等用户在确认点①明确)

Step 5: Interface inventory scan (execute separately by validation type)

Execute only for components in k1-architecture-map.md whose interface validation type ≠ NONE:

FOR 每个 接口校验类型 = HTTP 的组件:
  执行 grep 扫描:
    Go:   grep -rn "\.GET\|\.POST\|\.PUT\|\.DELETE\|router\.Handle\|@handler" <component_dir>
    Python: grep -rn "@app\.route\|@router\.\|APIRouter\|include_router" <component_dir>
  记录:组件名 → HTTP接口数 N(SCAN_CONFIDENCE: HIGH/MEDIUM)

FOR 每个 接口校验类型 = MQ 的组件:
  执行 grep 扫描:
    grep -rn "Exchange\|Queue\|Topic\|consumer\|subscribe\|@KafkaListener" <component_dir>
  记录:组件名 → MQ Topic/Queue 数 N

FOR 每个 接口校验类型 = RPC 的组件:
  解析 .proto / .thrift 文件:
    find <component_dir> -name "*.proto" -o -name "*.thrift" | xargs grep "^rpc\|^service"
  记录:组件名 → RPC Method 数 N

Write results to _review/interface-inventory.json:

{
  "ComponentA": {"type": "HTTP", "count": 13, "confidence": "HIGH"},
  "ComponentB": {"type": "MQ",   "count": 5,  "confidence": "MEDIUM"},
  "ComponentC": {"type": "RPC",  "count": 8,  "confidence": "HIGH"},
  "ComponentD": {"type": "NONE", "count": 0,  "confidence": "—"}
}

After completion: update current_phase to "phasek1_waiting_confirm"。

⛔ Confirmation point ① — wait for the user's explicit reply; do not automatically proceed to the next stage.

Show to the user:

架构分析完成。

组件清单(共 N 个):
  P0 核心: [列表]
  P1 重要: [列表]
  P2 辅助: [列表]

接口扫描结果(供校验用):
  HTTP 接口:ComponentA 13个, ComponentB 7个
  MQ Topic:  ComponentC 5个
  RPC Method:ComponentD 8个
  无接口组件:ComponentE, ComponentF, ...

AMBIGUOUS 关系(请明确):
  - ComponentX → ComponentY 的通信方式不确定

请确认(直接编辑 k1-architecture-map.md 后回复"继续"):
  1. 架构分层和 P0/P1/P2 标注是否正确?
  2. 每个组件的接口校验类型(HTTP/MQ/RPC/NONE)是否准确?
  3. 接口扫描数量是否合理?明显偏少说明有遗漏,偏多可能扫到了测试文件。

After confirmation: update "phasek1_confirmed" → Phase K2。


Phase K2: Document generation (parallel in batches + intermediate quality confirmation)

Methodology:references/methodology/phase2-document-types.md

Generation order (driven by the dependency chain, write the lower layers first)

批次1: 数据层 + 基础执行层 Type-4 组件文档    ← 并行
批次2: 资源/调度层 Type-4 组件文档            ← 并行
批次3: 消息/服务层 Type-4 组件文档            ← 并行
批次4: API入口层 Type-4 组件文档              ← 并行
           ⛔ 确认点② ← 人工抽查组件文档质量
批次5: 架构总览层 (Type-1 + Type-2 + Type-3) ← 串行(依赖上层全部完成)
批次6: 桥梁文档 (Type-5 + Type-6 + Type-7)   ← 串行(依赖产品文档)
批次7: 知识增强 (Type-8: 反模式/RPC契约/排障) ← 串行

Execution flow for each batch

Read references/agents/kb-doc-generator.md, assemble the input package and start:

component_list:    本批次组件/文档类型列表
architecture_map:  _review/k1-architecture-map.md 完整内容
repos:             _review/repo-manifest.json 中的仓库列表
service_map:       progress.json 中的 service_map
output_dir:        <Phase 0>
project_name:      <Phase 0>
product_docs_dir:  <Phase 0,可为空>
methodology_dir:   references/methodology/
completed_docs:    kb_progress.components_done(断点恢复跳过)
parallel_mode:     true(批次1~4)/ false(批次5~7)

After each batch is completed:

  • Append the completed components to kb_progress.components_done
  • Accumulate accuracy_stats(extracted from the self-validation summary returned by the Agent)
  • Update current_phase to "phasek2_batch_N"
  • Show this batch's token consumption and [UNVERIFIED] statistics

⛔ Confirmation point ② (after batches 1–4 are completed)

Show to the user:

已生成 {N} 份组件设计文档。准确性统计:
  总声明数: {N} | 已验证: {N} | [UNVERIFIED]: {N}({X}%)
  AMBIGUOUS 关系: {N} 条

请抽查 2~3 份文档(建议选最复杂的组件):
  路径:<output_dir>/XX_<组件名>设计说明.md

确认要点:
  1. AI 快速理解表的代码入口是否精确到函数名?
  2. 核心流程描述是否与代码实际一致?
  3. [UNVERIFIED] 比例是否可接受?(建议 <15%)

如发现系统性问题,请描述,我将调整策略后重新生成。

Update current_phase to "phasek2_waiting_confirm". After user confirmation, update to "phasek2_confirmed", and continue with batches 5–7.

After all batches are completed

Write to _review/k2-doc-list.md(document inventory: path + size KB + [UNVERIFIED] count + generation time). Update current_phase to "phasek2_done" → Phase K3。


Phase K3: AI-Native enhancement + graph document set

Methodology:references/methodology/phase3-ai-enhancement.md

Step 1: AI-Native element injection

Supplement all generated documents (if the Phase K2 Agent did not fully add them):

Element Requirement Applicable scope
search-anchor 5–15 keywords, first line after the title All documents
AI quick-understanding table 10 dimensions, immediately after the title All Type-4 component documents
Bidirectional links Component ↔ main architecture, bridge ↔ component All documents
Retrieval routing rules 4 routing rules + 4 priority levels Technical architecture overview only
QA pairs 10–20 high-frequency questions + answer references Technical architecture overview Chapter 9 only

Step 2: Graph RAG graph document set

Read references/agents/graph-rag-agent.md, assemble the input package and start:

all_kb_docs_dir:  <output_dir>
architecture_map: _review/k1-architecture-map.md
doc_list:         _review/k2-doc-list.md
project_name:     <Phase 0>
output_dir:       <output_dir>/graph/
methodology_file: references/methodology/phase2-document-types.md

Generate G1–G9 (each relationship must be annotated with a three-state confidence level):

Graph document Problem solved Confidence requirement
G1 Component dependency relationship matrix "Who depends on X?" EXTRACTED from explicit descriptions in the documents
G2 Call chain panorama + state machine + constraint matrix "Which modules does the API pass through?" Call chain EXTRACTED, inferred dependencies INFERRED
G3 Data flow and storage dependency graph "Where is the data stored?" Read/write relationships EXTRACTED
G4 Error code component mapping table "Which module does the error code belong to?" EXTRACTED
G5 Cross-component Interaction Scenario Manual (≥10 sequence diagrams) "How is quota checking done?" Sequence EXTRACTED, boundaries INFERRED
G6 Knowledge Graph Triples (≥100 entries) "Who does A indirectly depend on?" Each entry labeled E/I/A + score
G7 Architecture Risk and Impact Scope Analysis "How big is the impact if X goes down?" Direct dependencies EXTRACTED, indirect INFERRED
G8 Core Configuration Parameter Index "How do I change the XX configuration?" EXTRACTED from configuration files
G9 Business Rule Constraint Matrix + AI Reasoning Decision Tree "Can XX be done?" Rules EXTRACTED, inferences INFERRED

Simultaneously generate <output_dir>/graph/README.md(index + lookup table by question type + retrieval routing suggestions).

Step 3: Cross-document consistency verification

After the Graph RAG Agent completes, the main Agent executes this step itself (does not delegate to a sub-Agent).

Purpose: detect contradictory descriptions between component documents, preventing inconsistencies such as "A says it calls B via RPC, B says it is called by A via MQ".

Step 3A:构建"声称矩阵"

  对每份 Type-4 组件文档,从**两个层面**提取关系声称:
  
  层面1:AI 快速理解表中的"上游组件"和"下游组件"字段
  层面2:正文中的接口设计章节、核心流程章节中的调用描述
  
  如果层面1和层面2对同一关系描述不一致 → 首先记录为"文档内矛盾"(比表头和正文优先级更高的问题)
  
  提取示例:
    组件X.md 表头声称: X→Y(RPC), X→Z(MQ)
    组件X.md 正文声称: X→Z(HTTP)  ← 与表头矛盾!
    组件Y.md 表头声称: Y←X(RPC), Y→Z(DB)
    组件Z.md 表头声称: Z←X(HTTP), Z←Y(DB)

Step 3B:交叉比对

  FOR 每对组件 (A, B):
    IF A.md 声称 "A→B 用 RPC" AND B.md 声称 "B←A 用 MQ":
      → 记录矛盾: "A→B 通信方式不一致: A说RPC, B说MQ"
    IF A.md 声称 "A→B" BUT B.md 未提到 "被A调用":
      → 记录缺失: "A声称调用B,但B的文档未提及被A调用"
    IF G1矩阵中的关系 与 组件文档声称不一致:
      → 记录偏差: "G1矩阵说A→B(RPC),但A的文档说A→B(MQ)"

Step 3C:生成一致性报告

  写入 `_review/k3-consistency-check.md`:

  ```markdown
  # 跨文档一致性校验报告

  ## 矛盾项(必须修复)
  | 组件A | 组件B | A的描述 | B的描述 | 矛盾类型 |
  |-------|-------|---------|---------|---------|
  | X | Z | X→Z(MQ) | Z←X(HTTP) | 通信方式不一致 |

  ## 缺失项(建议补充)
  | 声称方 | 被引用方 | 声称内容 | 缺失 |
  |--------|---------|---------|------|
  | A | B | A→B(RPC) | B的文档未提及被A调用 |

  ## G1矩阵偏差(建议对齐)
  | G1矩阵 | 组件文档 | 偏差 |

  ## 统计
  - 矛盾项: N 处(❌ 需修复)
  - 缺失项: N 处(⚠️ 建议补充)
  - G1偏差: N 处(⚠️ 需对齐)
  - 一致关系: N 条(✅)
  - 一致率: X%

Step 3D: Automatic repair (only for clear-cut cases)

IF contradictions > 0: FOR each contradiction: Trace back to code for verification: use Grep to find the actual invocation method (e.g., rpc.Call / mq.Publish) IF the correct side can be determined → fix the description in the incorrect side's document + update the G1 matrix IF it cannot be determined → mark as AMBIGUOUS, leave it for the user to confirm at a confirmation point After repair, recalculate the consistency rate

IF contradictions = 0: → skip repair, go directly to Phase K4


**完成后**:更新 `current_phase` 为 `"phasek3_done"` → Phase K4。

---

## Phase K4:知识库质量评估与报告

**方法论**:`references/methodology/phase4-quality.md`

### Step 1:自动校验

```bash
python3 scripts/validate_kb.py <output_dir>

Output (must be displayed in full, not only the passing items):

链接完整性:     ✅/❌  N 个死链接
search-anchor:  ✅/⚠️  覆盖率 N/M (X%)
AI 快速理解表:  ✅/⚠️  覆盖率 N/M (X%)
双向链接:       ✅/⚠️  覆盖率 N/M (X%)
README 索引:    ✅/⚠️  收录率 N/M (X%)

Step 2: Accuracy audit

From accuracy_stats aggregate the credibility of the entire repository, and simultaneously from interface_coverage aggregate the interface coverage:

【内容准确性】
总声明数:            N 条(业务规则 + 接口描述 + 关系)
已验证(有代码引用):   N 条 (X%)
[UNVERIFIED]:        N 条 (X%)
AMBIGUOUS 关系:      N 条 (X%)

【接口覆盖率】(仅统计 HTTP/MQ/RPC 类型组件,NONE 类型不计入)
HTTP 接口:   文档记录 M 个 / 扫描基准 N 个 = X%
MQ Topic:    文档记录 M 个 / 扫描基准 N 个 = X%
RPC Method:  文档记录 M 个 / 扫描基准 N 个 = X%
综合覆盖率:  X%    目标 ≥ 90%

⚠️ 接口缺口清单(文档记录 < 扫描基准 的组件):
  - ComponentA: 文档记录 8 个,扫描基准 13 个,缺口 5 个 → 建议补充

⚠️ Items requiring manual confirmation: (documents with [UNVERIFIED] > 20% + components with interface gaps + AMBIGUOUS relationships)

Step 3: RAG retrieval spot check

According to phase4-quality.md §RAG检索测试用例 test 1 question each for the 7 question types (see methodology for details), and record the hit rate.

Step 4: AI end-to-end validation (E2E Validation)

Core idea: use the knowledge base to answer a set of standardized questions, thentrace back to the code to verify the correctness of the answers, to detect whether the knowledge base enables the AI to give correct answers.

Step 4A:生成标准验证问题集(自动,基于已有文档)

  **优先使用用户提供的外部验证集**:
  IF 用户在 Phase 0 或此时提供了验证问题列表(3~10 个真实业务问题):
    → 优先使用用户问题作为验证集(标注来源: USER)
    → 自动补充至 10~15 题(标注来源: AUTO)
  ELSE:
    → 全部自动生成(标注来源: AUTO)
  
  > 用户提供的问题更有价值,因为 AI 自己出题容易考自己已知的领域,
  > 真正的盲区(AI 没理解但没意识到的)只有外部问题才能测到。

  从 k1-architecture-map.md 和 k2-doc-list.md 自动生成 10~15 个验证问题:

  问题类型分布(至少覆盖以下 5 类):

  ┌────────────────────────────────────────────────────────────────────┐
  │ 类型1:组件职责(3题)                                              │
  │   模式:"<组件名> 的核心职责是什么?代码入口在哪?"                    │
  │   验证方式:答案中的函数名/文件名必须在代码中存在                      │
  │                                                                    │
  │ 类型2:调用关系(3题)                                              │
  │   模式:"<组件A> 和 <组件B> 之间是什么关系?通过什么方式通信?"         │
  │   验证方式:答案与 G1 矩阵 + 代码实际 import/call 一致               │
  │                                                                    │
  │ 类型3:操作约束(2题)                                              │
  │   模式:"在 <状态X> 下能否执行 <操作Y>?"                            │
  │   验证方式:答案与 G9 约束矩阵 + 代码中的状态检查一致                 │
  │                                                                    │
  │ 类型4:数据流向(2题)                                              │
  │   模式:"<操作Z> 最终会写入哪些表/队列?"                             │
  │   验证方式:答案与 G3 数据流 + 代码实际 SQL/MQ 操作一致               │
  │                                                                    │
  │ 类型5:错误排查(2题)                                              │
  │   模式:"错误码 <XXX> 是什么意思?在哪个组件产生?"                    │
  │   验证方式:答案与 G4 错误码映射 + 代码中的错误定义一致               │
  │                                                                    │
  │ 类型6(可选):认知边界测试(2题)                                    │
  │   模式:故意问知识库不覆盖的内容(如第三方 SDK 内部、历史架构变迁)     │
  │   验证方式:AI 应回答"超出知识库覆盖范围"而非幻觉                     │
  └────────────────────────────────────────────────────────────────────┘

Step 4B:用知识库回答(模拟 AI 使用场景)

  FOR 每个验证问题:
    1. 假设只能读知识库文档,不能直接读代码
    2. 按检索路由规则,找到对应文档
    3. 从文档中提取答案

Step 4C:代码回溯验证

  FOR 每个答案:
    1. 用 Grep/Read 直接在代码中验证关键声明
    2. 判定结果:
       ✅ CORRECT     — 答案与代码一致
       ⚠️ PARTIAL     — 答案部分正确,有遗漏或不精确
       ❌ INCORRECT   — 答案与代码矛盾
       🔇 BOUNDARY_OK — 认知边界问题,正确拒绝回答(仅类型6)
       🔇 BOUNDARY_FAIL — 认知边界问题,错误地给出了答案(仅类型6)

Step 4D:写入验证报告

  追加到 k4-quality-report.md 的 ## AI 端到端验证 章节:

  | 问题 | 类型 | 检索文档 | AI答案摘要 | 代码验证 | 结果 |
  |------|------|---------|-----------|---------|------|
  | Aurora 核心职责? | 组件职责 | 03_Aurora设计说明.md | 调度编排... | scheduler.go:42 | ✅ |
  | A→B 通信方式? | 调用关系 | G1矩阵 | RPC | import rpc_client | ✅ |
  | 状态X下能否操作Y? | 操作约束 | G9矩阵 | 不能 | check_state.go:88 | ✅ |
  | 第三方SDK内部? | 认知边界 | — | 超出范围 | — | 🔇 OK |

  统计:
    CORRECT: N/M (X%)
    PARTIAL: N/M (X%)
    INCORRECT: N/M (X%) — ❌ 每个 INCORRECT 必须列出具体矛盾点
    BOUNDARY_OK: N/N
    BOUNDARY_FAIL: N/N

    E2E 准确率 = (CORRECT + BOUNDARY_OK) / 总题数
    目标: ≥ 80%

If the E2E accuracy rate < 80%: list the documents that need improvement and the specific issues in the "suggestions" section of the quality report.

Step 5: Generate the quality report

Write to _review/k4-quality-report.md:

# 知识库质量报告

## 概览
- 代码基准:<commit SHA> (<tag>)
- 生成时间:<ISO8601>
- 文档总数:N 份(Type-1~8: N份,图谱G1~G9: 9份)

## 准确性
| 指标 | 数值 | 状态 |
| 总声明数 | N | — |
| 有代码引用 | N (X%) | ✅/❌ |
| [UNVERIFIED] | N (X%) | ✅/<15% / ⚠️15~25% / ❌>25% |
| AMBIGUOUS关系 | N | ✅/⚠️ |

## 结构质量(validate_kb.py 输出)
(完整展示,不隐藏任何数字)

## 跨文档一致性(k3-consistency-check.md 摘要)
| 指标 | 数值 | 状态 |
| 矛盾项 | N | ✅=0 / ❌>0 |
| 缺失引用 | N | ⚠️ |
| G1偏差 | N | ⚠️ |
| 一致率 | X% | 目标≥95% |

## RAG 检索抽检
| 测试问题 | 期望命中 | 实际命中 | 结果 |

## AI 端到端验证
| 指标 | 数值 | 状态 |
| CORRECT | N/M (X%) | — |
| PARTIAL | N/M (X%) | ⚠️ |
| INCORRECT | N/M (X%) | ❌ |
| BOUNDARY_OK | N/N | ✅ |
| E2E 准确率 | X% | 目标≥80% |

INCORRECT 详情:
(每个 INCORRECT 的具体矛盾点和改进建议)

## 待人工确认清单
([UNVERIFIED] 超标文档 + AMBIGUOUS 关系 + 矛盾项 + 死链接)

## 建议
(基于一致性校验 + E2E 验证的改进方向)

After completion: update current_phase to "completed", the process ends.


Output directory structure

<output_dir>/
├── README.md                           ← 知识库索引 + 检索路由规则 + 认知边界声明(AI 专用)
├── {项目名} 技术架构.md                ← [Type-1] 架构总览(目标 ≤80KB,超过则自动拆分)
├── {项目名} 技术架构-核心链路.md       ← [Type-1b] 仅当 Type-1 超 80KB 时拆出
├── {项目名} 技术架构-AI元数据.md       ← [Type-1c] 仅当 Type-1 超 80KB 时拆出
├── {项目名} 业务架构.md                ← [Type-2] 产品能力 + 生命周期 ~70KB
├── {项目名} 部署架构.md                ← [Type-3] 部署拓扑 ~40KB
├── XX_{组件名}设计说明.md × N          ← [Type-4] 每份 20~100KB
├── XX_{项目名}核心API产品代码映射.md    ← [Type-5] 仅有产品文档时生成
├── XX_{项目名}产品规则速查表.md         ← [Type-6]
├── XX_{项目名}业务开发规范SOP.md       ← [Type-7]
├── {知识增强文档} × N                  ← [Type-8] 反模式/RPC契约/排障/知识文库
└── graph/                              ← [Type-9] Graph RAG 图谱文档集
    ├── README.md                       ← 图谱索引 + 按问题类型查找
    ├── G1_{项目名}组件依赖关系矩阵.md
    ├── G2_{项目名}组件调用链路全景.md
    ├── G3_{项目名}数据流与存储依赖图.md
    ├── G4_{项目名}错误码组件映射表.md
    ├── G5_{项目名}跨组件交互场景手册.md
    ├── G6_{项目名}知识图谱三元组.md
    ├── G7_{项目名}架构风险与影响面分析.md
    ├── G8_{项目名}核心配置参数索引.md
    └── G9_{项目名}业务规则约束矩阵.md

_review/                                ← 过程文件(不入知识库)
├── progress.json                       ← 断点续传 + 增量更新状态
├── metadata.json                       ← 代码基准版本
├── interface-inventory.json            ← 接口扫描基准(Phase K1 Step 5)
├── k1-architecture-map.md              ← 架构逆向结果(用户确认过)
├── k2-doc-list.md                      ← 文档清单 + 准确性统计
├── k3-consistency-check.md             ← 跨文档一致性校验报告(Phase K3 Step 3)
└── k4-quality-report.md                ← 质量报告(含 E2E 验证结果)

Inter-phase control

User reply Behavior
"continue" / "continue" / "ok" Proceed to the next phase
"stop" / "stop" Stop; already generated files remain usable
Describe the issue directly Re-confirm after adjustments, then continue
Reply "continue" after directly editing the file Continue based on the modified file contents

Constraints

  • The main Agent does not perform code analysis: all done by dedicated Agents; before starting, the corresponding agent file must be Read first
  • Redundant output is strictly prohibited: generated files are to be written directly with Write; printing the full content in the conversation first is forbidden
  • Component document naming:XX_{组件名}设计说明.md(XX is a two-digit number, assigned in dependency chain order; lower-level components get smaller numbers)
  • When there is no product documentation: Type-5/6 may be skipped or the constraint value may be annotated as [PRODUCT_DOC_MISSING], without speculation
  • Parallel mode: Type-4 batches must issue all Agent calls concurrently in the same message; serial batches execute sequentially

Honesty Rules

  • Inventing things out of thin air is prohibited: every relationship in the graph must have explicit support in the component documentation and must not be guessed based on names
  • Confidence must not be falsified: EXTRACTED=1.0, INFERRED 0.4 to 0.3 according to evidence strength; the 0.5 default value is forbidden0.9,AMBIGUOUS 0.10.3; disable the 0.5 default value
  • [UNVERIFIED] must not be hidden: if it exceeds 20%, add a visible warning at the top of the document
  • Quality figures are shown in full: validate_kb.py output must not show only passing items
  • Token cost is transparent: after each batch is completed, show the number of files read and the estimated token consumption
  • When uncertain, prefer AMBIGUOUS: rather than deleting or pretending to be certain, mark it as pending confirmation

Coordination with the TeamAI CLI (required reading)

Phase Command / Path
Phase 0 Structural baseline teamai codebase --extract <repo> --project <slug>(writes <repo>/teamwiki/)
Deep knowledge Use teamai codebase --deep-enrich --project <slug> --output <repo> after extract has written teamwiki/evidence/code/<slug>/. --output is the repository root, not the teamwiki/ directory. Prefix with teamai --dry-run to preview without writing. TeamAI does not ship a separate team-wiki CLI. No extra plugin is required.
Compiled into the wiki after K3 Skip. TeamAI does not ship a separate team-wiki CLI. Continue with this skill using teamai and the files under this skill directory. No extra plugin is required.
Product documentation included in the graph Skip. Same English note as above.
Product↔Code bridging Use teamai codebase --reconcile --output <repo> after product pages and extracted code pages are under <repo>/teamwiki/. Prefix with teamai --dry-run to preview without updating the graph.
One-click refresh Use teamai codebase --extract <repo> --project <slug> --incremental, reusing the Phase 0 repository path and project slug even when running from another directory. Do not look for another CLI.
Quality assessment Use scripts/validate_kb.py and teamai codebase --lint --output <repo> to check <repo>/teamwiki/ (--output takes the repository root, not the teamwiki/ directory). Skip any extra evaluate binary.

Path conventions(after this skill is installed):

  • Methodology:references/methodology/*.md(relative to this skill directory)
  • Agent:references/agents/kb-doc-generator.md、references/agents/graph-rag-agent.md
  • Scripts:scripts/scan_repo.py、scripts/validate_kb.py

All processes are completed within this skill (references/、scripts/) and the teamai CLI. No extra plugin is required.