Skip to content

15.2 Skills 上下文管理

上下文管理概述

上下文管理是 Skills 能够理解项目、代码和用户需求的关键机制。本节将深入探讨 Skills 如何收集、存储、检索和利用上下文信息。

上下文类型

1. 项目上下文

1.1 项目结构

项目结构上下文

包含信息

  • 目录层次结构
  • 文件组织方式
  • 模块划分
  • 资源位置

收集方式

  • 扫描文件系统
  • 解析目录结构
  • 识别关键目录
  • 构建结构树
python
### 示例

    bash


    ├── src/
    │   ├── main.py
    │   ├── utils/
    │   │   ├── helpers.py
    │   │   └── validators.py
    │   └── api/
    │       ├── routes.py
    │       └── models.py
    ├── tests/
    │   ├── test_main.py
    │   └── test_utils.py
    ├── docs/
    │   └── api.md
    ├── config/
    │   ├── settings.py
    │   └── logging.yaml
    ├── requirements.txt
    ├── setup.py
    └── README.md
    ~~~#### 1.2 技术栈

    ## 技术栈上下文
    ### 包含信息
    - 编程语言
    - 框架和库
    - 构建工具
    - 测试框架
    - 部署平台
    ### 收集方式
    - 解析依赖文件
    - 检测配置文件
    - 分析导入语句
    - 识别工具链
    ### 示例
    ~~~`yaml
    `yaml

    technology_stack:
    language: Python
    version: "3.9"
    frameworks:
     - Flask 2.3.0
     - SQLAlchemy 2.0.0
    libraries:
     - requests 2.28.0
     - numpy 1.24.0
    build_tools:
     - setuptools
     - wheel
    test_frameworks:
     - pytest 7.3.0
     - pytest-cov
    deployment:
     - Docker
     - Kubernetes

    #### 1.3 配置信息

    ## 配置上下文
    ### 包含信息
    - 应用配置
    - 环境变量
    - 构建配置
    - 部署配置
    ### 收集方式
    - 读取配置文件
    - 解析环境变量
    - 分析设置文件
    - 检测 CI/CD 配置
    ### 示例
    ~~~`python
    `python

    # config/settings.py
    class Config:
    DEBUG = False
    TESTING = False
    DATABASE_URI = os.getenv('DATABASE_URI')
    SECRET_KEY = os.getenv('SECRET_KEY')
    LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')

    class DevelopmentConfig(Config):
    DEBUG = True

    class ProductionConfig(Config):
    DEBUG = False

    ### 2. 代码上下文

    #### 2.1 代码结构

    ## 代码结构上下文
    ### 包含信息
    - 模块组织
    - 类层次结构
    - 函数定义
    - 变量作用域
    ### 收集方式
    - 解析源代码
    - 构建抽象语法树(AST
    - 分析符号表
    - 追踪依赖关系
    ### 示例

    ```

    src/
    ├── main.py
    │   ├── class Application
    │   │   ├── method __init__
    │   │   ├── method run
    │   │   └── method shutdown
    │   └── function main
    ├── utils/
    │   ├── helpers.py
    │   │   ├── function format_date
    │   │   └── function validate_email
    │   └── validators.py
    │       └── class Validator
    │           ├── method validate
    │           └── method sanitize

```python

    ```> > ~~~

    #### 2.2 代码依赖

    ## 代码依赖上下文

    ### 包含信息


    - 导入关系
    - 函数调用
    - 类继承
    - 模块引用

    ### 收集方式


    - 分析 import 语句
    - 追踪函数调用
    - 解析类定义
    - 构建依赖图

    ### 示例

    ~~~`python
    `python

    # 依赖图

    main.py
    ├─> utils/helpers.py
    │   ├─> datetime (标准库)
    │   └─> utils/validators.py
    │       └─> re (标准库)
    ├─> api/routes.py
    │   ├─> flask (外部库)
    │   └─> api/models.py
    └─> config/settings.py
    └─> os (标准库)

    ```> >

    ~~~
    #### 2.3 代码模式

    ## 代码模式上下文
    ### 包含信息
    - 设计模式
    - 编码风格
    - 命名约定
    - 代码规范
    ### 收集方式
    - 模式识别算法
    - 风格分析
    - 命名分析
    - 规则检查
    ### 示例
    ~~~`yaml
    `yaml

    code_patterns:
    design_patterns:
     - singleton: Application
     - factory: create_validator
     - strategy: validate_input

    coding_style:
    naming_convention: snake_case
    max_line_length: 88
    docstring_style: Google

    conventions:
     - use_type_hints: true
     - include_docstrings: true
     - follow_pep8: true

    ```> > ~~~

    ### 3. 用户上下文

    #### 3.1 用户偏好

    ## 用户偏好上下文

    ### 包含信息


    - 编码风格偏好
    - 工具使用偏好
    - 输出格式偏好
    - 交互方式偏好

    ### 收集方式


    - 读取用户配置
    - 分析历史操作
    - 收集用户反馈
    - 学习使用模式

    ### 示例

    ~~~`yaml
    `yaml

    user_preferences:
    coding_style:
    language: Python
    style_guide: PEP8
    formatter: black
    linter: pylint

    output_preferences:
    format: markdown
    verbosity: normal
    include_code_blocks: true

    interaction_preferences:
    auto_confirm: false
    show_progress: true
    color_output: true

    ```> >

    ~~~
    #### 3.2 历史记录

    ## 历史记录上下文
    ### 包含信息
    - 执行过的命令
    - 使用过的 Skills
    - 修改过的文件
    - 生成的内容
    ### 收集方式
    - 记录操作日志
    - 追踪文件变更
    - 统计使用频率
    - 分析操作模式
    ### 示例
    ~~~`json
    `json

    {
    "history": [
    {
    "timestamp": "2024-01-15T10:30:00Z",
    "command": "claude --skill code-review --file src/main.py",
    "skill": "code-review",
    "files": ["src/main.py"],
    "result": "success"
    },
    {
    "timestamp": "2024-01-15T10:35:00Z",
    "command": "claude --skill generate-tests --file src/utils.py",
    "skill": "generate-tests",
    "files": ["src/utils.py", "tests/test_utils.py"],
    "result": "success"
    }
    ]
    }

    ```#### 3.3 学习进度

    ~~~
    markdown

    ## 学习进度上下文

    ### 包含信息


    - 掌握的 Skills
    - 常用的功能
    - 遇到的问题
    - 改进建议

    ### 收集方式


    - 跟踪使用情况
    - 分析错误模式
    - 收集反馈
    - 评估熟练度

    ### 示例

    learning_progress:
    mastered_skills:

     - code-review: 85%
     - generate-tests: 70%
     - refactor: 60%

    frequently_used:

     - code-review: 45
     - generate-tests: 30
     - format-code: 25

    common_issues:

     - type: parameter_validation

    frequency: 10
    suggestion: "使用 --help 查看参数说明"

    improvement_suggestions:

     - "尝试使用更多高级功能"
     - "学习自定义 Skill 开发"

    `> >

    ~~~

    ### 4. 会话上下文

    #### 4.1 对话历史

    ~~~
    markdown

    ## 对话历史上下文

    ### 包含信息


    - 用户请求
    - 系统响应
    - 执行的操作
    - 中间结果

    ### 收集方式


    - 记录对话
    - 追踪操作
    - 保存结果
    - 维护状态

    ### 示例

    {
    "conversation": [
    {
    "role": "user",
    "message": "帮我审查 src/main.py 的代码质量",
    "timestamp": "2024-01-15T10:30:00Z"
    },
    {
    "role": "assistant",
    "message": "正在执行代码审查...",
    "action": "execute_skill",
    "skill": "code-review",
    "timestamp": "2024-01-15T10:30:01Z"
    },
    {
    "role": "assistant",
    "message": "审查完成!发现 5 个问题。",
    "result": {...},
    "timestamp": "2024-01-15T10:30:15Z"
    }
    ]
    }

    `> >

    #### 4.2 执行状态

    ~~~markdown
    markdown

    ## 执行状态上下文

    ### 包含信息


    - 当前任务
    - 执行进度
    - 中间结果
    - 错误信息

    ### 收集方式


    - 跟踪执行
    - 记录进度
    - 保存状态
    - 捕获错误

    ### 示例

    ~~~yaml

    ```yaml

    execution_state:
      current_task:
        skill: code-review
        step: 3/5
        status: in_progress

      progress:
        completed_steps:
          - analyze_structure
          - check_security
        current_step: evaluate_quality
        remaining_steps:
          - generate_report
          - save_results

      intermediate_results:
        issues_found: 3
        security_issues: 1
        quality_score: 75

      errors: []

    #### 4.3 资源状态

    ```markdown

    ## 资源状态上下文

    ### 包含信息

    > - 打开的文件
    > - 使用的工具
    > - 占用的资源
    > - 网络连接

    ### 收集方式

    > - 监控资源
    > - 追踪连接
    > - 统计使用
    > - 检测泄漏

    ### 示例

    ~~~yaml

    ```yaml

    resource_state:
      open_files:
        - src/main.py
        - src/utils.py
        - tests/test_main.py

      active_tools:
        - read_file
        - search_codebase
        - run_command

      resource_usage:
        memory: "256MB"
        cpu: "15%"
        disk_io: "10MB/s"

      network_connections:
        - type: mcp
          server: github
          status: connected

    ## 上下文收集

    ### 收集策略

    #### 1. 按需收集

    ## 按需收集策略
    ### 原则
    - 只收集需要的上下文
    - 避免不必要的开销
    - 动态调整收集范围
    ### 实现方式
    - 分析 Skill 需求
    - 识别必需的上下文
    - 延迟加载非关键上下文
    - 按需扩展收集范围
    ### 示例
    ~~~`python
    `python

    def collect_context(skill_name, parameters):
     # 分析 Skill 需求
    requirements = analyze_skill_requirements(skill_name)

     # 收集必需的上下文
    context = {}
    for req in requirements.required:
    context[req] = collect_required_context(req)

     # 延迟加载可选上下文
    for req in requirements.optional:
    if should_collect(req, parameters):
    context[req] = collect_optional_context(req)

    return context

    ```> >

    ~~~

    #### 2. 增量收集

    ## 增量收集策略

    ### 原则


    - 基于已有上下文
    - 只收集变更部分
    - 减少重复工作

    ### 实现方式


    - 维护上下文快照
    - 检测变更
    - 只更新变更部分
    - 复用未变更部分

    ### 示例

    ~~~`python
    `python

    def incremental_collect(previous_context, changes):
    new_context = previous_context.copy()

    for change in changes:
    if change.type == "file_modified":

     # 只更新变更的文件

    new_context["code"][change.file] = analyze_file(change.file)
    elif change.type == "file_added":

     # 添加新文件

    new_context["code"][change.file] = analyze_file(change.file)
    elif change.type == "file_deleted":

     # 删除文件

    del new_context["code"][change.file]

    return new_context

    ```> > ~~~

    #### 3. 并行收集

    ## 并行收集策略
    ### 原则
    - 同时收集多个上下文
    - 提高收集效率
    - 合理分配资源
    ### 实现方式
    - 识别独立任务
    - 并行执行
    - 合并结果
    - 处理依赖关系
    ### 示例
    ~~~`python
    `python

    async def parallel_collect(context_types):
    tasks = []

     # 创建并行任务
    for ctx_type in context_types:
    if is_independent(ctx_type):
    task = asyncio.create_task(collect_context(ctx_type))
    tasks.append(task)

     # 等待所有任务完成
    results = await asyncio.gather(*tasks)

     # 合并结果
    context = merge_results(results)
    return context

    ```> >

    ~~~

    ### 收集优化

    #### 1. 缓存机制

    ## 缓存机制

    ### 缓存策略


    - 内存缓存(快速访问)
    - 磁盘缓存(持久化)
    - 分布式缓存(多节点)

    ### 缓存键


    - 上下文类型
    - 文件路径
    - 时间戳
    - 版本号

    ### 缓存失效


    - 文件变更
    - 配置更新
    - 时间过期
    - 手动清除

    ### 示例

    ~~~`python
    `python

    class ContextCache:
    def __init__(self):
    self.memory_cache = {}
    self.disk_cache = DiskCache()

    def get(self, key):

     # 先查内存缓存

    if key in self.memory_cache:
    return self.memory_cache[key]

     # 再查磁盘缓存

    value = self.disk_cache.get(key)
    if value:
    self.memory_cache[key] = value
    return value

    return None

    def set(self, key, value, ttl=3600):

     # 设置内存缓存

    self.memory_cache[key] = value

     # 设置磁盘缓存

    self.disk_cache.set(key, value, ttl)

    ```> > ~~~

    #### 2. 智能过滤

    ## 智能过滤
    ### 过滤策略
    - 相关性分析
    - 重要性评分
    - 优先级排序
    - 数量限制
    ### 过滤维度
    - 文件类型
    - 代码复杂度
    - 修改频率
    - 使用频率
    ### 示例
    ~~~`python
    `python

    def filter_context(context, requirements):
    filtered = {}

     # 按相关性过滤
    for item in context.items():
    relevance = calculate_relevance(item, requirements)
    if relevance > threshold:
    filtered[item.key] = item.value

     # 按重要性排序
    sorted_items = sort_by_importance(filtered)

     # 限制数量
    limited = limit_items(sorted_items, max_items)

    return limited

    ```> >

    ~~~

    #### 3. 压缩技术

    ## 压缩技术

    ### 压缩策略


    - 摘要压缩
    - 去重压缩
    - 结构压缩
    - 算法压缩

    ### 压缩方法


    - 提取关键信息
    - 移除冗余数据
    - 简化结构
    - 使用压缩算法

    ### 示例

    ~~~`python
    `python

    def compress_context(context):
    compressed = {}

    for key, value in context.items():

     # 摘要压缩

    if is_large(value):
    compressed[key] = summarize(value)

     # 去重压缩

    elif has_duplicates(value):
    compressed[key] = deduplicate(value)

     # 结构压缩

    else:
    compressed[key] = simplify_structure(value)

    return compressed

    ```## 上下文存储

    ### 存储结构

    #### 1. 层次结构

    ~~~
    markdown

    ## 层次存储结构

    ### 存储层次

    ### 存储策略
    - 热数据存内存
    - 温数据存磁盘
    - 冷数据存远程

    ### 示例
    Context Storage
    ├── Memory Layer
    │   ├── Current Session
    │   ├── Active Skills
    │   └── Frequently Used
    ├── Disk Layer
    │   ├── Project Context
    │   ├── User Preferences
    │   └── Historical Data
    └── Remote Layer
    │   ├── Backup Data
    │   ├── Shared Context
    │   └── Archive Data

    `````> >

    ~~~

    #### 2. 索引结构

    ~~~markdown
    markdown

    ## 索引结构

    ### 索引类型


    - 文件索引
    - 符号索引
    - 依赖索引
    - 时间索引

    ### 索引优化


    - B+ 树索引
    - 哈希索引
    - 全文索引
    - 倒排索引

    ### 示例

    class ContextIndex:
    def __init__(self):
    self.file_index = BPlusTree()
    self.symbol_index = HashIndex()
    self.dependency_index = GraphIndex()
    self.time_index = TimeSeriesIndex()

    def add(self, context_item):

     # 添加到多个索引

    self.file_index.add(context_item.path, context_item)
    self.symbol_index.add(context_item.symbols, context_item)
    self.dependency_index.add(context_item.dependencies, context_item)
    self.time_index.add(context_item.timestamp, context_item)

    def query(self, query):

     # 组合查询

    results = []
    if query.path:
    results.extend(self.file_index.query(query.path))
    if query.symbols:
    results.extend(self.symbol_index.query(query.symbols))
    return deduplicate(results)

    `````> > ~~~

    ### 存储优化

    #### 1. 增量更新

    ~~~markdown
    markdown

    ## 增量更新

    ### 更新策略
    - 检测变更
    - 只更新变更部分
    - 维护版本历史
    - 支持回滚

    ### 实现方式
    - 文件监控
    - 变更检测
    - 差异计算
    - 增量应用

    ### 示例
    def incremental_update(context, changes):
    for change in changes:
    if change.type == "modified":
     # 计算差异
    diff = calculate_diff(context[change.file], change.new_content)
     # 应用差异
    context[change.file] = apply_diff(context[change.file], diff)
    elif change.type == "added":
     # 添加新文件
    context[change.file] = change.new_content
    elif change.type == "deleted":
     # 删除文件
    del context[change.file]

    return context

    `````> >

    ~~~

    #### 2. 版本控制

    ~~~markdown
    markdown

    ## 版本控制

    ### 版本策略


    - 时间戳版本
    - 增量版本
    - 标签版本
    - 分支版本

    ### 版本操作


    - 创建版本
    - 切换版本
    - 比较版本
    - 合并版本

    ### 示例

    class ContextVersionManager:
    def __init__(self):
    self.versions = {}
    self.current_version = None

    def create_version(self, label=None):
    version = {
    "id": generate_id(),
    "timestamp": datetime.now(),
    "label": label,
    "context": copy.deepcopy(self.current_context)
    }
    self.versions[version["id"]] = version
    self.current_version = version["id"]
    return version["id"]

    def switch_version(self, version_id):
    if version_id in self.versions:
    self.current_version = version_id
    self.current_context = copy.deepcopy(self.versions[version_id]["context"])
    return True
    return False

    `````> > ~~~

    ## 上下文检索

    ### 检索策略

    #### 1. 精确检索

    ~~~markdown
    markdown

    ## 精确检索

    ### 检索方式
    - 按键检索
    - 按路径检索
    - 按符号检索
    - 按时间检索

    ### 示例
    def exact_retrieve(context, query):
    if query.type == "key":
    return context.get(query.key)
    elif query.type == "path":
    return context.get_file(query.path)
    elif query.type == "symbol":
    return context.get_symbol(query.symbol)
    elif query.type == "time":
    return context.get_by_time(query.time_range)

    `````> >

    ~~~

    #### 2. 模糊检索

    ~~~markdown
    markdown

    ## 模糊检索

    ### 检索方式


    - 模糊匹配
    - 相似度检索
    - 语义检索
    - 关联检索

    ### 示例

    def fuzzy_retrieve(context, query):
    results = []

    for item in context.items():

     # 计算相似度

    similarity = calculate_similarity(item, query)
    if similarity > threshold:
    results.append((item, similarity))

     # 按相似度排序

    results.sort(key=lambda x: x[1], reverse=True)

    return [item for item, _ in results]

    #### 3. 组合检索

    ~~~
    markdown

    ## 组合检索

    ### 检索方式


    - 多条件组合
    - 逻辑运算
    - 权重组合
    - 分级检索

    ### 示例

    ~~~python

    ```python

    def combined_retrieve(context, query):
        results = []

        # 执行多个检索
        for condition in query.conditions:
            partial_results = retrieve(context, condition)
            results.extend(partial_results)

        # 应用逻辑运算
        if query.operator == "AND":
            results = intersect(results)
        elif query.operator == "OR":
            results = union(results)

        # 应用权重
        weighted_results = apply_weights(results, query.weights)

        return weighted_results

    ### 检索优化

    #### 1. 预计算

    ~~~`markdown

    ````markdown

    ## 预计算

    ### 预计算内容

    > - 统计信息
    > - 关联关系
    > - 索引数据
    > - 聚合结果

    ### 预计算时机

    > - 上下文更新时
    > - 定期批处理
    > - 按需触发

    ### 示例

    ~~~python

    ```python

    def precompute_context(context):
        # 计算统计信息
        stats = calculate_statistics(context)
        context.statistics = stats

        # 计算关联关系
        relations = calculate_relations(context)
        context.relations = relations

        # 构建索引
        index = build_index(context)
        context.index = index

    ```> >

    #### 2. 查询优化

    ~~~`markdown
    `markdown

    ## 查询优化

    ### 优化策略

    > - 查询重写
    > - 执行计划优化
    > - 索引选择
    > - 结果缓存

    ### 示例

    ~~~python

    ```python

    def optimize_query(query, context):
        # 查询重写
        optimized = rewrite_query(query)

        # 选择最佳索引
        best_index = select_best_index(optimized, context.indexes)

        # 生成执行计划
        plan = generate_execution_plan(optimized, best_index)

        return plan


    ## 总结

    Skills 的上下文管理是一个复杂而精密的系统,涉及多种上下文类型、收集策略、存储机制和检索方法。有效的上下文管理能够:

    1. **提高准确性**:提供更准确的上下文信息
    2. **提升性能**:优化上下文收集和检索效率
    3. **增强体验**:提供更流畅的用户体验
    4. **支持扩展**:为功能扩展提供基础

    在下一节中,我们将探讨 Skills 与主代理的交互机制,了解 Skills 如何与主代理协同工作。

    ~~~

基于 MIT 许可发布 | 永久导航