用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/huangwb8/skills --skill context-optimizer命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
检查 Markdown 文档中的引用是否可定位、URL 或锚点是否可访问,并整理供后续判断引用真实性与适切性的结构化证据。当用户要求核查引用、检查文档链接,或确认引用是否支持正文论断时使用。
规范 AI 开发 R Markdown 分析脚本的行为准则。当用户要求"写 Rmd 分析"、"开发 R 脚本"、"做数据分析"时触发。核心原则:遵循主业与副业分离架构(.R 保留完整数据,.Rmd 应用业务阈值),优先使用用户已有 R 包资源;图表默认按 Nature 级别可读性与出版质量生成;专家级解读兼顾弱背景读者,提供四层框架、指标导读与不常用指标首次解释协议;路径验证确保跨平台兼容性。前提:luckyBase 为硬依赖。
当需要把本仓库 skills/alpha 下的生产 skills 安装到系统级(默认同时安装到 Codex: ~/.codex/skills 和 Claude Code: ~/.claude/skills),以便在任意项目/对话中可被发现与调用时使用。默认不安装 skills/beta;只有显式指定 beta 源目录时才处理 beta skill。使用 MD5 哈希进行版本控制,仅安装有更新的 skills;支持 --skill 指定单个或少量技能安装/更新、强制覆盖安装、指定单一目标安装和远程安装模式(--remote --check/--auto)。
正在显示 SKILL.md
| name | context-optimizer |
| description | 上下文优化专家。专注于长对话中的上下文管理、token 效率和性能优化。解决 lost-in-middle、context poisoning 等问题,提升 AI 代理在复杂任务中的表现。 |
| metadata | {"short-description":"上下文管理与优化","keywords":["context-optimizer","上下文优化","token 效率","长对话","压缩策略","缓存机制","性能优化","上下文窗口"],"category":"性能优化","author":"Bensz Conan","platform":"Claude Code | OpenAI Codex | ChatGPT"} |
本 Skill 的新任务中间文件统一写入 ./.bensz-api/task-{yyyymmdd-hhmm}-{简短描述}/{skill名}/input|output|log/。同一任务复用一个任务根目录;多 Skill 协作才创建 shared/。正式交付物不写入该目录,历史隐藏目录只允许显式兼容读取、迁移或清理。
bensz-collect-bugs 规范记录到 ~/.bensz-skills/bugs/,不要直接修改用户本地已安装的 skill 源码;若有 workaround,先记 bug,再继续完成任务。gh 上传新增 bug 到 huangwb8/bensz-bugs;不要 pull / clone 整个仓库。上下文优化 是长对话性能的关键:
┌─────────────────────────────────────────────────────────┐
│ 识别问题 → 压缩历史 → 掩码加载 → 缓存重用 → 性能提升 │
└─────────────────────────────────────────────────────────┘
核心问题:
在以下场景时激活:
表现:
检测:
def detect_lost_in_middle(conversation: list) -> bool:
"""检测是否出现 lost-in-middle 问题"""
# 1. 检查对话长度
if len(conversation) < 10:
return False
# 2. 检查是否有重复提问
questions = [msg for msg in conversation if '?' in msg]
unique_questions = set(questions)
if len(questions) > len(unique_questions) * 1.5:
return True # 存在重复提问
# 3. 检查中间内容是否被引用
middle_start = len(conversation) // 3
middle_end = len(conversation) * 2 // 3
middle_content = conversation[middle_start:middle_end]
# 检查后续对话是否引用中间内容
later_refs = sum(
1 for msg in conversation[middle_end:]
if any(keyword in msg for keyword in extract_keywords(middle_content))
)
if later_refs < len(middle_content) * 0.1:
return True # 中间内容被遗忘
return
表现:
检测:
def detect_context_poisoning(conversation: list) -> list:
"""检测上下文污染"""
conflicts = []
# 1. 提取所有事实陈述
facts = extract_facts(conversation)
# 2. 检测矛盾
for fact1, fact2 in combinations(facts, 2):
if are_contradictory(fact1, fact2):
conflicts.append({
'type': 'contradiction',
'fact1': fact1,
'fact2': fact2,
'severity': 'high'
})
# 3. 检测信息源冲突
sources = group_by_source(facts)
for source, source_facts in sources.items():
if has_internal_conflicts(source_facts):
conflicts.append({
'type': 'source_conflict',
'source': source,
'severity': 'medium'
})
return conflicts
class ContextCompressor:
"""上下文压缩器"""
def compress_history(
self,
conversation: list,
max_tokens: int,
retention_priority: list[str] = None
) -> list:
"""
压缩对话历史
Args:
conversation: 对话历史
max_tokens: 最大 token 数
retention_priority: 保留优先级 ["current_task", "decisions", "errors"]
Returns:
压缩后的对话
"""
priority = retention_priority or ["current_task", "decisions", "errors"]
# 1. 分类消息
categorized = self._categorize_messages(conversation)
# 2. 按优先级保留
retained = []
current_tokens = 0
for category in priority:
messages = categorized.get(category, [])
for msg in messages:
tokens = self._count_tokens(msg)
if current_tokens + tokens > max_tokens:
# 尝试压缩
compressed = self._compress_message(msg)
if current_tokens + self._count_tokens(compressed) <= max_tokens:
retained.append(compressed)
current_tokens += self._count_tokens(compressed)
else:
retained.append(msg)
current_tokens += tokens
return retained
def _categorize_messages(self, conversation: ) -> :
categories = {
: [],
: [],
: [],
: []
}
msg conversation:
._is_task_related(msg):
categories[].append(msg)
._is_decision(msg):
categories[].append(msg)
._is_error(msg):
categories[].append(msg)
:
categories[].append(msg)
categories
() -> :
key_points = extract_key_points(message)
summary = summarize(key_points)
() -> :
(text.split()) *
class IncrementalSummarizer:
"""增量摘要器"""
def __init__(self, summary_interval: int = 10):
self.summary_interval = summary_interval
self.summaries = []
def add_messages(self, messages: list) -> str:
"""添加消息并生成摘要"""
# 每隔 N 条消息生成一次摘要
if len(messages) % self.summary_interval == 0:
summary = self._generate_summary(messages[-self.summary_interval:])
self.summaries.append(summary)
# 返回完整的摘要历史
return "\n\n".join(self.summaries)
def _generate_summary(self, messages: list) -> str:
"""生成消息摘要"""
# 提取关键信息
key_info = {
'tasks': self._extract_tasks(messages),
'decisions': self._extract_decisions(messages),
'errors': self._extract_errors(messages),
'outcomes': self._extract_outcomes(messages)
}
# 格式化摘要
summary_parts = []
key_info[]:
summary_parts.append()
key_info[]:
summary_parts.append()
key_info[]:
summary_parts.append()
key_info[]:
summary_parts.append()
.join(summary_parts)
class LazyContextLoader:
"""懒加载上下文"""
def __init__(self):
self.loaded_references = {}
self.reference_metadata = {}
def load_reference(
self,
ref_name: str,
force: bool = False
) -> str | None:
"""
按需加载参考文档
Args:
ref_name: 参考文档名称
force: 是否强制重新加载
"""
# 已加载且不强制
if ref_name in self.loaded_references and not force:
return self.loaded_references[ref_name]
# 检查元数据
metadata = self.reference_metadata.get(ref_name)
if not metadata:
return None
# 按需决策
if self._should_load(metadata):
content = self._load_from_disk(ref_name)
self.loaded_references[ref_name] = content
return content
return None
def _should_load(self, metadata: dict) -> bool:
"""判断是否应该加载"""
relevance = metadata.get(, )
token_usage = metadata.get(, )
relevance > token_usage <
class SmartCache:
"""智能缓存系统"""
def __init__(self, max_size: int = 100):
self.cache = {}
self.max_size = max_size
self.access_count = {}
def get(self, key: str) -> any:
"""获取缓存"""
if key in self.cache:
# 更新访问计数
self.access_count[key] = self.access_count.get(key, 0) + 1
return self.cache[key]
return None
def set(self, key: str, value: any, priority: int = 1):
"""设置缓存"""
# 缓存已满,清理低优先级项
if len(self.cache) >= self.max_size:
self._evict_low_priority()
self.cache[key] = value
self.access_count[key] = 0
def _evict_low_priority(self):
items = (.cache.items())
items.sort(key= x: .access_count.get(x[], ) * x[].get(, ))
items:
key_to_remove = items[][]
.cache[key_to_remove]
.access_count[key_to_remove]
cache = SmartCache()
code_structure = parse_code()
cache.(, code_structure, priority=)
cached = cache.get()
cached:
use_cached_structure(cached)
# ❌ 一次性处理所有信息
def process_large_file(filename):
content = read_file(filename) # 可能很大
result = analyze(content)
return result
# ✅ 分阶段处理
def process_large_file(filename):
# 第一阶段:获取结构
structure = get_file_structure(filename)
# 第二阶段:按需加载
for section in structure.sections:
content = load_section(filename, section)
result = analyze_section(content)
return aggregate_results(results)
# ❌ 一次性提供所有信息
def provide_context():
return """
这是项目的完整文档,包括架构、API、配置等...
(可能 10000+ tokens)
"""
# ✅ 渐进式披露
def provide_context():
return """
项目概述:这是一个 Web 应用
需要详细信息时,可查阅:
- [架构设计](docs/architecture.md)
- [API 文档](docs/api.md)
- [配置指南](docs/config.md)
(约 100 tokens)
"""