[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M777DKASWJJ9T3JBJAY0EDV3":3,"skill-same:01M777DKASWJJ9T3JBJAY0EDV3":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M777DKASWJJ9T3JBJAY0EDV3","claude-code-engine",null,"将 OpenClaw 升级为 Claude-Code 引擎架构 - 并发执行\u002F自我反思\u002F向量检索\u002F子代理系统\u002F上下文压缩","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fc\u002Fclaude-code-engine\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: claude-code-engine\ndescription: 将 OpenClaw 升级为 Claude-Code 引擎架构 - 并发执行\u002F自我反思\u002F向量检索\u002F子代理系统\u002F上下文压缩\n---\n\n# Claude-Code 引擎赋能 OpenClaw\n\n> 整合 Claude-Code 核心架构 | 并发执行 | 自我反思 | 向量检索 | 子代理系统\n\n---\n\n## 一、核心定位\n\n本技能帮助将 OpenClaw 升级为类 Claude-Code 的高效代理架构，核心目标：\n\n| 目标 | 说明 |\n|------|------|\n| **并发执行** | 子代理并行处理，无需等待前序任务 |\n| **自我反思** | 每6小时无交互时自动反思教训\u002F经验\u002F错误 |\n| **向量检索** | 精准从记忆文件中找回历史内容 |\n| **上下文压缩** | 92%阈值自动压缩，保留核心信息 |\n| **长时自主** | 支持30-50小时连续运行 |\n\n---\n\n## 二、Claude-Code 核心架构\n\n### 2.1 N0 引擎核心循环\n\n```\n┌─────────────────────────────────────────────────────┐\n│              Claude-Code N0 循环架构                  │\n├─────────────────────────────────────────────────────┤\n│                                                      │\n│   while True:                                         │\n│     ┌─────────┐                                      │\n│     │ 获取输入 │ ← 用户请求 + 项目背景 + 系统状态      │\n│     └────┬────┘                                      │\n│          ↓                                           │\n│     ┌─────────┐                                      │\n│     │ 模型决策 │ → stop_reason + tool_calls          │\n│     └────┬────┘                                      │\n│          ↓                                           │\n│     ┌─────────┐                                      │\n│     │ 执行工具 │ → bash\u002Fread\u002Fwrite\u002Fedit\u002Fgrep\u002Fbrowser │\n│     └────┬────┘                                      │\n│          ↓                                           │\n│     ┌─────────┐                                      │\n│     │ 反馈循环 │ → 工具结果返回 → 再次进入模型         │\n│     └─────────┘                                      │\n│          ↓                                           │\n│   直到 stop_reason == endturn                        │\n│                                                      │\n└─────────────────────────────────────────────────────┘\n```\n\n### 2.2 七种内置工具\n\n| 工具 | 功能 | OpenClaw 等价 |\n|------|------|--------------|\n| `bash` | 执行命令行 | `exec` |\n| `read` | 读文件 | `read` |\n| `write` | 写文件 | `write` |\n| `edit` | 编辑文件 | `edit` |\n| `glob\u002Fgrep` | 搜索文件 | `exec find\u002Fgrep` |\n| `browser` | 访问网页 | `browser` |\n| `skill` | 加载领域知识 | `skills` |\n\n---\n\n## 三、OpenClaw 升级清单\n\n### 3.1 自我反思系统\n\n**目标**：每6小时无交互时自动反思\n\n```bash\n# 创建自我反思脚本\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fself-reflection.sh \u003C\u003C 'EOF'\n#!\u002Fbin\u002Fbash\n# OpenClaw 自我反思脚本\n# 每6小时无交互时自动执行\n\nREFLECTION_DIR=\"\u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002Freflections\"\nmkdir -p \"$REFLECTION_DIR\"\n\n反思内容包含：\n- 教训 (lessons)\n- 经验 (experiences)\n- 错误 (errors)\n- 成功 (successes)\n- 待优化点 (improvements)\n\ntimestamp=$(date +%Y%m%d_%H%M%S)\nlog_file=\"$REFLECTION_DIR\u002F${timestamp}.md\"\n\ncat > \"$log_file\" \u003C\u003C 'LOG'\n# 自我反思日志\n\n## 时间\n{TIMESTAMP}\n\n## 教训 (Lessons)\n-\n\n## 经验 (Experiences)\n-\n\n## 错误 (Errors)\n-\n\n## 成功 (Successes)\n-\n\n## 待优化 (Improvements)\n-\n\nLOG\n\necho \"反思已记录: $log_file\"\nEOF\nchmod +x \u002Froot\u002F.openclaw\u002Fscripts\u002Fself-reflection.sh\n\n# 添加到 crontab（每6小时）\n(crontab -l 2>\u002Fdev\u002Fnull; echo \"0 *\u002F6 * * * \u002Froot\u002F.openclaw\u002Fscripts\u002Fself-reflection.sh\") | crontab -\n```\n\n### 3.2 向量检索配置\n\n**目标**：从记忆文件中精准检索\n\n```bash\n# 安装向量检索依赖\npip install chromadb sentence-transformers\n\n# 创建向量检索脚本\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fvector-search.py \u003C\u003C 'EOF'\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nOpenClaw 向量检索系统\n基于 ChromaDB + Sentence-Transformers\n\"\"\"\n\nimport chromadb\nfrom sentence_transformers import SentenceTransformer\nfrom pathlib import Path\nimport os\n\nclass VectorMemory:\n    def __init__(self, persist_dir=\"\u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002Fvector_db\"):\n        self.client = chromadb.PersistentClient(path=persist_dir)\n        self.model = SentenceTransformer('all-MiniLM-L6-v2')\n        self.collection = self.client.get_or_create_collection(\"openclaw_memory\")\n    \n    def add_memory(self, text, metadata=None):\n        \"\"\"添加记忆到向量库\"\"\"\n        embedding = self.model.encode([text])\n        self.collection.add(\n            embeddings=embedding.tolist(),\n            documents=[text],\n            metadatas=[metadata or {\"source\": \"manual\"}]\n        )\n    \n    def search(self, query, n_results=5):\n        \"\"\"语义检索记忆\"\"\"\n        embedding = self.model.encode([query])\n        results = self.collection.query(\n            query_embeddings=embedding.tolist(),\n            n_results=n_results\n        )\n        return results\n    \n    def load_from_files(self, memory_dir=\"\u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\"):\n        \"\"\"从文件批量加载记忆\"\"\"\n        path = Path(memory_dir)\n        for md_file in path.rglob(\"*.md\"):\n            content = md_file.read_text()\n            self.add_memory(\n                content,\n                metadata={\"source\": str(md_file), \"type\": \"memory\"}\n            )\n\nif __name__ == \"__main__\":\n    vm = VectorMemory()\n    query = input(\"请输入检索内容: \")\n    results = vm.search(query)\n    print(\"检索结果:\")\n    for i, (doc, meta) in enumerate(zip(results['documents'][0], results['metadatas'][0])):\n        print(f\"\\n{i+1}. [{meta['source']}]\")\n        print(doc[:200] + \"...\" if len(doc) > 200 else doc)\nEOF\n```\n\n### 3.3 子代理并发系统\n\n```bash\n# 创建并发执行管理器\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fsubagent_executor.py \u003C\u003C 'EOF'\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nOpenClaw 子代理并发执行器\n支持多任务并行处理，无需等待前序完成\n\"\"\"\n\nimport asyncio\nimport concurrent.futures\nfrom typing import List, Callable, Any\nimport subprocess\nimport json\n\nclass SubAgentExecutor:\n    def __init__(self, max_workers=5):\n        self.max_workers = max_workers\n        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)\n    \n    def run_task(self, task: dict) -> dict:\n        \"\"\"执行单个子任务\"\"\"\n        task_type = task.get(\"type\")\n        command = task.get(\"command\")\n        \n        if task_type == \"bash\":\n            result = subprocess.run(\n                command, shell=True, \n                capture_output=True, text=True, timeout=task.get(\"timeout\", 300)\n            )\n            return {\n                \"task_id\": task.get(\"id\"),\n                \"status\": \"success\" if result.returncode == 0 else \"failed\",\n                \"output\": result.stdout,\n                \"error\": result.stderr\n            }\n        elif task_type == \"skill\":\n            # 调用 OpenClaw skill\n            result = subprocess.run(\n                f\"npx clawhub@latest run {command}\",\n                shell=True, capture_output=True, text=True\n            )\n            return {\n                \"task_id\": task.get(\"id\"),\n                \"status\": \"success\" if result.returncode == 0 else \"failed\",\n                \"output\": result.stdout\n            }\n        return {\"task_id\": task.get(\"id\"), \"status\": \"unknown_type\"}\n    \n    def run_parallel(self, tasks: List[dict]) -> List[dict]:\n        \"\"\"并发执行多个任务\"\"\"\n        futures = [self.executor.submit(self.run_task, task) for task in tasks]\n        results = [f.result() for f in concurrent.futures.as_completed(futures)]\n        return results\n\nif __name__ == \"__main__\":\n    executor = SubAgentExecutor(max_workers=5)\n    \n    # 示例：并行执行多个任务\n    tasks = [\n        {\"id\": \"task1\", \"type\": \"bash\", \"command\": \"ls -la \u002Froot\"},\n        {\"id\": \"task2\", \"type\": \"skill\", \"command\": \"mckinsey-frameworks\"},\n        {\"id\": \"task3\", \"type\": \"bash\", \"command\": \"git status\"},\n    ]\n    \n    results = executor.run_parallel(tasks)\n    print(json.dumps(results, indent=2))\nEOF\n```\n\n---\n\n## 四、上下文压缩系统\n\n### 4.1 92% 阈值压缩\n\n```python\n# 创建上下文管理器\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fcontext_compressor.py \u003C\u003C 'EOF'\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nOpenClaw 上下文压缩管理器\n当上下文达到 92% 时自动压缩\n\"\"\"\n\nimport os\nimport json\nfrom pathlib import Path\n\nclass ContextCompressor:\n    def __init__(self, max_tokens=200000, compression_threshold=0.92):\n        self.max_tokens = max_tokens\n        self.threshold = compression_threshold\n        self.current_usage = 0\n    \n    def check_and_compress(self, messages: list) -> list:\n        \"\"\"检查上下文使用率并在需要时压缩\"\"\"\n        total_tokens = sum(len(str(m)) \u002F\u002F 4 for m in messages)\n        self.current_usage = total_tokens \u002F self.max_tokens\n        \n        if self.current_usage >= self.threshold:\n            return self.compress(messages)\n        return messages\n    \n    def compress(self, messages: list) -> list:\n        \"\"\"压缩策略：保留关键决策和结果\"\"\"\n        compressed = []\n        for msg in messages:\n            content = str(msg.get(\"content\", \"\"))\n            # 保留关键信息：决策、结论、结果\n            if any(kw in content for kw in [\"✅\", \"❌\", \"决策\", \"结论\", \"result\", \"error\"]):\n                compressed.append(msg)\n            # 保留工具调用结果\n            elif msg.get(\"role\") == \"tool\":\n                compressed.append(msg)\n        return compressed\n    \n    def extract_summary(self, messages: list) -> str:\n        \"\"\"提取中间总结\"\"\"\n        summary = []\n        for msg in messages:\n            content = str(msg.get(\"content\", \"\"))\n            if any(kw in content for kw in [\"架构选择\", \"测试结论\", \"决策\", \"selected\"]):\n                summary.append(content[:200])\n        return \"\\n\".join(summary)\nEOF\n```\n\n### 4.2 记忆文件化系统\n\n```markdown\n# 四层记忆文件结构（参考 Claude-Code）\n\nroot: \u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002F\n├── daily\u002F                 # 每日日志\n│   ├── 2026-04-19.md\n│   └── 2026-04-25.md\n├── reflections\u002F           # 自我反思\n│   └── ${timestamp}.md\n├── lessons\u002F             # 经验总结\n│   └── lessons.md\n└── memory.md            # 索引文件（由 AGENTS.md 管理）\n```\n\n---\n\n## 五、并发执行配置\n\n### 5.1 子代理配置\n\n```json\n\u002F\u002F \u002Froot\u002F.openclaw\u002Fconfig\u002Fsubagents.json\n{\n  \"enabled\": true,\n  \"max_concurrent\": 5,\n  \"default_timeout\": 300,\n  \"strategies\": {\n    \"code_review\": {\n      \"type\": \"skill\",\n      \"skill\": \"code-review\"\n    },\n    \"research\": {\n      \"type\": \"skill\", \n      \"skill\": \"browser-use\"\n    },\n    \"documentation\": {\n      \"type\": \"skill\",\n      \"skill\": \"docs-generator\"\n    }\n  }\n}\n```\n\n### 5.2 并发执行示例\n\n```python\n# 并发执行示例\ntasks = [\n    {\"id\": \"1\", \"type\": \"code_review\", \"target\": \"src\u002Fmain.py\"},\n    {\"id\": \"2\", \"type\": \"research\", \"query\": \"latest AI trends\"},\n    {\"id\": \"3\", \"type\": \"documentation\", \"target\": \"API docs\"},\n]\n\nexecutor = SubAgentExecutor(max_workers=3)\nresults = executor.run_parallel(tasks)\n```\n\n---\n\n## 六、长时自主运行配置\n\n### 6.1 健康检查脚本\n\n```bash\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fhealth_check.sh \u003C\u003C 'EOF'\n#!\u002Fbin\u002Fbash\n# OpenClaw 长时运行健康检查\n\nLOG_FILE=\"\u002Froot\u002F.openclaw\u002Flogs\u002Fagent_health.log\"\nMAX_IDLE_HOURS=6\n\ncheck_idle() {\n    last_activity=$(stat -c %Y \u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002Fmemory.md 2>\u002Fdev\u002Fnull || echo 0)\n    now=$(date +%s)\n    idle_hours=$(( (now - last_activity) \u002F 3600 ))\n    \n    if [ $idle_hours -ge $MAX_IDLE_HOURS ]; then\n        echo \"[$(date)] 检测到空闲${idle_hours}小时，执行自我反思...\" >> $LOG_FILE\n        \u002Froot\u002F.openclaw\u002Fscripts\u002Fself-reflection.sh\n    fi\n}\n\ncheck_memory() {\n    mem_usage=$(free | grep Mem | awk '{printf \"%.1f\", $3\u002F$2 * 100}')\n    if (( $(echo \"$mem_usage > 90\" | bc -l) )); then\n        echo \"[$(date)] 内存使用率${mem_usage}%，触发压缩...\" >> $LOG_FILE\n        python3 \u002Froot\u002F.openclaw\u002Fscripts\u002Fcontext_compressor.py --compress\n    fi\n}\n\ncheck_idle\ncheck_memory\nEOF\nchmod +x \u002Froot\u002F.openclaw\u002Fscripts\u002Fhealth_check.sh\n\n# 添加到 crontab（每30分钟检查）\n(crontab -l 2>\u002Fdev\u002Fnull; echo \"*\u002F30 * * * * \u002Froot\u002F.openclaw\u002Fscripts\u002Fhealth_check.sh\") | crontab -\n```\n\n---\n\n## 七、Claude-Code 工作流集成\n\n### 7.1 N0 循环实现\n\n```python\n# claude_code_loop.py\nimport asyncio\nfrom typing import Optional\n\nclass N0Engine:\n    \"\"\"Claude-Code N0 循环引擎\"\"\"\n    \n    def __init__(self):\n        self.running = False\n        self.context = []\n    \n    async def step(self, user_input: str) -> str:\n        \"\"\"单步执行\"\"\"\n        # 1. 获取输入\n        self.context.append({\"role\": \"user\", \"content\": user_input})\n        \n        # 2. 模型决策（调用 LLM）\n        response = await self.llm.chat(messages=self.context)\n        \n        # 3. 执行工具\n        if response.tool_calls:\n            for tool in response.tool_calls:\n                result = await self.execute_tool(tool)\n                self.context.append({\"role\": \"tool\", \"content\": result})\n        \n        # 4. 检查停止条件\n        if response.stop_reason == \"endturn\":\n            self.running = False\n        \n        return response.content\n    \n    async def run(self, user_input: str):\n        \"\"\"主循环\"\"\"\n        self.running = True\n        while self.running:\n            result = await self.step(user_input)\n            print(result)\n            user_input = input(\"> \")\n    \n    async def execute_tool(self, tool_call: dict) -> str:\n        \"\"\"执行工具调用\"\"\"\n        tool_name = tool_call[\"name\"]\n        args = tool_call[\"arguments\"]\n        \n        if tool_name == \"bash\":\n            return await self.run_bash(args[\"command\"])\n        elif tool_name == \"read\":\n            return self.read_file(args[\"path\"])\n        # ... 其他工具\n        \n        return \"tool executed\"\n```\n\n### 7.2 与 OpenClaw 集成\n\n```python\n# openclaw_n0_bridge.py\nfrom openclaw import OpenClaw\n\nclass OpenClawN0Bridge:\n    \"\"\"将 N0 引擎桥接到 OpenClaw\"\"\"\n    \n    def __init__(self, openclaw: OpenClaw):\n        self.oc = openclaw\n        self.context = []\n    \n    async def process(self, user_input: str) -> str:\n        \"\"\"处理用户输入\"\"\"\n        # 添加到上下文\n        self.context.append({\"role\": \"user\", \"content\": user_input})\n        \n        # 检查压缩\n        compressor = ContextCompressor()\n        self.context = compressor.check_and_compress(self.context)\n        \n        # 调用 OpenClaw 处理\n        response = await self.oc.chat(messages=self.context)\n        \n        # 添加响应到上下文\n        self.context.append({\"role\": \"assistant\", \"content\": response})\n        \n        return response\n```\n\n---\n\n## 八、使用方式\n\n### 触发场景\n\n```\n用户说「启动 Claude-Code 模式」→ 激活 N0 引擎\n用户说「并发执行这些任务」→ 触发子代理系统\n用户说「搜索记忆」→ 启动向量检索\n用户说「自我反思」→ 执行反思脚本\n用户说「检查上下文」→ 触发压缩检查\n```\n\n### 配置检查清单\n\n```bash\n# 1. 确认 crontab 已配置\ncrontab -l | grep self-reflection\n\n# 2. 确认向量数据库已初始化\nls \u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002Fvector_db\u002F\n\n# 3. 确认并发执行器可运行\npython3 \u002Froot\u002F.openclaw\u002Fscripts\u002Fsubagent_executor.py --test\n\n# 4. 确认健康检查已启用\nps aux | grep health_check\n```\n\n---\n\n## 九、技术对比\n\n| 功能 | Claude-Code | OpenClaw (当前) | OpenClaw (目标) |\n|------|------------|----------------|----------------|\n| N0 循环 | ✅ while True | ⚠️ 单次交互 | ✅ 实现 |\n| 并发执行 | ✅ 子代理并行 | ❌ 顺序执行 | ✅ 实现 |\n| 上下文压缩 | ✅ 92% 阈值 | ❌ 无 | ✅ 实现 |\n| 自我反思 | ✅ 日志记录 | ⚠️ 手动 | ✅ 自动 |\n| 向量检索 | ⚠️ 外部工具 | ❌ 无 | ✅ 实现 |\n| 7 种内置工具 | ✅ 完整 | ⚠️ 部分 | ✅ 补充 |\n\n---\n\n## 十、已知限制\n\n```\n⚠️ 限制说明：\n- N0 引擎需要持续运行进程，当前 OpenClaw 为请求-响应模式\n- 并发执行需要多进程\u002F多线程支持，单核环境受限\n- 向量检索需要额外存储（约 500MB 用于向量库）\n- 自我反思依赖 LLM 调用，需 API Key\n- 部分功能需要 root 权限（crontab）\n```\n\n---\n\n## 十一、相关技能\n\n| 技能 | 关系 |\n|------|------|\n| `thinking-knowledge-system` | 认知闭环构建 |\n| `ai-research-tools` | 子代理研究系统 |\n| `browser-use` | 浏览器工具支持 |\n\n---\n\n*本技能帮助将 OpenClaw 升级为类 Claude-Code 的高效代理架构*\n","# Claude-Code 引擎赋能 OpenClaw\n\n> 整合 Claude-Code 核心架构 | 并发执行 | 自我反思 | 向量检索 | 子代理系统\n\n---\n\n## 一、核心定位\n\n本技能帮助将 OpenClaw 升级为类 Claude-Code 的高效代理架构，核心目标：\n\n| 目标 | 说明 |\n|------|------|\n| **并发执行** | 子代理并行处理，无需等待前序任务 |\n| **自我反思** | 每6小时无交互时自动反思教训\u002F经验\u002F错误 |\n| **向量检索** | 精准从记忆文件中找回历史内容 |\n| **上下文压缩** | 92%阈值自动压缩，保留核心信息 |\n| **长时自主** | 支持30-50小时连续运行 |\n\n---\n\n## 二、Claude-Code 核心架构\n\n### 2.1 N0 引擎核心循环\n\n```\n┌─────────────────────────────────────────────────────┐\n│              Claude-Code N0 循环架构                  │\n├─────────────────────────────────────────────────────┤\n│                                                      │\n│   while True:                                         │\n│     ┌─────────┐                                      │\n│     │ 获取输入 │ ← 用户请求 + 项目背景 + 系统状态      │\n│     └────┬────┘                                      │\n│          ↓                                           │\n│     ┌─────────┐                                      │\n│     │ 模型决策 │ → stop_reason + tool_calls          │\n│     └────┬────┘                                      │\n│          ↓                                           │\n│     ┌─────────┐                                      │\n│     │ 执行工具 │ → bash\u002Fread\u002Fwrite\u002Fedit\u002Fgrep\u002Fbrowser │\n│     └────┬────┘                                      │\n│          ↓                                           │\n│     ┌─────────┐                                      │\n│     │ 反馈循环 │ → 工具结果返回 → 再次进入模型         │\n│     └─────────┘                                      │\n│          ↓                                           │\n│   直到 stop_reason == endturn                        │\n│                                                      │\n└─────────────────────────────────────────────────────┘\n```\n\n### 2.2 七种内置工具\n\n| 工具 | 功能 | OpenClaw 等价 |\n|------|------|--------------|\n| `bash` | 执行命令行 | `exec` |\n| `read` | 读文件 | `read` |\n| `write` | 写文件 | `write` |\n| `edit` | 编辑文件 | `edit` |\n| `glob\u002Fgrep` | 搜索文件 | `exec find\u002Fgrep` |\n| `browser` | 访问网页 | `browser` |\n| `skill` | 加载领域知识 | `skills` |\n\n---\n\n## 三、OpenClaw 升级清单\n\n### 3.1 自我反思系统\n\n**目标**：每6小时无交互时自动反思\n\n```bash\n# 创建自我反思脚本\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fself-reflection.sh \u003C\u003C 'EOF'\n#!\u002Fbin\u002Fbash\n# OpenClaw 自我反思脚本\n# 每6小时无交互时自动执行\n\nREFLECTION_DIR=\"\u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002Freflections\"\nmkdir -p \"$REFLECTION_DIR\"\n\n反思内容包含：\n- 教训 (lessons)\n- 经验 (experiences)\n- 错误 (errors)\n- 成功 (successes)\n- 待优化点 (improvements)\n\ntimestamp=$(date +%Y%m%d_%H%M%S)\nlog_file=\"$REFLECTION_DIR\u002F${timestamp}.md\"\n\ncat > \"$log_file\" \u003C\u003C 'LOG'\n# 自我反思日志\n\n## 时间\n{TIMESTAMP}\n\n## 教训 (Lessons)\n-\n\n## 经验 (Experiences)\n-\n\n## 错误 (Errors)\n-\n\n## 成功 (Successes)\n-\n\n## 待优化 (Improvements)\n-\n\nLOG\n\necho \"反思已记录: $log_file\"\nEOF\nchmod +x \u002Froot\u002F.openclaw\u002Fscripts\u002Fself-reflection.sh\n\n# 添加到 crontab（每6小时）\n(crontab -l 2>\u002Fdev\u002Fnull; echo \"0 *\u002F6 * * * \u002Froot\u002F.openclaw\u002Fscripts\u002Fself-reflection.sh\") | crontab -\n```\n\n### 3.2 向量检索配置\n\n**目标**：从记忆文件中精准检索\n\n```bash\n# 安装向量检索依赖\npip install chromadb sentence-transformers\n\n# 创建向量检索脚本\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fvector-search.py \u003C\u003C 'EOF'\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nOpenClaw 向量检索系统\n基于 ChromaDB + Sentence-Transformers\n\"\"\"\n\nimport chromadb\nfrom sentence_transformers import SentenceTransformer\nfrom pathlib import Path\nimport os\n\nclass VectorMemory:\n    def __init__(self, persist_dir=\"\u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002Fvector_db\"):\n        self.client = chromadb.PersistentClient(path=persist_dir)\n        self.model = SentenceTransformer('all-MiniLM-L6-v2')\n        self.collection = self.client.get_or_create_collection(\"openclaw_memory\")\n    \n    def add_memory(self, text, metadata=None):\n        \"\"\"添加记忆到向量库\"\"\"\n        embedding = self.model.encode([text])\n        self.collection.add(\n            embeddings=embedding.tolist(),\n            documents=[text],\n            metadatas=[metadata or {\"source\": \"manual\"}]\n        )\n    \n    def search(self, query, n_results=5):\n        \"\"\"语义检索记忆\"\"\"\n        embedding = self.model.encode([query])\n        results = self.collection.query(\n            query_embeddings=embedding.tolist(),\n            n_results=n_results\n        )\n        return results\n    \n    def load_from_files(self, memory_dir=\"\u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\"):\n        \"\"\"从文件批量加载记忆\"\"\"\n        path = Path(memory_dir)\n        for md_file in path.rglob(\"*.md\"):\n            content = md_file.read_text()\n            self.add_memory(\n                content,\n                metadata={\"source\": str(md_file), \"type\": \"memory\"}\n            )\n\nif __name__ == \"__main__\":\n    vm = VectorMemory()\n    query = input(\"请输入检索内容: \")\n    results = vm.search(query)\n    print(\"检索结果:\")\n    for i, (doc, meta) in enumerate(zip(results['documents'][0], results['metadatas'][0])):\n        print(f\"\\n{i+1}. [{meta['source']}]\")\n        print(doc[:200] + \"...\" if len(doc) > 200 else doc)\nEOF\n```\n\n### 3.3 子代理并发系统\n\n```bash\n# 创建并发执行管理器\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fsubagent_executor.py \u003C\u003C 'EOF'\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nOpenClaw 子代理并发执行器\n支持多任务并行处理，无需等待前序完成\n\"\"\"\n\nimport asyncio\nimport concurrent.futures\nfrom typing import List, Callable, Any\nimport subprocess\nimport json\n\nclass SubAgentExecutor:\n    def __init__(self, max_workers=5):\n        self.max_workers = max_workers\n        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)\n    \n    def run_task(self, task: dict) -> dict:\n        \"\"\"执行单个子任务\"\"\"\n        task_type = task.get(\"type\")\n        command = task.get(\"command\")\n        \n        if task_type == \"bash\":\n            result = subprocess.run(\n                command, shell=True, \n                capture_output=True, text=True, timeout=task.get(\"timeout\", 300)\n            )\n            return {\n                \"task_id\": task.get(\"id\"),\n                \"status\": \"success\" if result.returncode == 0 else \"failed\",\n                \"output\": result.stdout,\n                \"error\": result.stderr\n            }\n        elif task_type == \"skill\":\n            # 调用 OpenClaw skill\n            result = subprocess.run(\n                f\"npx clawhub@latest run {command}\",\n                shell=True, capture_output=True, text=True\n            )\n            return {\n                \"task_id\": task.get(\"id\"),\n                \"status\": \"success\" if result.returncode == 0 else \"failed\",\n                \"output\": result.stdout\n            }\n        return {\"task_id\": task.get(\"id\"), \"status\": \"unknown_type\"}\n    \n    def run_parallel(self, tasks: List[dict]) -> List[dict]:\n        \"\"\"并发执行多个任务\"\"\"\n        futures = [self.executor.submit(self.run_task, task) for task in tasks]\n        results = [f.result() for f in concurrent.futures.as_completed(futures)]\n        return results\n\nif __name__ == \"__main__\":\n    executor = SubAgentExecutor(max_workers=5)\n    \n    # 示例：并行执行多个任务\n    tasks = [\n        {\"id\": \"task1\", \"type\": \"bash\", \"command\": \"ls -la \u002Froot\"},\n        {\"id\": \"task2\", \"type\": \"skill\", \"command\": \"mckinsey-frameworks\"},\n        {\"id\": \"task3\", \"type\": \"bash\", \"command\": \"git status\"},\n    ]\n    \n    results = executor.run_parallel(tasks)\n    print(json.dumps(results, indent=2))\nEOF\n```\n\n---\n\n## 四、上下文压缩系统\n\n### 4.1 92% 阈值压缩\n\n```python\n# 创建上下文管理器\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fcontext_compressor.py \u003C\u003C 'EOF'\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nOpenClaw 上下文压缩管理器\n当上下文达到 92% 时自动压缩\n\"\"\"\n\nimport os\nimport json\nfrom pathlib import Path\n\nclass ContextCompressor:\n    def __init__(self, max_tokens=200000, compression_threshold=0.92):\n        self.max_tokens = max_tokens\n        self.threshold = compression_threshold\n        self.current_usage = 0\n    \n    def check_and_compress(self, messages: list) -> list:\n        \"\"\"检查上下文使用率并在需要时压缩\"\"\"\n        total_tokens = sum(len(str(m)) \u002F\u002F 4 for m in messages)\n        self.current_usage = total_tokens \u002F self.max_tokens\n        \n        if self.current_usage >= self.threshold:\n            return self.compress(messages)\n        return messages\n    \n    def compress(self, messages: list) -> list:\n        \"\"\"压缩策略：保留关键决策和结果\"\"\"\n        compressed = []\n        for msg in messages:\n            content = str(msg.get(\"content\", \"\"))\n            # 保留关键信息：决策、结论、结果\n            if any(kw in content for kw in [\"✅\", \"❌\", \"决策\", \"结论\", \"result\", \"error\"]):\n                compressed.append(msg)\n            # 保留工具调用结果\n            elif msg.get(\"role\") == \"tool\":\n                compressed.append(msg)\n        return compressed\n    \n    def extract_summary(self, messages: list) -> str:\n        \"\"\"提取中间总结\"\"\"\n        summary = []\n        for msg in messages:\n            content = str(msg.get(\"content\", \"\"))\n            if any(kw in content for kw in [\"架构选择\", \"测试结论\", \"决策\", \"selected\"]):\n                summary.append(content[:200])\n        return \"\\n\".join(summary)\nEOF\n```\n\n### 4.2 记忆文件化系统\n\n```markdown\n# 四层记忆文件结构（参考 Claude-Code）\n\nroot: \u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002F\n├── daily\u002F                 # 每日日志\n│   ├── 2026-04-19.md\n│   └── 2026-04-25.md\n├── reflections\u002F           # 自我反思\n│   └── ${timestamp}.md\n├── lessons\u002F             # 经验总结\n│   └── lessons.md\n└── memory.md            # 索引文件（由 AGENTS.md 管理）\n```\n\n---\n\n## 五、并发执行配置\n\n### 5.1 子代理配置\n\n```json\n\u002F\u002F \u002Froot\u002F.openclaw\u002Fconfig\u002Fsubagents.json\n{\n  \"enabled\": true,\n  \"max_concurrent\": 5,\n  \"default_timeout\": 300,\n  \"strategies\": {\n    \"code_review\": {\n      \"type\": \"skill\",\n      \"skill\": \"code-review\"\n    },\n    \"research\": {\n      \"type\": \"skill\", \n      \"skill\": \"browser-use\"\n    },\n    \"documentation\": {\n      \"type\": \"skill\",\n      \"skill\": \"docs-generator\"\n    }\n  }\n}\n```\n\n### 5.2 并发执行示例\n\n```python\n# 并发执行示例\ntasks = [\n    {\"id\": \"1\", \"type\": \"code_review\", \"target\": \"src\u002Fmain.py\"},\n    {\"id\": \"2\", \"type\": \"research\", \"query\": \"latest AI trends\"},\n    {\"id\": \"3\", \"type\": \"documentation\", \"target\": \"API docs\"},\n]\n\nexecutor = SubAgentExecutor(max_workers=3)\nresults = executor.run_parallel(tasks)\n```\n\n---\n\n## 六、长时自主运行配置\n\n### 6.1 健康检查脚本\n\n```bash\ncat > \u002Froot\u002F.openclaw\u002Fscripts\u002Fhealth_check.sh \u003C\u003C 'EOF'\n#!\u002Fbin\u002Fbash\n# OpenClaw 长时运行健康检查\n\nLOG_FILE=\"\u002Froot\u002F.openclaw\u002Flogs\u002Fagent_health.log\"\nMAX_IDLE_HOURS=6\n\ncheck_idle() {\n    last_activity=$(stat -c %Y \u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002Fmemory.md 2>\u002Fdev\u002Fnull || echo 0)\n    now=$(date +%s)\n    idle_hours=$(( (now - last_activity) \u002F 3600 ))\n    \n    if [ $idle_hours -ge $MAX_IDLE_HOURS ]; then\n        echo \"[$(date)] 检测到空闲${idle_hours}小时，执行自我反思...\" >> $LOG_FILE\n        \u002Froot\u002F.openclaw\u002Fscripts\u002Fself-reflection.sh\n    fi\n}\n\ncheck_memory() {\n    mem_usage=$(free | grep Mem | awk '{printf \"%.1f\", $3\u002F$2 * 100}')\n    if (( $(echo \"$mem_usage > 90\" | bc -l) )); then\n        echo \"[$(date)] 内存使用率${mem_usage}%，触发压缩...\" >> $LOG_FILE\n        python3 \u002Froot\u002F.openclaw\u002Fscripts\u002Fcontext_compressor.py --compress\n    fi\n}\n\ncheck_idle\ncheck_memory\nEOF\nchmod +x \u002Froot\u002F.openclaw\u002Fscripts\u002Fhealth_check.sh\n\n# 添加到 crontab（每30分钟检查）\n(crontab -l 2>\u002Fdev\u002Fnull; echo \"*\u002F30 * * * * \u002Froot\u002F.openclaw\u002Fscripts\u002Fhealth_check.sh\") | crontab -\n```\n\n---\n\n## 七、Claude-Code 工作流集成\n\n### 7.1 N0 循环实现\n\n```python\n# claude_code_loop.py\nimport asyncio\nfrom typing import Optional\n\nclass N0Engine:\n    \"\"\"Claude-Code N0 循环引擎\"\"\"\n    \n    def __init__(self):\n        self.running = False\n        self.context = []\n    \n    async def step(self, user_input: str) -> str:\n        \"\"\"单步执行\"\"\"\n        # 1. 获取输入\n        self.context.append({\"role\": \"user\", \"content\": user_input})\n        \n        # 2. 模型决策（调用 LLM）\n        response = await self.llm.chat(messages=self.context)\n        \n        # 3. 执行工具\n        if response.tool_calls:\n            for tool in response.tool_calls:\n                result = await self.execute_tool(tool)\n                self.context.append({\"role\": \"tool\", \"content\": result})\n        \n        # 4. 检查停止条件\n        if response.stop_reason == \"endturn\":\n            self.running = False\n        \n        return response.content\n    \n    async def run(self, user_input: str):\n        \"\"\"主循环\"\"\"\n        self.running = True\n        while self.running:\n            result = await self.step(user_input)\n            print(result)\n            user_input = input(\"> \")\n    \n    async def execute_tool(self, tool_call: dict) -> str:\n        \"\"\"执行工具调用\"\"\"\n        tool_name = tool_call[\"name\"]\n        args = tool_call[\"arguments\"]\n        \n        if tool_name == \"bash\":\n            return await self.run_bash(args[\"command\"])\n        elif tool_name == \"read\":\n            return self.read_file(args[\"path\"])\n        # ... 其他工具\n        \n        return \"tool executed\"\n```\n\n### 7.2 与 OpenClaw 集成\n\n```python\n# openclaw_n0_bridge.py\nfrom openclaw import OpenClaw\n\nclass OpenClawN0Bridge:\n    \"\"\"将 N0 引擎桥接到 OpenClaw\"\"\"\n    \n    def __init__(self, openclaw: OpenClaw):\n        self.oc = openclaw\n        self.context = []\n    \n    async def process(self, user_input: str) -> str:\n        \"\"\"处理用户输入\"\"\"\n        # 添加到上下文\n        self.context.append({\"role\": \"user\", \"content\": user_input})\n        \n        # 检查压缩\n        compressor = ContextCompressor()\n        self.context = compressor.check_and_compress(self.context)\n        \n        # 调用 OpenClaw 处理\n        response = await self.oc.chat(messages=self.context)\n        \n        # 添加响应到上下文\n        self.context.append({\"role\": \"assistant\", \"content\": response})\n        \n        return response\n```\n\n---\n\n## 八、使用方式\n\n### 触发场景\n\n```\n用户说「启动 Claude-Code 模式」→ 激活 N0 引擎\n用户说「并发执行这些任务」→ 触发子代理系统\n用户说「搜索记忆」→ 启动向量检索\n用户说「自我反思」→ 执行反思脚本\n用户说「检查上下文」→ 触发压缩检查\n```\n\n### 配置检查清单\n\n```bash\n# 1. 确认 crontab 已配置\ncrontab -l | grep self-reflection\n\n# 2. 确认向量数据库已初始化\nls \u002Froot\u002F.openclaw\u002Fworkspace\u002Fmemory\u002Fvector_db\u002F\n\n# 3. 确认并发执行器可运行\npython3 \u002Froot\u002F.openclaw\u002Fscripts\u002Fsubagent_executor.py --test\n\n# 4. 确认健康检查已启用\nps aux | grep health_check\n```\n\n---\n\n## 九、技术对比\n\n| 功能 | Claude-Code | OpenClaw (当前) | OpenClaw (目标) |\n|------|------------|----------------|----------------|\n| N0 循环 | ✅ while True | ⚠️ 单次交互 | ✅ 实现 |\n| 并发执行 | ✅ 子代理并行 | ❌ 顺序执行 | ✅ 实现 |\n| 上下文压缩 | ✅ 92% 阈值 | ❌ 无 | ✅ 实现 |\n| 自我反思 | ✅ 日志记录 | ⚠️ 手动 | ✅ 自动 |\n| 向量检索 | ⚠️ 外部工具 | ❌ 无 | ✅ 实现 |\n| 7 种内置工具 | ✅ 完整 | ⚠️ 部分 | ✅ 补充 |\n\n---\n\n## 十、已知限制\n\n```\n⚠️ 限制说明：\n- N0 引擎需要持续运行进程，当前 OpenClaw 为请求-响应模式\n- 并发执行需要多进程\u002F多线程支持，单核环境受限\n- 向量检索需要额外存储（约 500MB 用于向量库）\n- 自我反思依赖 LLM 调用，需 API Key\n- 部分功能需要 root 权限（crontab）\n```\n\n---\n\n## 十一、相关技能\n\n| 技能 | 关系 |\n|------|------|\n| `thinking-knowledge-system` | 认知闭环构建 |\n| `ai-research-tools` | 子代理研究系统 |\n| `browser-use` | 浏览器工具支持 |\n\n---\n\n*本技能帮助将 OpenClaw 升级为类 Claude-Code 的高效代理架构*\n",{"name":5,"description":7},"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fc\u002Fclaude-code-engine",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill claude-code-engine",{"tool":39,"command":40},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill claude-code-engine",{"tool":42,"command":43},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill claude-code-engine","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fc\u002Fclaude-code-engine\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]