knowledge-graph
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseKnowledge Graph Skill
知识图谱Skill
Overview
概述
Persistent JSON storage that caches agent discoveries and codebase analysis. Remember findings across sessions, validate task dependencies, query patterns/components/APIs, skip redundant exploration.
Location:
docs/specs/[ID-feature]/knowledge-graph.json持久化JSON存储,用于缓存Agent探索结果和代码库分析数据,可跨会话留存发现内容、验证任务依赖、查询模式/组件/API,避免重复探索。
存储位置:
docs/specs/[ID-feature]/knowledge-graph.jsonWhen to Use
适用场景
- Cache results - Before launching expensive codebase analysis, check if findings are already stored
- Remember findings - After agent exploration, persist discoveries for future use
- Reuse discoveries - Query existing context to maintain consistency across tasks
- Validate dependencies - Check if required components/APIs exist before implementing
- Look up previous work - Find what patterns, components, or APIs were already discovered
- 缓存结果 - 启动耗时的代码库分析前,检查是否已经存储了相关结果
- 留存发现 - Agent探索完成后,持久化探索结果供后续使用
- 复用探索内容 - 查询现有上下文,保证多任务间的一致性
- 验证依赖 - 实现功能前检查所需的组件/API是否存在
- 查询历史工作 - 查找已经发现的模式、组件或API
Instructions
使用说明
read-knowledge-graph
read-knowledge-graph
Read existing Knowledge Graph or initialize empty structure:
Read file_path="docs/specs/001/knowledge-graph.json"Returns full KG content. If file missing, returns empty structure and creates on first update.
读取现有知识图谱或初始化空结构:
Read file_path="docs/specs/001/knowledge-graph.json"返回完整的知识图谱内容。如果文件不存在,返回空结构,并在首次更新时创建文件。
query-knowledge-graph
query-knowledge-graph
Query specific sections: , , , ,
componentspatternsapisintegration-pointsallRead file_path="docs/specs/001/knowledge-graph.json"Filter results by section and process in-memory.
查询指定分区:、、、、
componentspatternsapisintegration-pointsallRead file_path="docs/specs/001/knowledge-graph.json"按分区过滤结果后在内存中处理。
update-knowledge-graph
update-knowledge-graph
undefinedundefined1. Read existing
1. 读取现有内容
Read file_path="docs/specs/001/knowledge-graph.json"
Read file_path="docs/specs/001/knowledge-graph.json"
2. Deep-merge updates (arrays append by ID, objects preserve existing)
2. 深度合并更新内容(数组按ID追加,对象保留已有内容)
3. Update timestamp
3. 更新时间戳
Write file_path="docs/specs/001/knowledge-graph.json" content="<merged JSON>"
**Deep-merge rules:**
- Arrays: append new items, deduplicate by `id` field
- Objects: preserve existing keys, add/update new keys
- Always update `metadata.updated_at` to current ISO timestamp
**Complete JSON example for update:**
```json
{
"metadata": {
"spec_id": "001-hotel-search",
"created_at": "2026-03-14T10:30:00Z",
"updated_at": "2026-03-23T10:00:00Z",
"version": "1.0.0"
},
"patterns": {
"architectural": [
{
"id": "pat-001",
"name": "Repository Pattern",
"convention": "Extend JpaRepository<Entity, ID>",
"files": ["src/main/java/**/repository/*Repository.java"]
}
]
},
"components": {
"services": [
{
"id": "comp-svc-001",
"name": "HotelService",
"location": "src/main/java/com/example/hotel/service/HotelService.java",
"type": "service",
"methods": [{"name": "searchHotels", "returns": "List<HotelDTO>"}]
}
]
}
}Write file_path="docs/specs/001/knowledge-graph.json" content="<merged JSON>"
**深度合并规则:**
- 数组:追加新条目,按`id`字段去重
- 对象:保留已有键,新增/更新新键
- 始终将`metadata.updated_at`更新为当前ISO时间戳
**完整的更新JSON示例:**
```json
{
"metadata": {
"spec_id": "001-hotel-search",
"created_at": "2026-03-14T10:30:00Z",
"updated_at": "2026-03-23T10:00:00Z",
"version": "1.0.0"
},
"patterns": {
"architectural": [
{
"id": "pat-001",
"name": "Repository Pattern",
"convention": "Extend JpaRepository<Entity, ID>",
"files": ["src/main/java/**/repository/*Repository.java"]
}
]
},
"components": {
"services": [
{
"id": "comp-svc-001",
"name": "HotelService",
"location": "src/main/java/com/example/hotel/service/HotelService.java",
"type": "service",
"methods": [{"name": "searchHotels", "returns": "List<HotelDTO>"}]
}
]
}
}validate-against-knowledge-graph
validate-against-knowledge-graph
undefinedundefined1. Read KG
1. 读取知识图谱
Read file_path="docs/specs/001/knowledge-graph.json"
Read file_path="docs/specs/001/knowledge-graph.json"
2. Check KG contains required IDs
2. 检查知识图谱是否包含所需的ID
3. Verify actual files exist
3. 验证实际文件是否存在
Grep pattern="src/**/HotelRepository.java"
Report satisfied dependencies and missing components.
---Grep pattern="src/**/HotelRepository.java"
上报已满足的依赖和缺失的组件。
---validate-contract
validate-contract
undefinedundefined1. Read KG and task expectations
1. 读取知识图谱和任务预期
Read file_path="docs/specs/001/knowledge-graph.json"
Glob pattern="src/**/ExpectedFile.java"
Grep pattern="class ExpectedClass|interface ExpectedInterface"
Read file_path="docs/specs/001/knowledge-graph.json"
Glob pattern="src/**/ExpectedFile.java"
Grep pattern="class ExpectedClass|interface ExpectedInterface"
2. Match expectations against KG.provides
2. 将预期与KG.provides内容匹配
3. Report satisfied/unsatisfied contracts
3. 上报满足/不满足的合约
---
---extract-provides
extract-provides
undefinedundefined1. Find implementation files
1. 查找实现文件
Glob pattern="src/**/*.java"
Glob pattern="src/**/*.java"
2. Extract symbols
2. 提取符号
Grep pattern="^(public|protected)? (class|interface|enum) " output_mode="content"
Grep pattern="^(public|protected)? (class|interface|enum) " output_mode="content"
3. Classify by directory: /entity/ → entity, /service/ → service, /repository/ → repository
3. 按目录分类:/entity/ → entity, /service/ → service, /repository/ → repository
4. Update KG.provides with {task_id, file, symbols, type, implemented_at}
4. 用 {task_id, file, symbols, type, implemented_at} 更新KG.provides
---
---aggregate-knowledge-graphs
aggregate-knowledge-graphs
undefinedundefined1. Find all KG files
1. 查找所有知识图谱文件
Glob pattern="docs/specs/*/knowledge-graph.json"
Glob pattern="docs/specs/*/knowledge-graph.json"
2. Read each, extract patterns.architectural and patterns.conventions
2. 读取每个文件,提取patterns.architectural和patterns.conventions
3. Write merged .global-knowledge-graph.json
3. 写入合并后的.global-knowledge-graph.json
Write file_path="docs/specs/.global-knowledge-graph.json" content="<aggregated>"
---Write file_path="docs/specs/.global-knowledge-graph.json" content="<aggregated>"
---Schema Structure
模式结构
knowledge-graph.json
├── metadata (spec_id, created_at, updated_at, version, analysis_sources)
├── codebase_context (project_structure, technology_stack)
├── patterns (architectural[], conventions[])
├── components (controllers[], services[], repositories[], entities[], dtos[])
├── provides[] ({ task_id, file, symbols[], type, implemented_at })
├── apis (internal[], external[])
└── integration_points[]Complete schema with field definitions: See
references/schema.mdknowledge-graph.json
├── metadata (spec_id, created_at, updated_at, version, analysis_sources)
├── codebase_context (project_structure, technology_stack)
├── patterns (architectural[], conventions[])
├── components (controllers[], services[], repositories[], entities[], dtos[])
├── provides[] ({ task_id, file, symbols[], type, implemented_at })
├── apis (internal[], external[])
└── integration_points[]含字段定义的完整模式: 参见
references/schema.mdError Handling
错误处理
| Scenario | Handling |
|---|---|
| File not found | Return empty KG; creates on first update |
| Invalid JSON | Raise error; offer to recreate from analysis |
| Merge conflicts | Deep-merge preserves existing, adds new with timestamps |
| Write failure | Log error; continue without caching (non-blocking) |
Update workflow:
- Read: →
Readdocs/specs/[ID]/knowledge-graph.json - Validate update JSON structure
- Deep-merge updates into KG object
- Write: → same path
Write - Verify write succeeded
| 场景 | 处理方式 |
|---|---|
| 文件未找到 | 返回空知识图谱;首次更新时创建文件 |
| JSON无效 | 抛出错误;提供从分析重新生成的选项 |
| 合并冲突 | 深度合并保留已有内容,新增内容附带时间戳 |
| 写入失败 | 记录错误;不缓存继续执行(非阻塞) |
更新工作流:
- 读取:→
Readdocs/specs/[ID]/knowledge-graph.json - 验证更新JSON的结构
- 将更新内容深度合并到知识图谱对象
- 写入:→ 同一路径
Write - 验证写入成功
Best Practices
最佳实践
Before expensive operations:
- Query KG first to check for cached analysis
- If fresh (< 7 days), skip redundant exploration
- Offer user choice: use cached or re-explore
After discoveries:
- Update KG immediately after agent analysis completes
- Include source agent/timestamp in metadata
- Batch similar updates, avoid per-operation writes
Freshness guidelines:
- < 7 days: Fresh, safe to use
- 7-30 days: Consider regenerating
-
30 days: Stale, re-analysis recommended
执行耗时操作前:
- 先查询知识图谱检查是否有缓存的分析结果
- 如果内容较新(<7天),跳过重复探索
- 提供用户选择:使用缓存或重新探索
获得探索结果后:
- Agent分析完成后立即更新知识图谱
- 在元数据中包含来源Agent/时间戳
- 批量处理相似更新,避免每次操作都写入
新鲜度指引:
- <7天:新鲜,可安全使用
- 7-30天:考虑重新生成
-
30天:过时,建议重新分析
Examples
示例
Cache Agent Discoveries (Complete Workflow)
缓存Agent探索结果(完整工作流)
undefinedundefinedStep 1: Check existing KG
步骤1:检查现有知识图谱
Read file_path="docs/specs/001/knowledge-graph.json"
Read file_path="docs/specs/001/knowledge-graph.json"
Step 2: Analyze codebase (agent task)
步骤2:分析代码库(Agent任务)
Glob pattern="src/main/java/**/*.java"
Grep pattern="public (class|interface) " output_mode="content"
Glob pattern="src/main/java/**/*.java"
Grep pattern="public (class|interface) " output_mode="content"
Step 3: Build update with discoveries
步骤3:构建包含探索结果的更新内容
Write file_path="docs/specs/001/knowledge-graph.json" content="{
"metadata": {
"spec_id": "001-hotel-search",
"created_at": "2026-03-14T10:30:00Z",
"updated_at": "2026-03-23T10:00:00Z",
"version": "1.0.0",
"analysis_sources": [{"agent": "general-code-explorer", "timestamp": "2026-03-23T10:00:00Z"}]
},
"patterns": {
"architectural": [{
"id": "pat-001",
"name": "Repository Pattern",
"convention": "Extend JpaRepository<Entity, ID>"
}]
},
"components": {
"services": [{
"id": "comp-svc-001",
"name": "HotelService",
"location": "src/main/java/com/example/hotel/service/HotelService.java",
"type": "service"
}],
"repositories": [{
"id": "comp-repo-001",
"name": "HotelRepository",
"location": "src/main/java/com/example/hotel/repository/HotelRepository.java",
"type": "repository"
}]
}
}"
undefinedWrite file_path="docs/specs/001/knowledge-graph.json" content="{
"metadata": {
"spec_id": "001-hotel-search",
"created_at": "2026-03-14T10:30:00Z",
"updated_at": "2026-03-23T10:00:00Z",
"version": "1.0.0",
"analysis_sources": [{"agent": "general-code-explorer", "timestamp": "2026-03-23T10:00:00Z"}]
},
"patterns": {
"architectural": [{
"id": "pat-001",
"name": "Repository Pattern",
"convention": "Extend JpaRepository<Entity, ID>"
}]
},
"components": {
"services": [{
"id": "comp-svc-001",
"name": "HotelService",
"location": "src/main/java/com/example/hotel/service/HotelService.java",
"type": "service"
}],
"repositories": [{
"id": "comp-repo-001",
"name": "HotelRepository",
"location": "src/main/java/com/example/hotel/repository/HotelRepository.java",
"type": "repository"
}]
}
}"
undefinedValidate Task Dependencies
验证任务依赖
undefinedundefinedRead KG and task requirements
读取知识图谱和任务需求
Read file_path="docs/specs/001/knowledge-graph.json"
Read file_path="docs/specs/001/knowledge-graph.json"
Verify components exist in codebase
验证代码库中是否存在相关组件
Grep pattern="src/main/java/com/example/hotel/repository/HotelRepository.java"
Grep pattern="src/main/java/com/example/hotel/service/HotelService.java"
Grep pattern="src/main/java/com/example/hotel/repository/HotelRepository.java"
Grep pattern="src/main/java/com/example/hotel/service/HotelService.java"
Report validation result
上报验证结果
If all found: "All dependencies satisfied, proceed with implementation"
如果全部找到:"所有依赖已满足,可继续实现"
If missing: "Warning: HotelService not found. Create it first?"
如果缺失:"警告:未找到HotelService,是否先创建该组件?"
undefinedundefinedQuery for Context Before Task Generation
生成任务前查询上下文
undefinedundefinedLoad KG to get cached context
加载知识图谱获取缓存上下文
Read file_path="docs/specs/001/knowledge-graph.json"
Read file_path="docs/specs/001/knowledge-graph.json"
Present summary to user:
向用户展示摘要:
"Found cached analysis (2 days old):
"找到缓存的分析结果(2天前更新):
- Patterns: Repository Pattern, Service Layer
- 设计模式:Repository Pattern、服务层模式
- Components: HotelService, HotelController
- 组件:HotelService、HotelController
- Conventions: naming with *Controller/*Service/*Repository
- 规范:命名采用*Controller/*Service/*Repository后缀
Use cached context for task generation?"
是否使用缓存上下文生成任务?"
**More examples:** See `references/query-examples.md`
---
**更多示例:** 参见 `references/query-examples.md`
---Constraints and Warnings
约束与警告
Critical Constraints:
- Read-only on source code; only creates/updates
knowledge-graph.json - Only reads/writes KG files from paths
docs/specs/[ID]/ - Does NOT generate implementation code automatically
Limitations:
- Validation checks KG only; cannot verify actual codebase if KG outdated
- KG accuracy depends on freshness; re-explore if > 7 days old
- Cross-spec learning only via operation
aggregate
Warnings:
- KG > 30 days old may not reflect current codebase state
- Validator may report false negatives if KG predates implementation
- Merge strategy preserves existing values; explicit overwrite required to replace
核心约束:
- 对源代码为只读权限;仅创建/更新文件
knowledge-graph.json - 仅读写路径下的知识图谱文件
docs/specs/[ID]/ - 不会自动生成实现代码
限制:
- 验证仅基于知识图谱内容;如果知识图谱过时,无法验证实际代码库状态
- 知识图谱准确性取决于新鲜度;超过7天建议重新探索
- 跨规范学习仅能通过操作实现
aggregate
警告:
- 超过30天的知识图谱可能无法反映当前代码库状态
- 如果知识图谱的更新时间早于实现时间,验证器可能会报假阴性
- 合并策略会保留现有值,替换内容需要显式覆盖
See Also
相关参考
- - Complete JSON schema with field definitions
references/schema.md - - Query patterns and integration examples
references/query-examples.md - - Command integration details
references/integration-patterns.md
- - 含字段定义的完整JSON模式
references/schema.md - - 查询模式和集成示例
references/query-examples.md - - 命令集成细节
references/integration-patterns.md