OPC Agent Orchestration (Fozu)
One-Person Company (OPC) orchestration skill — turns OpenClaw into a CEO that directs a team of specialized sub-agents to collaboratively complete complex enterprise tasks. Implements role definition, task decomposition, Heartbeat protocol, cost tracking, and full multi-agent coordination via OpenClaw's native sessions_spawn/sessions_send mechanism.
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
🏢 OPC — One-Person Company
Multi-Agent Orchestration Skill — Turn OpenClaw into the CEO of a one-person company.
多 Agent 编排技能 — 让 OpenClaw 成为一人公司的 CEO。
English
What is OPC?
OPC (One-Person Company) is an OpenClaw skill that turns complex tasks into multi-agent collaboration. You give the goal, the CEO (OpenClaw) breaks it down, hires the right agents, monitors progress, and delivers results.
You (Owner) → OpenClaw CEO → Sub-agents (Specialists)
Key Features
- Phase 0 Context Intake — CEO reads your background, proposes a plan, waits for confirmation before executing
- Built-in Persona Library — Inject top expert mindsets (Kotler, Fowler, Jeff Dean...) into each agent role
- LZW Advisor Persona — Author's own methodology framework, ready to inject into any agent role
- Project State Persistence — Survives context compaction; full lifecycle state in
state.json - Checkpoint & Resume — Failed agents resume from last checkpoint, not from scratch
- Auto Root Cause Analysis — L1-L4 fault classification (platform / orchestration / skill / external)
- Aware Triggers — Declarative event-driven scheduling (cron / once / interval / on_message)
- Tool Discovery v2 — domain × capability tag system, precise skill recommendations
- User Model Evolution — CEO writes back learnings after each project; gets smarter over time
Quick Start
# Install
cd ~/.openclaw/skills
unzip agent-orchestration-v5.0.zip
# Trigger OPC by telling OpenClaw:
# "Help me build a complete [project]"
# "I need [multi-step task] done end-to-end"
Architecture
agent-orchestration-20260309-lzw/
├── SKILL.md ← Entry point (v5.0)
├── brain/ ← CEO decision layer
│ ├── core-flow.md ← 4-phase flow + Context Intake
│ ├── task-decomposition.md
│ ├── role-design.md
│ └── collaboration-patterns.md
├── engine/ ← Execution engine
│ ├── project_state.py ← Project lifecycle state
│ ├── trigger_engine.py ← Aware triggers
│ ├── tool_discovery.py ← Tool discovery (tag system v2)
│ └── diagnose_agent.py ← Auto root cause analysis
└── playbook/ ← Knowledge & templates
├── persona-priming.md ← Persona methodology + library index
├── personas/
│ └── lzw.md ← Built-in LZW Advisor Persona (v5.0)
├── templates/
└── scenarios/
Persona Priming
Two types of Personas, two design logics:
| Type | Example | How it works |
|---|---|---|
| Activation (public figures) | Kotler, Fowler, Jeff Dean | One-line reference activates LLM's pre-trained knowledge |
| Injection (real individuals) | LZW (personas/lzw.md) | Full methodology doc injected into agent context |
New paradigm: You can crystallize your own thinking framework into a Persona and inject it into your agent team.
Real-World Validation
| Case | Scale | Result |
|---|---|---|
| 315 Marketing Campaign (v1.0) | 3 agents serial | 67K tokens / $0.17 |
| 3 Venues Parallel Build (v1.4) | 4 agents parallel | All 3 venues delivered |
| KangaBase 0→1 (v2.0) | 8 agents, 4 phases | ~100 files / 8000 lines in 8h |
| Neurotech Deep Analysis (v3.1) | 4 researchers + integrator | 4500-word report / $0.10 |
Prerequisites
- OpenClaw installed and configured
- Python 3 (for engine scripts)
License
Apache License 2.0 — modifications must declare changes. See LICENSE.
中文
OPC 是什么?
OPC(One-Person Company,一人公司)是一个 OpenClaw Skill,把复杂任务转化为多 Agent 协作。你说目标,CEO(OpenClaw)负责拆活儿、招人、盯进度、交结果。
用户(老板)→ OpenClaw CEO → Sub-agents(专业员工)
核心能力
- Phase 0 Context Intake — CEO 理解背景,给出方案,等确认后才执行
- 内置 Persona 库 — 给角色注入 Kotler / Fowler / Jeff Dean 等顶级人才的方法论
- LZW 顾问 Persona — 作者本人的方法论框架,可直接注入任意 Agent 角色
- 项目状态持久化 — 抗 context compaction,全生命周期状态写入
state.json - 断点续传 — Agent 失败后从断点继续,不完全重跑
- 自动归因 — L1-L4 故障分层(平台/编排/Skill/外部)
- Aware 触发器 — 声明式事件驱动(cron / once / interval / on_message)
- 工具发现 v2 — domain × capability 双轴标签,精准推荐可用 Skill
- 用户模型自进化 — 每次项目结束 CEO 自动写回学习结果,越用越懂你
快速上手
# 安装
cd ~/.openclaw/skills
unzip agent-orchestration-v5.0.zip
# 触发 OPC,对 OpenClaw 说:
# "帮我做一个完整的 [项目]"
# "我需要 [多步骤任务] 全链路完成"
Persona Priming
OPC 的 Persona 分为两类,设计逻辑不同:
| 类型 | 代表 | 工作原理 |
|---|---|---|
| 激活型(公众人物) | Kotler、Fowler、Jeff Dean | 一行描述即可激活 LLM 预训练知识 |
| 注入型(真实个人) | LZW(personas/lzw.md) | 完整方法论文档注入 Agent context |
新范式:用户可以把自己的思维框架沉淀为 Persona,注入到自己的 Agent 团队中。
实战验证
| 案例 | 规模 | 结果 |
|---|---|---|
| 315 营销活动(v1.0) | 3 角色串行 | 67K tokens / $0.17 |
| 三会场并行搭建(v1.4) | 4 角色并行 | 3 个会场全部交付 |
| KangaBase 从零到开源(v2.0) | 8 Agent / 4 Phase | ~100文件/8000行,8小时 |
| 神经调控深度分析(v3.1) | 4 研究员 + 整合员 | 4500字报告 / $0.10 |
版本历史
| 版本 | 日期 | 核心变更 |
|---|---|---|
| v5.0 | 2026-03-16 | 内置 LZW 顾问 Persona + personas/ 目录 |
| v3.1 | 2026-03-14 | 用户模型自学习:Phase 0 读取 + Phase 4 写回 |
| v3.0 | 2026-03-14 | 三层架构重构 + Context Intake + 工具发现标签体系 v2 |
| v2.0 | 2026-03-12 | Aware 触发器 + 运行时工具自发现 |
| v1.4 | 2026-03-11 | 状态持久化 + 断点续传 + 自动归因 |
| v1.0 | 2026-03-09 | 首版:角色卡 + 任务分解 + 协作模式 |
见完整 CHANGELOG.md
前置条件
- 已安装并配置 OpenClaw
- Python 3(用于引擎脚本)
许可证
Apache License 2.0 — 修改文件须声明变更。详见 LICENSE。
Built with ❤️ by LZW · Powered by OpenClaw
// HOW IT'S BUILT
// FILES
44 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
SKILL.md11 KB7ec75135c3d8upstream ↗
--- name: agent-orchestration-20260309-lzw version: "5.3" description: > One-Person Company (OPC) 编排技能 — 复杂任务的多 Agent 协作指挥中枢。 【优先触发条件 — 满足任意一条即应调用 OPC】 ① 任务需要多个步骤且步骤之间有依赖关系(如 策划→搭建→发布) ② 任务预计超过 50K tokens 或 10 分钟 ③ 任务涉及多个领域(调研+创作+开发+发布 等两个以上领域并存) ④ 任务需要多个专业角色分工(研究员、工程师、设计师等) ⑤ 任务明确包含"并行执行""多路线""团队协作"等关键词 ⑥ 用户提到"全链路""从头到尾""完整流程""做一个完整的X" 核心能力:Context Intake(用户模型读取+背景摄入)、任务分解、多角色编排、状态持久化、断点续传、用户模型自更新。 触发词(任意匹配): OPC、一人公司、多agent、编排、全链路、复杂项目、帮我做完整的、 需要多个步骤、并行执行、团队协作、策划+搭建+发布、研究项目、内容流水线 --- # OPC — One-Person Company 编排技能 v5.3 > 用户是老板,OpenClaw 是 CEO,Sub-agents 是专业员工。 > 用户只说"我要做 X",CEO 负责拆活儿、招人、盯进度、**亲自验收**、交结果。 --- ## 30 秒上手 ``` 1. 触发 OPC → Phase 0: Context Intake(理解背景目标,给出方案,等确认) 2. 确认后 → Phase 1: init 项目 + 任务分解 3. spawn Sub-agents → Phase 2: 注入角色卡 + 注册状态 4. 监控执行 → Phase 3: 主动检查 + trigger-evaluate + 汇报进度 5. 交付汇总 → Phase 4: cost 报告 + close 项目 ``` --- ## Phase 0:Context Intake(最重要,不可跳过) OPC 被触发后,**第一步必须理解背景,给出方案,征询确认**。 ### 必须明确的四个维度 ``` 【背景】业务场景是什么?有什么前置条件?新建还是继续? 【目标】交付物是什么?怎么判断"完成"? 【约束】截止时间?token 预算?平台限制? 【范围】从哪里开始到哪里结束?什么不在本次范围? ``` ### 方案输出格式(等用户确认才开始) ```markdown ## 📋 OPC 项目方案 **背景理解**:{一句话概括} **目标**:{交付物 + 成功标准} **约束**:{时间/预算/限制} **推进方案**: - 角色配置:{N 个角色,名称 + 主要职责} - 协作模式:{串行/并行/混合} - 预估总预算:~{N}K tokens - 预计耗时:~{N} 分钟 **确认后开始执行,是否有需要调整的地方?** ``` ### 确认轮次 | 复杂度 | 判断标准 | 轮次 | |--------|---------|------| | 简单 | ≤2 角色,单流水线 | **1 轮**(Phase 0+1 合并)| | 中等 | 3-5 角色,有并行 | **1 轮**(Phase 0+1 合并)| | 复杂 | >5 角色,>200K 预算 | **2 轮**(理解→方案分开)| 详细决策逻辑 → brain/core-flow.md --- ## 核心执行命令速查 ```bash # Phase 1 — 项目初始化 python3 engine/project_state.py init "项目名" python3 engine/project_state.py update-phase <pid> phase_1_planning # Phase 2 — agent 注册 python3 engine/project_state.py agent-start <pid> <label> '{"role":"角色名"}' # Phase 3 — 监控 python3 engine/project_state.py agent-complete <pid> <label> '{"output":"..."}' <tokens> python3 engine/project_state.py agent-fail <pid> <label> '{"error":"原因"}' python3 engine/project_state.py trigger-evaluate <pid> # 每轮循环必须调用 # 断点续传 python3 engine/project_state.py checkpoint <pid> <label> '{"completedSteps":[...],"nextStep":"..."}' python3 engine/project_state.py checkpoint-get <pid> <label> # Phase 4 — 交付 python3 engine/project_state.py cost <pid> python3 engine/project_state.py close <pid> # 诊断恢复 python3 engine/project_state.py restore <pid> python3 engine/project_state.py diagnose <pid> # ⭐ v4.0 CEO 自主验收(agent 完成后、agent-complete 前执行) python3 engine/project_state.py verify <pid> <label> "npm test" # ⭐ v4.0 冻结项目扫描(Heartbeat 时调用) python3 engine/project_state.py wake-frozen # 工具发现(Phase 0 可选) python3 engine/tool_discovery.py report "任务描述" ``` --- ## 角色卡模板 ``` [OPC 角色卡] - 角色:{role_name} - Persona:以 {expert_name}({expert_title})的方法论工作 - 汇报给:OpenClaw CEO - 职责:{responsibilities} - 预算:{N}K tokens [Heartbeat 协议] 1. 确认角色和任务 2. 阅读上游产出(如有) 3. 执行工作 4. 完成后汇报:产出摘要 + 遇到的问题 5. 遇障碍:说明障碍 + 建议 + 是否需要 CEO 介入 [任务] {task_description} [产出要求] 格式:{format},保存到:{file_path} ``` Persona 库 → playbook/persona-priming.md 完整模板 → playbook/templates/agent-prompt.md --- ## 协作模式 | 模式 | 适用 | 示例 | |------|------|------| | 串行流水线 | 严格依赖顺序 | 策划→搭建→发布 | | 并行分工 | 独立子任务 | 文案∥设计∥数据→组装 | | 迭代反馈 | 需审核修改 | 搭建↔QA→发布 | | 分治汇总 | 大任务拆分 | 研究1∥研究2∥研究3→汇总 | 详细 → brain/collaboration-patterns.md --- ## 故障处理 ``` agent 失败 → 立即归因 python3 engine/project_state.py diagnose <pid> 归因:L1-Platform → sessions_history拉取/重试 L2-Orchestration → 修改角色卡重新spawn L3-BusinessSkill → 修复skill,断点续传 ``` 详细 → engine/troubleshooting.md --- ## 适用场景 ✅ 适用 OPC:多角色复杂项目 / 跨领域任务 / 全链路执行 / 研究+实现+发布 ❌ 不适用:简单单一任务(直接spawn)/ 定时重复(Cron)/ 日常监控(Heartbeat) --- ## 目录结构 ``` agent-orchestration-20260309-lzw/ ├── SKILL.md ← 入口(你在这里) ├── CHANGELOG.md ← 完整版本历程(v1.0 → v5.0) ├── brain/ ← CEO 决策层(怎么想) │ ├── core-flow.md ← 四阶段流程 + Context Intake + 冻结唤醒 │ ├── verification.md ← ⭐ v4.0 CEO 自主验收规则库 │ ├── task-decomposition.md │ ├── role-design.md │ ├── collaboration-patterns.md │ ├── heartbeat-protocol.md │ ├── proactive-reporting.md │ └── cost-tracking.md ├── engine/ ← 执行引擎层(怎么跑) │ ├── project_state.py ← 核心:项目状态管理(v4.0:+verify, +wake-frozen) │ ├── trigger_engine.py ← Aware 触发器 │ ├── tool_discovery.py ← 工具发现(标签体系 v2) │ ├── diagnose_agent.py ← 自动归因 │ └── README.md ← 命令速查 ├── playbook/ ← 知识与模板层(参考素材) │ ├── persona-priming.md ← Persona 方法论 + 预置库索引 │ ├── personas/ │ │ └── lzw.md ← 内置 LZW 顾问 Persona(v3.2) │ ├── philosophy.md │ ├── templates/ │ │ └── opc-user-model.md ← 用户模型模板(v3.1) │ └── scenarios/ ← 实战案例 └── archive/ ← 旧版归档 用户模型实例(workspace,自动维护): ~/.openclaw/workspace/opc-user-model.md ``` --- ## 触发分级矩阵(v5.0) > CEO 收到任务后,先用此矩阵判断 OPC 级别,再决定是否启动以及以何种模式启动。 ``` L0 — 不触发 OPC(直接执行) 条件:单一工具调用 / 单步任务 / 预计 < 5 分钟 / 无需协作 L1 — 轻量 OPC(省略 Phase 0 确认,直接 spawn + 简报) 条件:2-3 步串行 / 有上下文依赖 / 单一领域 L2 — 标准 OPC(完整四阶段,方案卡 ≤ 5 行) 触发任意 3 条: □ 用户消息含"完整"/"全链路"/"从头到尾"/"完整的X" □ 预计步骤 > 5 步 □ 涉及 2+ 个独立业务领域 □ 需要输出文件 > 3 个 □ 预估 token > 50K □ 用户提到"并行"/"多角色"/"分工" L3 — 重型 OPC(完整四阶段 + 结构化方案卡 + 明确确认) 触发任意 2 条: □ 预计跨天或多个 session □ 涉及 3+ 个领域 □ 预估 token > 200K □ 有复杂依赖链(A 完成才能启动 B,B 完成才能启动 C) ``` ### 自适应指挥规则 | 级别 | Phase 0 | 方案卡 | 交付包 | 复盘 | |------|---------|--------|--------|------| | L1 | 跳过 | 跳过 | 简版(3行) | 跳过 | | L2 | 执行 | ≤ 5 行 | 标准版 | 执行 | | L3 | 执行 | 完整结构化 | 完整版 | 执行 | --- ## 角色模板库(v5.0) CEO spawn Sub-agent 时,优先继承 `playbook/roles/` 中的模板,再覆盖个性化参数。 | 文件 | 角色 | 核心产出 | |------|------|---------| | researcher.md | 研究员 | 调研报告、竞品分析 | | engineer.md | 工程师 | 代码、测试 | | writer.md | 写作者 | 文章、文档 | | analyst.md | 数据分析师 | 数据报告、指标分析 | | integrator.md | 汇总整合员 | 多角色产出合并 | | ux-designer.md | 体验设计师 | 交互方案、设计规格 | | biz-analyst.md | 商业分析师 | 商业模型、战略建议 | | critic.md | 评价与反馈 | 质量审查、改进建议 | **Persona 与角色是两个维度,可自由组合**: - 岗位模板定义"做什么"(任务边界 + 产出规格) - Persona 定义"怎么思考"(思维方式 + 方法论) ``` # 示例:高质量研究角色 [角色] researcher.md 研究员 [Persona] 以 Nate Silver 的数据驱动思维工作 [USER_VOICE] "{用户原话}" [文件所有权] reports/topic-a/ ``` --- ## 项目类型速启模板(v5.2) > 适用:Phase 1 规划时,识别项目类型 → 继承对应模板 → 只填参数 → spawn | 模板文件 | 项目类型 | 预设角色(含 critic) | |---------|---------|-------------------| | research-project.yaml | 调研/分析/竞品 | researcher×N + integrator + **critic** | | engineering-project.yaml | 开发/重构/MVP | engineer×N + (ux-designer) + **critic** | | content-project.yaml | 文章/博客/文档 | (researcher) + writer + **critic** | ⭐ **铁律:任何项目类型都必须包含至少一个 critic 角色** critic 在所有主产出完成后执行,评分 ≥ 3 才能进入交付包。 模板目录:`playbook/scenarios/` --- ## Output Contract(v5.0) 项目初始化时,CEO 在 `opc-projects/{pid}/` 创建 `output-contract.yaml`,声明所有预期产出。 ```bash # 使用模板 cp playbook/templates/output-contract.yaml opc-projects/{pid}/output-contract.yaml # verify 时对照 contract 执行 python3 engine/project_state.py verify <pid> <label> "contract" ``` 详见 `playbook/templates/output-contract.yaml`。engine/README.md2.9 KB11b2fdc71e4aupstream ↗
# Engine 层命令速查 > OPC 执行引擎 — 所有脚本的完整命令参考 工作目录建议切换到 skill 根目录执行: `cd ~/.openclaw/skills/agent-orchestration-20260309-lzw/` --- ## project_state.py — 项目状态管理 ```bash # 初始化 python3 engine/project_state.py init "项目名" [yyyymmdd] python3 engine/project_state.py update-phase <pid> <phase> # Agent 生命周期 python3 engine/project_state.py agent-start <pid> <label> '{"role":"名"}' python3 engine/project_state.py agent-complete <pid> <label> '{"output":"..."}' <tokens> python3 engine/project_state.py agent-fail <pid> <label> '{"error":"原因"}' # 断点续传 python3 engine/project_state.py checkpoint <pid> <label> '{"completedSteps":[...],"nextStep":"..."}' python3 engine/project_state.py checkpoint-get <pid> <label> # 查询 python3 engine/project_state.py list python3 engine/project_state.py show <pid> python3 engine/project_state.py restore <pid> # compaction 后恢复用 python3 engine/project_state.py cost <pid> python3 engine/project_state.py diagnose <pid> python3 engine/project_state.py close <pid> # 触发器(Phase 3 每轮必调) python3 engine/project_state.py trigger-evaluate <pid> python3 engine/project_state.py trigger-status <pid> python3 engine/project_state.py focus-list <pid> python3 engine/project_state.py focus-update <pid> <id> "[x]" # 工具发现 python3 engine/project_state.py tool-scan "任务描述" ``` --- ## tool_discovery.py — 工具发现(标签体系 v2) ```bash python3 engine/tool_discovery.py scan # 扫描本地 Skill python3 engine/tool_discovery.py report "任务描述" # 推荐报告(Phase 0 使用) python3 engine/tool_discovery.py search "关键词" # 搜索 python3 engine/tool_discovery.py check <skill_path> # 安全初筛 python3 engine/tool_discovery.py enrich <skill_name> # 查看某 Skill 的标签 python3 engine/tool_discovery.py --self-test ``` v2 标签体系:domain(12) × capability(8) 双路匹配,OPC 自排除。 --- ## trigger_engine.py — Aware 触发器 ```bash python3 engine/trigger_engine.py evaluate <project_dir> python3 engine/trigger_engine.py status <project_dir> python3 engine/trigger_engine.py --self-test ``` **CEO 集成规则**:Phase 3 每轮循环调用 `trigger-evaluate`;agent-complete 时自动检查 on_message 触发器(内置)。 --- ## diagnose_agent.py — 自动归因 ```bash python3 engine/diagnose_agent.py '{"spawn":"ok","announce":"missing","subagent_status":"done","error_msg":""}' ``` 归因层级:`L1-Platform` / `L2-Orchestration` / `L3-BusinessSkill` / `L4-External` --- ## 触发器生命周期 ``` 项目创建 → 可选:复制 playbook/templates/triggers.yaml 到项目目录 Phase 3 每轮 → trigger-evaluate(检查 once/interval/on_message) agent-complete → 自动检查 on_message + Focus auto-complete(内置) 项目关闭 → close(自动停用相关触发器) ```README.md6.8 KB240572643b8fupstream ↗
# 🏢 OPC — One-Person Company > **Multi-Agent Orchestration Skill** — Turn OpenClaw into the CEO of a one-person company. > > **多 Agent 编排技能** — 让 OpenClaw 成为一人公司的 CEO。 [English](#english) | [中文](#中文) --- <a name="english"></a> ## English ### What is OPC? OPC (One-Person Company) is an OpenClaw skill that turns complex tasks into multi-agent collaboration. You give the goal, the CEO (OpenClaw) breaks it down, hires the right agents, monitors progress, and delivers results. ``` You (Owner) → OpenClaw CEO → Sub-agents (Specialists) ``` ### Key Features - **Phase 0 Context Intake** — CEO reads your background, proposes a plan, waits for confirmation before executing - **Built-in Persona Library** — Inject top expert mindsets (Kotler, Fowler, Jeff Dean...) into each agent role - **LZW Advisor Persona** — Author's own methodology framework, ready to inject into any agent role - **Project State Persistence** — Survives context compaction; full lifecycle state in `state.json` - **Checkpoint & Resume** — Failed agents resume from last checkpoint, not from scratch - **Auto Root Cause Analysis** — L1-L4 fault classification (platform / orchestration / skill / external) - **Aware Triggers** — Declarative event-driven scheduling (cron / once / interval / on_message) - **Tool Discovery v2** — domain × capability tag system, precise skill recommendations - **User Model Evolution** — CEO writes back learnings after each project; gets smarter over time ### Quick Start ```bash # Install cd ~/.openclaw/skills unzip agent-orchestration-v5.0.zip # Trigger OPC by telling OpenClaw: # "Help me build a complete [project]" # "I need [multi-step task] done end-to-end" ``` ### Architecture ``` agent-orchestration-20260309-lzw/ ├── SKILL.md ← Entry point (v5.0) ├── brain/ ← CEO decision layer │ ├── core-flow.md ← 4-phase flow + Context Intake │ ├── task-decomposition.md │ ├── role-design.md │ └── collaboration-patterns.md ├── engine/ ← Execution engine │ ├── project_state.py ← Project lifecycle state │ ├── trigger_engine.py ← Aware triggers │ ├── tool_discovery.py ← Tool discovery (tag system v2) │ └── diagnose_agent.py ← Auto root cause analysis └── playbook/ ← Knowledge & templates ├── persona-priming.md ← Persona methodology + library index ├── personas/ │ └── lzw.md ← Built-in LZW Advisor Persona (v5.0) ├── templates/ └── scenarios/ ``` ### Persona Priming Two types of Personas, two design logics: | Type | Example | How it works | |------|---------|-------------| | **Activation** (public figures) | Kotler, Fowler, Jeff Dean | One-line reference activates LLM's pre-trained knowledge | | **Injection** (real individuals) | LZW (`personas/lzw.md`) | Full methodology doc injected into agent context | **New paradigm**: You can crystallize your own thinking framework into a Persona and inject it into your agent team. ### Real-World Validation | Case | Scale | Result | |------|-------|--------| | 315 Marketing Campaign (v1.0) | 3 agents serial | 67K tokens / $0.17 | | 3 Venues Parallel Build (v1.4) | 4 agents parallel | All 3 venues delivered | | KangaBase 0→1 (v2.0) | 8 agents, 4 phases | ~100 files / 8000 lines in 8h | | Neurotech Deep Analysis (v3.1) | 4 researchers + integrator | 4500-word report / $0.10 | ### Prerequisites - [OpenClaw](https://github.com/openclaw/openclaw) installed and configured - Python 3 (for engine scripts) ### License Apache License 2.0 — modifications must declare changes. See [LICENSE](LICENSE). --- <a name="中文"></a> ## 中文 ### OPC 是什么? OPC(One-Person Company,一人公司)是一个 OpenClaw Skill,把复杂任务转化为多 Agent 协作。你说目标,CEO(OpenClaw)负责拆活儿、招人、盯进度、交结果。 ``` 用户(老板)→ OpenClaw CEO → Sub-agents(专业员工) ``` ### 核心能力 - **Phase 0 Context Intake** — CEO 理解背景,给出方案,等确认后才执行 - **内置 Persona 库** — 给角色注入 Kotler / Fowler / Jeff Dean 等顶级人才的方法论 - **LZW 顾问 Persona** — 作者本人的方法论框架,可直接注入任意 Agent 角色 - **项目状态持久化** — 抗 context compaction,全生命周期状态写入 `state.json` - **断点续传** — Agent 失败后从断点继续,不完全重跑 - **自动归因** — L1-L4 故障分层(平台/编排/Skill/外部) - **Aware 触发器** — 声明式事件驱动(cron / once / interval / on_message) - **工具发现 v2** — domain × capability 双轴标签,精准推荐可用 Skill - **用户模型自进化** — 每次项目结束 CEO 自动写回学习结果,越用越懂你 ### 快速上手 ```bash # 安装 cd ~/.openclaw/skills unzip agent-orchestration-v5.0.zip # 触发 OPC,对 OpenClaw 说: # "帮我做一个完整的 [项目]" # "我需要 [多步骤任务] 全链路完成" ``` ### Persona Priming OPC 的 Persona 分为两类,设计逻辑不同: | 类型 | 代表 | 工作原理 | |------|------|---------| | **激活型**(公众人物) | Kotler、Fowler、Jeff Dean | 一行描述即可激活 LLM 预训练知识 | | **注入型**(真实个人) | LZW(`personas/lzw.md`) | 完整方法论文档注入 Agent context | **新范式**:用户可以把自己的思维框架沉淀为 Persona,注入到自己的 Agent 团队中。 ### 实战验证 | 案例 | 规模 | 结果 | |------|------|------| | 315 营销活动(v1.0) | 3 角色串行 | 67K tokens / $0.17 | | 三会场并行搭建(v1.4) | 4 角色并行 | 3 个会场全部交付 | | KangaBase 从零到开源(v2.0) | 8 Agent / 4 Phase | ~100文件/8000行,8小时 | | 神经调控深度分析(v3.1) | 4 研究员 + 整合员 | 4500字报告 / $0.10 | ### 版本历史 | 版本 | 日期 | 核心变更 | |------|------|---------| | **v5.0** | **2026-03-16** | **内置 LZW 顾问 Persona + personas/ 目录** | | v3.1 | 2026-03-14 | 用户模型自学习:Phase 0 读取 + Phase 4 写回 | | v3.0 | 2026-03-14 | 三层架构重构 + Context Intake + 工具发现标签体系 v2 | | v2.0 | 2026-03-12 | Aware 触发器 + 运行时工具自发现 | | v1.4 | 2026-03-11 | 状态持久化 + 断点续传 + 自动归因 | | v1.0 | 2026-03-09 | 首版:角色卡 + 任务分解 + 协作模式 | 见完整 [CHANGELOG.md](CHANGELOG.md) ### 前置条件 - 已安装并配置 [OpenClaw](https://github.com/openclaw/openclaw) - Python 3(用于引擎脚本) ### 许可证 Apache License 2.0 — 修改文件须声明变更。详见 [LICENSE](LICENSE)。 --- *Built with ❤️ by LZW · Powered by [OpenClaw](https://github.com/openclaw/openclaw)*brain/collaboration-patterns.md2.7 KBc2f98e7e24f1upstream ↗
# 协作模式 ## 模式1:串行流水线 ``` A → B → C ``` - 适用:严格依赖顺序 - 示例:策划 → 搭建 → 发布 - 实现:A 完成后 spawn B,B 完成后 spawn C ## 模式2:并行分工 ``` ┌─ B1 ─┐ A ──┼─ B2 ─┼── C └─ B3 ─┘ ``` - 适用:独立子任务可同时进行 - 示例:搭建员/内容员/供给员 同时工作 - 实现:A 完成后同时 spawn B1/B2/B3,全部完成后 spawn C - 注意:需要追踪所有并行任务状态 ## 模式3:迭代反馈 ``` A ←→ B → C ``` - 适用:需要审核/修改循环 - 示例:搭建员 ↔ QA审核员 → 发布员 - 实现:A 完成后 spawn B,B 不通过则 sessions_send 给 A 修改 ## 模式4:分治汇总 ``` ┌─ A1 ─┐ 任务─┼─ A2 ─┼── 汇总 └─ A3 ─┘ ``` - 适用:大任务可拆分为独立子任务 - 示例:3 个研究员分别研究,最后文档员汇总 - 实现:同时 spawn A1/A2/A3,全部完成后 spawn 汇总员 ## 模式选择决策 | 场景 | 推荐模式 | |------|---------| | 任务有严格先后顺序 | 串行 | | 多个独立子任务 | 并行 | | 产出需要质量审核 | 迭代 | | 大任务可拆分 | 分治 | | 复杂项目 | 混合(串行+并行+迭代)| ## 混合示例:营销活动 ``` 策划 ──→ 预算 ──→ ┬── 搭建 ──┬──→ QA ←→ 搭建 ──→ 发布 ├── 内容 ──┤ └── 供给 ──┘ ``` 阶段1:串行(策划→预算) 阶段2:并行(搭建/内容/供给) 阶段3:迭代(QA↔搭建) 阶段4:串行(发布) --- ## task-graph 使用指南(v5.1) 在 Phase 1(规划阶段)完成任务拆解后,CEO 应立即声明依赖图: ```bash # 示例:研究项目,两个研究员并行,汇总员串行 python3 engine/project_state.py task-graph <pid> add researcher_a "" reports/topic-a.md python3 engine/project_state.py task-graph <pid> add researcher_b "" reports/topic-b.md python3 engine/project_state.py task-graph <pid> add integrator "researcher_a,researcher_b" reports/final.md # 查看并行组(spawn 决策依据) python3 engine/project_state.py task-graph <pid> show # 输出:可并行启动: ['researcher_a', 'researcher_b'] ``` **执行策略**: ``` task-graph show → 找出"可并行启动"列表 │ ├── 并行组:同时 spawn,监控各自完成 │ └── 全部完成 → verify 各自产出 → 启动下游 └── 串行节点:等依赖项全部完成后再 spawn ``` **context compaction 后恢复**: ```bash python3 engine/project_state.py restore <pid> # restore 会输出 task_graph,CEO 根据已完成节点判断从哪里继续 ```brain/core-flow.md11 KB8293f83bac2eupstream ↗
# OPC 核心执行流程 > CEO 决策层 — 完整的 OPC 工作循环 --- ## Phase 0:Context Intake(上下文摄入)⭐ 最重要 **OPC 被触发后,第一步必须是理解背景、任务和目标,给出推进方案,征询确认。** 不允许跳过此步骤直接开始规划。 ### 0.1 用户模型读取(Phase 0 第一步,在追问用户之前) CEO 必须依次尝试读取以下文件(存在就读,不存在跳过,不报错): ``` 优先级 文件 说明 ① workspace/opc-user-model.md OPC 专属用户模型(越用越精准) ② ~/.openclaw/workspace/MEMORY.md OpenClaw 官方长期记忆 ③ ~/.openclaw/workspace/USER.md 用户扩展文件(可能不存在) ④ ~/.openclaw/workspace/memory/YYYY-MM-DD.md 今日日志(可选,近期上下文) ``` 读取后,CEO 综合这些信息形成对用户的预判: - 用户的偏好和风格(深度 vs 广度、报告格式偏好等) - 过去类似任务的成功配置(角色数量、Persona 选择、大致 token 消耗) - 已知约束(平台限制、惯用工具等) **有预判 → 生成带预填的方案草稿,用户只需校正差异** **无预判(首次)→ 正常追问,记录为这是第一次使用** ### 0.2 主动追问框架 CEO 围绕以下维度明确信息(已从用户模型中推断的可跳过,不确定的主动问): ``` 【背景】 - 这个任务在什么业务场景下?有什么前置条件? - 是新建还是继续已有工作? 【目标】 - 最终交付物是什么?(文档/页面/代码/分析报告...) - 成功的标准是什么?怎么判断"完成了"? 【约束】 - 截止时间?预算(token 上限)? - 有哪些平台限制(需要 SSO/浏览器/特定工具)? - 需要人工介入的节点? 【范围】 - 从哪里开始、到哪里结束? - 哪些不在本次范围内? ``` ### 0.3 推进方案输出格式 理解完成后,CEO 输出以下结构化方案,**等用户确认后才进入 Phase 1**: ```markdown ## 📋 OPC 项目方案 **背景理解**:{一句话概括} **目标**:{交付物 + 成功标准} **约束**:{时间/预算/限制} **推进方案**: - 角色配置:{N 个角色,名称 + 主要职责} - 协作模式:{串行/并行/混合,简述顺序} - 预估总预算:~{N}K tokens - 预计耗时:~{N} 分钟 **确认后开始执行,是否有需要调整的地方?** ``` ### 0.3 复杂度自动判断 | 条件 | 复杂度 | 确认轮次 | |------|--------|---------| | ≤2 角色,单一流水线 | 简单 | 1轮(合并 0+1) | | 3-5 角色,有并行 | 中等 | 1轮(0+1合并)| | >5 角色,跨业务线,>200K预算 | 复杂 | 2轮(0理解→1方案)| --- ## Phase 1:项目规划 1. 用 `project_state.py init` 创建项目 2. 拆解 OKR → Epic → Task(见 task-decomposition.md) 3. 定义角色、依赖关系、token 预算 4. 工具扫描(可选,见 engine/README.md) 5. **用户确认方案后才执行** ```bash python3 engine/project_state.py init "项目名称" python3 engine/project_state.py update-phase <pid> phase_1_planning ``` --- ## Phase 2:团队组建 按角色定义 spawn Sub-agents,注入角色卡 + Heartbeat 协议。 ```bash python3 engine/project_state.py agent-start <pid> <label> '{"role":"角色名"}' ``` 每个 spawn 后必须给用户一条确认消息: > ✅ {角色} 已启动(预计 N 分钟),持续监控中。 --- ## Phase 3:执行监控循环 ``` Sub-agent 完成 / 超时检查 │ ├── 收到结果 → 质量验收 │ ├── OK → agent-complete → 触发下游 │ └── 不OK → sessions_send 修改 → 最多 3 次 │ ├── 超时未收到 → 主动检查 │ subagents(action=list) → sessions_history → 拉取结果 │ ├── 触发器评估(每轮循环必须执行) │ python3 engine/project_state.py trigger-evaluate <pid> │ └── 阶段进度汇报给用户 ``` ### 主动监控间隔 | 任务复杂度 | 首次检查 | 后续间隔 | |-----------|---------|---------| | 简单 | 3 min | 2 min | | 中等 | 5 min | 3 min | | 复杂 | 10 min | 5 min | --- ## Phase 4:交付汇总 1. 汇总所有 Sub-agent 产出 2. 生成成本报告:`python3 engine/project_state.py cost <pid>` 3. 关闭项目:`python3 engine/project_state.py close <pid>` 4. 向用户交付最终成果 + 成本报告 --- ## 关键规则(CEO 必须遵守) 1. **Context Intake 不可跳过** — Phase 0 是所有 OPC 项目的入口,必须执行 2. **确认后才执行** — 任何 spawn 必须在用户确认方案后才触发 3. **不信任 announce** — 超时必须主动检查 4. **每步持久化** — Phase 切换、agent 状态变更立即写入 project_state 5. **断点优于重试** — agent 失败先保存 checkpoint,再考虑重新 spawn 6. **Phase 3 必须 trigger-evaluate** — 每轮监控循环必须调用触发器评估 --- ## 用户模型更新规范(Phase 4 关闭前必须执行) 项目关闭前,CEO 将本次项目的关键信息写入 `workspace/opc-user-model.md`: ### 写入内容 ```markdown ## [YYYY-MM-DD] {项目名称}({项目ID}) - 任务类型:{research / marketing / engineering / content / ...} - 角色配置:{N 个角色,列出名称+职责} - 协作模式:{串行 / 并行 / 混合} - 实际消耗:{N}K tokens(预算 {N}K) - 耗时:{N} 分钟 - 结果:{✅ 成功 / ⚠️ 部分完成 / ❌ 失败} - Persona 效果:{哪个 Persona 表现突出,简短备注} - 踩坑 / 经验:{有就写,没有跳过} ``` ### 更新用户偏好区 如果本次项目揭示了用户的新偏好或修正了旧认知,同步更新文件顶部的 `## 用户偏好` 区块。 ### 写入原则 - **只追加,不删除历史记录** - **偏好区可更新**(覆盖旧的同类条目) - **不写入 MEMORY.md 或 USER.md**(那是用户和喵神维护的,OPC 不动) - **文件不存在时自动创建**(参考模板:`playbook/templates/opc-user-model.md`) --- ## Phase 0 扩展:问题重构(Office Hours)— v5.3 新增 > 灵感来源:gstack `/office-hours`(Garry Tan,YC CEO) > 触发条件:L2/L3 任务必须执行;L1 可选 在 Context Intake 完成后,CEO 在开始规划前先执行问题重构: ### 三步问题重构 ``` Step 1:听痛点,不听功能描述 ❌ 用户说"做一个 X" → 直接规划 X ✅ 先问:"你遇到了什么具体问题?什么情况下最让你烦?" 目标:找到用户真正想解决的问题,而不是他描述的功能 Step 2:挑战前提假设(Premise Challenge) 提出 2-4 条关于这个任务的核心假设,让用户逐条确认: "我理解你的核心需求是 A,B 是必须要做的,C 可以之后再加——对吗?" 用户同意/修正每一条 → 这些假设成为规划的基础 Step 3:提供 2-3 个实现路径 + 诚实工作量估算 每条路径: - 一句话描述做什么 - 预计 token 消耗(S/M/L/XL) - 核心权衡(速度 vs 质量 vs 完整性) 推荐最小可行路径(先跑起来,再迭代) ``` ### 何时可以跳过 ``` ✅ 可跳过: - 用户已明确表达完整需求(有具体文件、路径、标准) - L1 轻量任务(< 3步,单一领域) - 重复型任务(之前做过完全相同的事) ❌ 不可跳过: - 用户描述的是"症状"而不是"需求" - 任务描述模糊或宏大("帮我做完整的X") - L3 重型任务(跨天/多领域) ``` ### 输出格式 ``` 🔍 问题重构 真实需求(我的理解):{一句话,不同于用户的原始描述时要标注} 核心假设确认: A. {假设} → 请确认 B. {假设} → 请确认 推荐路径:{路径名}(预计 ~{N}K tokens) 理由:{为什么这个路径最合适} 备选路径: - {路径B}({工作量},适合{场景}) - {路径C}({工作量},适合{场景}) 等你确认后开始规划。 ``` --- ## Phase 4:交付包 Delivery Package(v5.0 新增) > CEO 在所有 Agent 完成 + verify 通过后,**主动生成交付包**,不等用户追问。 > 交付包是 OPC 与用户之间的最后一公里——从"原材料"变成"可以用的结果"。 ### 标准交付包格式 ``` 📦 OPC 项目交付 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ✅ 核心结论 {一段话,直接说这个项目做出了什么、结论是什么} 📁 产出清单 - {label}:{path} — {一句话描述这个文件是什么} - ... 💡 CEO 建议 {基于产出,下一步可以做什么?有没有值得继续深入的方向?} ⚠️ 注意事项 {质量瑕疵(如有)/ 未完成项 / 需要人工确认的地方} {如无,填"无"} 💰 消耗摘要 总 token:~{N}K | 耗时:~{N} 分钟 | Agent 数量:{N} ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ``` ### 生成规则 - **核心结论**:不是产出列表,是真正的"所以怎样"——即使用户不读报告,看这一段也能做决策 - **CEO 建议**:至少给 1 条下一步建议,不能只说"供参考" - **注意事项**:诚实写出瑕疵,不粉饰太平;没有瑕疵才写"无" - **自适应长度**:L1 任务交付包可以压缩到 5 行;L3 任务完整展开 --- ## Phase 5:自动复盘 Retrospective(v5.0 新增) > 项目 close 时自动触发,**不需要 spawn Sub-agent**,CEO 自己执行。 > 目的:把踩过的坑变成系统知识,让 OPC 越用越强。 ### 触发时机 ```bash # close 命令自动触发 Phase 5 python3 engine/project_state.py close <pid> "项目已交付" # close 内部会自动调用 retrospective 逻辑 ``` ### 复盘五步 ``` Step 1:消耗对比 预估 token vs 实际 token 偏差 > 50% → 记录原因到 state.json Step 2:验收失败归因 有 verify 失败记录?→ 提炼失败模式 → 写入 opc-user-model.md "研究员 A 在 X 类任务上需要更明确的格式约束" Step 3:质量自评 CEO 给本次产出打分(1-5) 评分依据:用户满意度信号 + verify 通过率 + 交付包完整度 Step 4:一句话教训 这个项目最重要的一个教训是什么? 写入 playbook/scenarios/{场景}.md 的「踩坑记录」区块 Step 5:更新用户模型 把任务类型、角色配置、有效 Persona、消耗、评分写回 opc-user-model.md ``` ### 复盘产出写入位置 | 内容 | 写入位置 | |------|---------| | 消耗偏差原因 | opc-projects/{pid}/state.json → retrospective | | 失败模式 | opc-user-model.md → failure_patterns | | 质量评分 | opc-projects/{pid}/state.json → quality_score | | 一句话教训 | playbook/scenarios/{type}.md → 踩坑记录 | | 全量项目记录 | opc-user-model.md → project_history |brain/cost-tracking.md3.9 KB90fe97496ae2upstream ↗
# 成本追踪方法(v1.1 — 自动化增强) ## 设计原则 1. **CEO 主动采集,不依赖 Sub-agent 自觉汇报** 2. **结合 session_status + project_state.py 双路径** 3. **预算是硬约束,超限自动暂停** ## 追踪维度 | 维度 | 方式 | |------|------| | 按角色 | project_state.py 的 `byRole` 字段 | | 按任务 | 每个 agent-complete 时记录 tokens | | 按阶段 | Phase 切换时汇总当前成本 | | 总计 | project_state.py cost 命令 | ## CEO 主动采集机制(v1.1 新增) ### 不再依赖 Sub-agent 汇报 旧方案(v1.0):要求 Sub-agent 在 announce 中包含 `### Token 消耗\n约 {N}K tokens` **问题**:实测中 Sub-agent 基本不汇报 token,即使汇报也不准确。 新方案(v1.1):**CEO 主动通过 session_status 获取** ``` 每个 Sub-agent 完成(announce 或超时主动检查)后: 1. 调用 session_status(sessionKey=<agent_session_key>) 2. 从返回中提取 Tokens 使用量 3. 写入 project_state.py:agent-complete <pid> <label> <output> <tokens> ``` ### 获取 sessionKey 的方法 spawn 返回值中包含 sessionKey。如果 spawn 后没记录: ``` subagents(action=list) → 找到目标 agent → 获取 sessionKey ``` ### 汇报流程 ``` Phase 完成时: 1. python3 project_state.py cost <project_id> 2. 输出成本报告给用户 3. 检查是否超预算 ``` ## 预算告警(增强) | 阈值 | 动作 | |------|------| | 50% | 汇报进度 + 当前成本 | | 80% | ⚠️ 告警用户,评估剩余任务是否在预算内 | | 100% | 🛑 暂停所有 agent,等待用户授权追加预算或削减范围 | | 120% | 🚨 强制终止,生成成本超支报告 | ### 预算设置 初始化项目后设置预算: ```bash python3 project_state.py show <pid> # 手动编辑 state.json 的 cost.budgetLimit 字段 # 或在 CEO 规划阶段根据任务复杂度自动估算 ``` ### 自动估算公式 ``` 简单任务(单角色):50K tokens 中等任务(2-3角色):150K tokens 复杂任务(4+角色/并行):300K tokens 每增加一个 Sub-agent:+50K 基础开销 ``` ## CEO 汇总模板 ```markdown 📊 项目成本报告 — {project_name} 周期:{start} → {end} | 角色 | 任务数 | Token消耗 | 成本估算 | |------|--------|----------|---------| | {role1} | {n} | {tokens}K | ${cost} | | {role2} | {n} | {tokens}K | ${cost} | | CEO协调 | - | {tokens}K | ${cost} | | **总计** | **{total_tasks}** | **{total_tokens}K** | **${total_cost}** | 预算使用: {used}% ({total}/{budget}) ``` ## 成本优化建议(v1.1 更新) 1. **先小后大**:先用简单方案验证,再投入大预算 2. **复用产出**:Sub-agent 产出保存为文件(project outputs/),后续可直接读取不用重新生成 3. **裁剪角色**:简单项目合并角色,减少协调开销 4. **选对 model**:简单任务用基础模型,复杂任务才用高端模型 5. **断点续传**:agent 失败后从断点恢复,而非完全重试(利用 checkpoint) 6. **确认流程分级**:简单任务压缩确认轮次(见下方) ## 确认流程分级(v1.1 新增) ### 复杂度评估 在 Phase 1(项目规划)完成后,CEO 自动评估复杂度: ``` agent数量 ≤ 2 且无串行依赖 → 简单 agent数量 3-5 或有串行依赖 → 中等 agent数量 > 5 或有复杂依赖图 → 复杂 ``` ### 确认轮次 | 复杂度 | 确认轮次 | 说明 | |--------|---------|------| | 简单 | **1轮** | 合并:目标确认 + 角色方案 + 开始执行 | | 中等 | **2轮** | 第1轮:目标+方案;第2轮:执行模式确认 | | 复杂 | **3轮** | 标准流程不变(任务理解→组织方案→执行模式) | ### 简单任务的1轮确认模板 ```markdown 📋 任务确认 **目标**: {goal} **方案**: spawn {n} 个 agent({role1}、{role2}) **执行模式**: 当前Session / 独立Session **预估成本**: ~{budget}K tokens 确认执行?(Y/N) ```brain/heartbeat-protocol.md1.1 KBccf2501753a0upstream ↗
# Heartbeat 协议 Sub-agent 执行标准协议,确保行为可控、产出规范。 ## 协议流程 ``` 1. 确认身份 - 我是谁(角色) - 我要做什么(任务) - 我的预算是多少 2. 理解上下文 - 有没有上游产出需要参考 - 有没有约束条件 3. 执行工作 - 按职责完成任务 - 使用允许的工具 - 在预算内完成 4. 汇报产出 - 产出内容(按要求的格式) - Token 消耗估算 - 是否完成/部分完成/失败 - 下游需要知道什么 5. 异常处理 - 如遇障碍:说明障碍 + 建议方案 - 如需帮助:明确说明需要 CEO 做什么 - 如超预算:先汇报已有产出,说明还需多少 ``` ## 产出汇报模板 ``` ## 任务完成报告 **角色**:{role} **任务**:{task} **状态**:已完成 / 部分完成 / 失败 ### 产出 {实际产出内容} ### Token 消耗 约 {N}K tokens ### 备注 {异常情况/建议/下游注意事项} ``` ## CEO 检查清单 收到 Sub-agent announce 后: 1. 产出是否符合要求? 2. 是否在预算内? 3. 是否有异常需要处理? 4. 下游任务是否可以触发?brain/proactive-reporting.md3.5 KB2bc50ce48906upstream ↗
# CEO 主动监控与汇报机制 ## 问题背景 联调中反复出现的问题:Sub-agent 完成任务后 announce 不到达 CEO, 导致项目停滞等待——直到用户主动询问才发现 Agent 早已完成。 这违背了 OPC "用户不应该需要催" 的核心原则。 ## 解决方案:CEO 主动轮询机制 ### 机制设计 ``` CEO spawn sub-agent 后,立即启动监控循环: 1. 记录 spawn 时间和预估完成时间 2. 设置检查间隔(根据任务复杂度) 3. 到达检查点时,主动执行: a. subagents(action=list) 查看状态 b. 如果 done → sessions_history 拉取结果 → 推进下游 c. 如果 active → 检查运行时长是否超预期 d. 如果 error → 分析原因,决定重试/告警 4. 向用户推送进度更新 ``` ### 检查间隔标准 | 任务复杂度 | 预估时长 | 首次检查 | 后续间隔 | |-----------|---------|---------|---------| | 简单(搜索/整理) | 2-5min | 3min 后 | 每 2min | | 中等(策划/分析) | 5-15min | 5min 后 | 每 3min | | 复杂(搭建/多步骤) | 15-30min | 10min 后 | 每 5min | ### CEO 主动汇报规则 **规则1:spawn 后必须给用户一条确认** ``` "✅ 策划员已启动(预计5分钟),我会持续监控并汇报进展。" ``` **规则2:到达检查点必须汇报** ``` - 如果 Agent 还在跑:"🔄 策划员运行中(已3分钟),正在搜索调研阶段。" - 如果 Agent 已完成:"✅ 策划员完成!产出质量OK,正在启动搭建员。" - 如果 Agent 异常:"⚠️ 策划员运行超时(15分钟),正在检查..." ``` **规则3:阶段转换必须汇报** ``` "📊 项目进度更新: T001 策划 ✅ → T002 制券 🔄 → T003 选品 🔄 → T004 搭建 ⏳ → T005 发布 ⏳" ``` **规则4:异常必须立即汇报** ``` "⚠️ 搭建员执行失败(错误:SSO 认证过期),需要你帮忙处理。" ``` ### 实现方式 由于 OpenClaw 中 CEO(Main Session)不能设置定时器, 主动监控需要 CEO 在每次与用户交互时顺带检查: ``` 用户发任何消息时: 1. 先检查有没有正在运行的 OPC 项目 2. 如果有 → subagents list → 更新状态 → 必要时汇报 3. 再处理用户当前消息 ``` 或者通过 heartbeat 机制: ``` Heartbeat 巡逻时: 1. 检查有没有 active sub-agents 2. 如果有 → 检查运行时长 → 必要时拉取结果或告警 ``` ### 汇报模板 **进度更新(定期)** ``` 📊 {项目名} 进度更新 | Task | 状态 | 时长 | Token | |------|------|------|-------| | T001 | ✅ done | 3min | 10K | | T002 | 🔄 running | 2min | - | | T003 | ⏳ pending | - | - | 下一步:T002 预计 2 分钟完成,届时启动 T003。 ``` **异常告警** ``` ⚠️ {项目名} 异常 问题:{Agent角色} 运行 {时长},超过预期 {预期时长}。 状态:{subagents list 结果} 建议:{重试 / kill 重建 / 等待 / 需要用户介入} ``` **阶段完成通知** ``` ✅ {项目名} 阶段完成 {Agent角色} 已完成 {任务名}: - 产出:{摘要} - 消耗:{token}K tokens - 质量:{OK / 需修改} 下一步:正在启动 {下游任务}。 ``` ## 与 Heartbeat 协议的关系 Sub-agent 端的 Heartbeat 协议(汇报产出)+ CEO 端的主动监控机制 = 双保险。 - **Sub-agent Heartbeat**:Agent 完成后主动汇报(依赖 announce,不可靠) - **CEO 主动监控**:CEO 定期检查 Agent 状态(不依赖 announce,可靠) 两者互补,确保不出现"两边都在等对方"的死锁。brain/role-design.md1.7 KB04950169c30aupstream ↗
# 角色设计方法论 ## 原则 1. **单一职责**:每个角色只做一件事 2. **角色 = 能力单元**:一个 Sub-agent 代表一种专业能力 3. **最小权限**:只给完成任务所需的工具和知识 ## 角色卡模板 ``` [OPC 角色卡] - 角色:{name} - 隶属:{team} - 汇报给:OpenClaw CEO - 职责:{核心职责} - 可用工具:{tools} - 业务 Skill:{如 gundam-ops} - 预算:{N}K tokens - 协作上游:{输入来自谁} - 协作下游:{产出给谁} ``` ## 预置角色库 ### 策划类 | 角色 | 职责 | 预算 | 工具 | |------|------|------|------| | 活动策划员 | 制定活动方案 | 20-40K | web_search | | 预算分析员 | 分析预算 ROI | 15-25K | exec | | 目标拆解员 | OKR 分解 | 15-25K | write | ### 执行类 | 角色 | 职责 | 预算 | 工具/Skill | |------|------|------|------------| | 会场搭建员 | 高达平台搭建 | 40-80K | browser, gundam-ops | | 供给配置员 | 数据片配置 | 20-40K | browser | | 内容创作员 | 文案撰写 | 20-40K | write | ### 发布类 | 角色 | 职责 | 预算 | 工具 | |------|------|------|------| | 发布专员 | 诊断+发布 | 15-30K | browser | | QA 审核员 | 质量检查 | 20-30K | browser | ### 通用类 | 角色 | 职责 | 预算 | 工具 | |------|------|------|------| | 研究员 | 深度调研 | 30-60K | web_search | | 文档整理员 | 汇总产出 | 15-25K | read, write | ## 角色组合 - **小型项目**:策划 → 执行 → 发布(2-3角色) - **中型项目**:策划 → 搭建/内容/供给 → 发布(4-5角色) - **大型项目**:策划 → 预算 → 搭建/内容/供给 → QA → 发布(6+角色) **原则:宁少角色多轮次,不多角色低利用率**brain/task-decomposition.md4.2 KBbb2ab2995894upstream ↗
# 任务分解方法论 ## 三层结构:OKR → Epic → Task ``` Objective: {一句话目标} ├── KR1: {可衡量的关键结果} │ ├── Epic 1.1: {大功能块} │ │ ├── Task: {具体任务} → 角色 [依赖] [预算] │ │ └── Task: ... │ └── Epic 1.2: ... └── KR2: ... ``` ## Task 定义规范 ```yaml task_id: T001 name: 确定活动主题 epic: E1.1-活动策划 role: 活动策划员 depends_on: [] # 依赖的 task_id 列表 estimated_tokens: 25000 # 预估 token status: pending # pending/assigned/in_progress/review/completed/failed priority: high # high/medium/low output: markdown # 产出格式 ``` ## 状态机 ``` pending → assigned → in_progress → review → completed ↓ ↓ failed failed ``` ## 依赖管理 1. **硬依赖**:必须等上游完成。如"搭建"依赖"策划方案" 2. **软依赖**:最好有但可以先开始。如"内容"软依赖"设计风格" 3. **无依赖**:可并行执行 ## 拆分粒度原则 - 每个 Task 预估 token < 50K - 每个 Task 产出明确可验收 - 每个 Task 由单一角色完成 - 依赖链不超过 5 层 ## 示例:营销活动 ``` Objective: 315 促销活动上线 ├── KR1: 活动页面 3.10 前发布 │ ├── Epic 1.1: 策划 │ │ ├── T001: 确定主题人群 → 策划员 [无依赖] [25K] │ │ └── T002: 制定预算分配 → 预算员 [T001] [20K] │ ├── Epic 1.2: 搭建 │ │ ├── T003: 创建高达活动 → 搭建员 [T001] [30K] │ │ ├── T004: 配置页面组件 → 搭建员 [T003] [40K] │ │ └── T005: 配置供给数据 → 供给员 [T003] [30K] │ └── Epic 1.3: 发布 │ ├── T006: 发布诊断 → 发布员 [T004,T005] [15K] │ └── T007: 正式发布 → 发布员 [T006] [10K] └── KR2: ... ``` --- ## 任务拆解四问(v5.1 强制检查) > CEO 每拆出一个 Agent,必须能回答这四个问题。 > 回答不出来 → 任务没拆清楚,继续拆,不要 spawn。 ``` Q1. 这个 Agent 的「唯一产出」是什么? ✅ 好:workspace/reports/2026-03-19-topic-a.md ❌ 差:帮我研究一下 X Q2. 产出的验收标准是什么? ✅ 好:行数 > 80,包含"核心发现"章节,npm test 全绿 ❌ 差:写得好 Q3. 这个 Agent 依赖什么输入? ✅ 好:workspace/reports/topic-a.md(由 researcher_a 产出) ✅ 好:无(独立任务,可直接 spawn) ❌ 差:(空白/未声明) Q4. 文件边界是什么?(owned_paths) ✅ 好:packages/core/src/ ❌ 差:(未声明,默认全局 → 并行风险) ``` --- ## 并行判断规则(v5.1 明确化) ### 可以并行的条件(全部满足才并行) ``` ✅ 两个 Agent 的输入来源互不依赖(A 不需要读 B 的产出) ✅ 两个 Agent 的 owned_paths 不重叠 ✅ 两个 Agent 的产出不需要互相参考 ``` ### 必须串行的条件(任意一条 → 强制串行) ``` ❌ Agent B 的任务描述里包含"基于上一步"/"参考前一个 Agent" ❌ 两个 Agent 可能写同一个文件(哪怕一个是主写一个是"微调") ❌ Agent B 的输入是 Agent A 的产出 ``` ### 典型模式速查 | 场景 | 模式 | 说明 | |------|------|------| | 多研究员各研究不同方向 | 并行 ✅ | 输入独立,输出独立 | | 研究员 + 汇总员 | 串行 ❌ | 汇总员依赖研究员产出 | | 前端 + 后端分离开发 | 并行 ✅ | 文件边界清晰不重叠 | | 编码 + 测试(同一模块)| 串行 ❌ | 测试依赖编码产出 | | 多会场搭建(各自独立Tab)| 并行 ✅ | 操作对象完全独立 | --- ## 拆解粒度校验(v5.1) 拆出的每个 Task 必须通过以下检验: ``` ☑ 预估 token < 80K(超过则继续拆分) ☑ 产出是单一文件/目录(不是"一堆东西") ☑ 由单一角色完成(不是两个角色混着干) ☑ 依赖链层数 ≤ 5(超过则重新规划结构) ☑ 四问全部能回答(见上方四问框架) ``` **黄金原则**:一个 Agent = 一个可独立验收的产出单元。brain/verification.md4.7 KB073f04b6c9eeupstream ↗
# CEO 自主验收规则库 (v4.0) > 每个 Phase 结束时,CEO **自己跑验收**——不依赖 Sub-agent 的自述。 > 验收通过才调用 `agent-complete`;不通过先反馈再重试,最多 3 次。 --- ## 核心原则 **"Sub-agent 说完成了" ≠ "完成了"。CEO 必须独立核实。** 执行流程: ``` Sub-agent announce / 超时轮询到结果 │ ├── 1. 跑验收命令(见下方速查表) ├── 2. PASS → verify 命令记录 → agent-complete └── 3. FAIL → 发精准反馈 → 最多重试 3 次 第 3 次仍失败 → agent-fail + checkpoint → 告警用户 ``` --- ## 验收命令速查表 ### 工程类 | 任务 | 验收命令 | 通过条件 | |------|---------|---------| | TypeScript/Node.js | `npm test` | 全绿,0 fail | | Python | `python -m pytest` | 全绿 | | 代码构建 | `npm run build` | 0 error | | 文件存在 | `test -f <path> && wc -l <path>` | 存在 + 行数 > 阈值 | | 接口可用 | `curl -s http://localhost:{port}/api/health` | 200 OK | **工程类验收模板:** ```bash # 1. 确认产出文件存在 ls -la <output_dir> # 2. 跑测试 cd <repo> && npm test 2>&1 | tail -5 # 3. 关键文件内容抽查 head -20 <key_file> ``` ### 研究/写作类 | 任务 | 验收方式 | 通过条件 | |------|---------|---------| | 研究报告 | `wc -l <file>` + 内容抽读 | 行数 > 50 + 关键章节存在 | | 多角色汇总 | 检查各研究员输出文件均存在 | N 个文件全部存在且非空 | **研究类验收模板:** ```bash for f in <output_dir>/*.md; do echo "=== $f ===" && wc -l "$f" && head -5 "$f" done ``` ### 通用兜底验收(任何任务都适用) ```bash # 文件存在性 + 大小 find <workspace> -newer <start_marker> -type f | head -20 # 读取产出尾部 tail -100 <output_file> ``` --- ## 验收失败处理流程 ``` 验收失败(第 N 次) │ ├── N < 3 → 发精准反馈给 Sub-agent │ "验收未通过(第{N}/3次): │ ✗ {具体失败原因,附命令输出} │ 请修复后重新提交。" │ └── N = 3 → agent-fail + checkpoint 保存进度 + 通知用户 人工判断:修复 skill → 断点续传 or 跳过 ``` ## 与 project_state.py 集成 ```bash # 验收(0=通过,非0=失败,自动记录到 state) python3 engine/project_state.py verify <pid> <label> "npm test" # 验收通过后再 complete python3 engine/project_state.py agent-complete <pid> <label> \ '{"output":"验收通过","verifyPassed":true}' <tokens> ``` --- ## Phase 级汇总验收 Phase 切换时,CEO 执行: ``` 1. 列出本 Phase 所有预期产出(from 项目规划) 2. 逐一核对:文件存在 + 内容抽查 3. 有缺失 → 补充 spawn 或标记 partial 4. 全部通过 → update-phase + 推送阶段成本报告(见 cost-tracking.md) ``` --- ## Iron Law 调试协议(v5.3 新增) > 灵感来源:gstack `/investigate` — "Iron Law: no fixes without investigation" ### 核心规则 **verify 失败不等于立刻重试。先调查,后修复。** ``` verify 失败第 1 次: → 仔细读错误信息 → 确认是哪个 Agent 的产出问题(文件不存在?命令失败?) → 给 Agent 精准反馈,要求修复 → 重新 verify verify 失败第 2 次(相同问题): ⚠️ 停止重试 → 触发根因分析(Root Cause Analysis) → CEO 自问: 1. 任务描述是否本来就不清楚?(输入问题) 2. 角色选择是否有误?(配置问题) 3. 产出标准是否不合理?(期望问题) 4. 有没有我没考虑到的技术约束?(环境问题) → 根据根因,选择:修改任务描述/换角色/降低标准/拆分任务 → 重新 spawn(不是重试) verify 失败第 3 次: 🛑 强制暂停 → 把失败情况完整描述给用户 → 请用户介入决策:降低标准?换方案?放弃这个产出? → 不再自主重试 ``` ### 根因分析模板 ``` 【verify 失败根因分析】 错误信息:{exact error} 失败次数:{N} 假设 1:{可能的原因} 验证方式:{怎么确认这个假设} 结论:{对/错} 假设 2:{可能的原因} ... 根因判断:{最可能的原因} 修复策略:{具体行动,不是"重试"} ``` ### 为什么这样设计 - 连续失败 = 系统性问题,不是随机错误,重试没有意义 - 根因不找到,同样的失败会在其他项目中重现 - 第 3 次失败必须让人介入——人类的判断比 CEO 自主绕行更可靠 ### 与 Phase 5 复盘的衔接 失败模式 → 记录到 `retrospective.failure_patterns` → `retro` 命令聚合分析 → 识别系统性问题CHANGELOG.md18 KBacba23bdff51upstream ↗
# Changelog - agent-orchestration-20260309-lzw ## 版本信息 - **分支名**: agent-orchestration-20260309-lzw - **作者**: 大仙 (lzw) - **创建时间**: 2026-03-09 14:05 - **方向**: One-Person Company (OPC) 编排技能 ## 设计目标 - 让 OpenClaw 成为"一人公司"CEO - 能指挥调度多个专业 Sub-agent 协作完成企业复杂任务 - 借鉴 PaperClip 组织管理方法论 - 与 gundam-ops 等业务 Skill 配合使用 ## v1.0 (2026-03-09) ### Added - SKILL.md 主入口 (~215行) - references/ 方法论文档 - role-design.md - 角色设计方法论 - task-decomposition.md - 任务分解(OKR → Epic → Task) - heartbeat-protocol.md - Agent 执行协议 - cost-tracking.md - 成本追踪方法 - collaboration-patterns.md - 协作模式 - templates/ 可复用模板 - agent-prompt.md - Sub-agent task prompt 模板 - project-plan.md - 项目计划模板 - cost-report.md - 成本报告模板 - scenarios/ 场景案例 - marketing-campaign.md - 营销活动全链路案例(含详细 spawn 示例) - scripts/ 自动化脚本 - project_tracker.py - 项目状态追踪 - cost_summary.sh - 成本汇总 ### 文件统计 - 总计 12 个文件 - 约 1100 行 ## 待迭代 - [ ] 实际营销场景联调验证 - [ ] 与 gundam-ops skill 联动测试 - [ ] 多 Agent 并行协作稳定性 - [ ] 更多场景案例(研究项目、内容创作...) ## 联调测试 (2026-03-09 14:22 - 15:37) ### 场景 315营销活动(精简3角色:策划→搭建→发布) ### 结果 - 3个 sub-agent 全部完成,产出质量良好 - 总消耗 67K tokens ($0.17) - 发现 announce 不可靠问题并修复 ### 迭代 - 新增 references/troubleshooting.md(故障归因) - SKILL.md 新增超时检查规则 + 三步归因法 ## v1.1 (2026-03-09 15:48) ### Added - references/design-philosophy.md (315行) — 完整设计理念文档 - OPC 核心理念和5大设计原则 - 全生命周期运行逻辑 - 多轮对话 OPC 组织设定流程(3轮确认) - 独立 Session 模式说明 - OPC 与业务 Skill 关系(分层架构 + 通俗比喻) - 独立 Session 决策指南 - 设计哲学总结 ### Changed - SKILL.md 新增多轮对话组织设定说明 + 设计理念引用 ## v1.2 (2026-03-09 16:23) ### Added - 附录A:OPC vs OpenClaw 原生 Multi-Agent 对比分析(追加到 design-philosophy.md) - 原生7种模式梳理(spawn/heartbeat/cron/send/lobster/A2A...) - 逐一对比(OPC vs spawn / heartbeat / cron / lobster) - 适用 vs 不适用场景明确 - 组合使用最佳实践 - 优劣势总结 ## v1.3 (2026-03-09 21:49) ### Added - references/persona-priming.md — 角色 Persona 增强方法论 - 顶级人才 persona 库(营销/技术/研究/创意 4大类) - 使用原则:借鉴方法论,而非模仿人格 - 升级版角色卡模板 - references/proactive-reporting.md — CEO 主动监控与汇报机制 - 检查间隔标准(简单3min/中等5min/复杂10min) - 4条汇报规则(确认/检查点/阶段转换/异常) - 汇报模板(进度更新/异常告警/阶段完成) - 与 Sub-agent Heartbeat 的双保险机制 ### Changed - SKILL.md 新增 Persona Priming 和 CEO 主动监控章节 - templates/agent-prompt.md 角色卡新增 Persona 字段 ## v1.4 (2026-03-11) — 实战驱动的四项优化 > 基于 2026-03-10 三会场搭建实战中暴露的问题,推动四项关键优化。 ### 实战问题 | 问题 | 影响 | 根因 | |------|------|------| | Compaction 丢失执行状态 | Phase 2 启动延迟 | 项目状态完全在 context 中 | | 并行 agent 状态不清晰 | CEO 难判断谁完了谁卡了 | 缺乏结构化状态看板 | | 失败后完整重试 | 到餐搭建员浪费 17min | 无断点续传机制 | | 成本追踪形同虚设 | Sub-agent 不汇报 token | 依赖"自觉"这种不可靠的机制 | ### Added — 项目状态持久化(P0) - **scripts/project_state.py** (368行) — 全新项目状态管理器 - `init` / `update-phase` / `agent-start` / `agent-complete` / `agent-fail` - `checkpoint` / `checkpoint-get` / `restore` - `show` / `list` / `report` / `diagnose` - 自动计算成本占比和预算告警 - **references/project-state.md** — 状态持久化设计文档 - 状态文件结构(JSON Schema) - 目录结构规范 - CEO 集成规范(4条必须遵守的规则) - Compaction 恢复流程 ### Added — 断点续传(P0) - SKILL.md 新增「断点续传」章节 - 完整流程:失败→提取步骤→保存断点→kill→恢复→注入 - 断点续传 prompt 模板 - 断点内容规范(completedSteps/nextStep/context) ### Added — 自动归因(P1) - `project_state.py diagnose` 命令 - 根据错误关键词自动分类:L1-Platform / L2-Orchestration / L3-BusinessSkill - 输出建议操作 - 标注是否有可用断点 ### Changed — 成本追踪自动化(P1) - 不再依赖 Sub-agent 自觉汇报 - CEO 通过 session_status 获取 token 消耗后写入 project_state - `project_state.py report` 自动生成成本报告 - 预算告警自动计算(80%/100% 阈值) ### Changed — 确认流程分级简化(P1) - 原来:所有任务都3轮确认 - 现在:简单1轮 / 中等2轮 / 复杂3轮 - 判断标准:Sub-agent 数量 + 并行度 + 跨业务线 ### Changed — 使用限制更新 - 第3条:「预算是软约束」→「预算通过 project_state.py 自动追踪」 - 第4条:「项目状态在 context 中」→「项目状态持久化到文件」 ### File Statistics - 新增文件:2(project_state.py + project-state.md) - 修改文件:2(SKILL.md + CHANGELOG.md) - 新增行数:~550行 - SKILL.md 总行数:~486行 # v2.0 (2026-03-12) — Aware 触发器 + 运行时工具自发现 > OPC 从"被动执行"进化为"事件驱动"——项目定义好规则后能自己动起来。 ## 核心新增 ### Aware 触发器系统(P0) 声明式事件驱动,CEO 在 heartbeat 时调用 `evaluate()` 自动检查触发条件。 - **scripts/trigger_engine.py** (~380行) — 触发器引擎 + Focus 管理器 - `TriggerEngine`: 5种触发类型(cron/once/interval/on_message/poll) - `FocusManager`: 项目焦点自适应管理,agent 全部完成时自动关闭 - 命令行: `evaluate` / `status` / `fire` / `focus-list` / `focus-update` - 状态持久化: `trigger_state.json` - 内置自测: `--self-test` - **references/aware-triggers.md** (~200行) — 完整设计文档 - 触发器类型说明和 YAML Schema - Focus 系统和联动机制 - CEO 集成规范和最佳实践 - **templates/triggers.yaml** — 触发器配置模板(5种类型示例) - **templates/focus.yaml** — Focus 焦点模板 ### 运行时工具自发现(P0) 任务启动前自动发现可用工具,弥补能力缺口。 - **scripts/tool_discovery.py** (~300行) — 工具自发现引擎 - `scan`: 扫描本地已安装 Skill - `search`: 搜索 ClawHub 公开 Skill - `report`: 生成工具建议报告(任务↔工具匹配) - `check`: 基础安全初筛 - 缓存: `.tool-cache.json`(TTL 1小时) - 内置自测: `--self-test` - **references/tool-discovery.md** (~150行) — 设计文档 - 搜索源优先级和安全策略 - CEO 集成规范和使用示例 ### project_state_v2.py — 集成扩展 在 v1.4 `project_state.py` 基础上新增 5 个命令: | 命令 | 说明 | |------|------| | `trigger-evaluate <pid>` | 评估所有触发器 | | `trigger-status <pid>` | 查看触发器状态 | | `focus-update <pid> <id> <status>` | 更新焦点状态 | | `focus-list <pid>` | 列出活跃焦点 | | `tool-scan <task>` | 扫描推荐工具 | 另外,`agent-complete` 命令现在会自动调用 `FocusManager.check_auto_complete()`。 ## Changed - **SKILL.md** — 追加两个新章节(Aware 触发器 + 工具自发现),更新目录结构 - **目录结构** — 新增 4 个文件到 scripts/、2 个到 references/、2 个到 templates/ ## 设计约束 - Python 3.9+ 兼容,仅标准库 + yaml(可选,有 fallback) - 所有脚本支持 `--help` 和 `--self-test` - YAML 解析容错(缺字段不崩溃) - 触发器状态持久化到 `trigger_state.json` - 工具缓存 TTL 1 小时 ## 文件统计 | 文件 | 行数 | 说明 | |------|------|------| | scripts/trigger_engine.py | ~380 | 新增 | | scripts/tool_discovery.py | ~300 | 新增 | | scripts/project_state_v2.py | ~370 | 新增(v1.4扩展) | | references/aware-triggers.md | ~200 | 新增 | | references/tool-discovery.md | ~150 | 新增 | | templates/triggers.yaml | ~60 | 新增 | | templates/focus.yaml | ~25 | 新增 | | SKILL_v2_additions.md | ~100 | SKILL.md 追加内容 | **新增总行数**: ~1585 **新增文件数**: 8 ## 迁移指南 1. 将 `scripts/trigger_engine.py` 和 `scripts/tool_discovery.py` 复制到正式路径 2. 用 `project_state_v2.py` 替换原 `project_state.py`(完全向后兼容) 3. 将 `references/` 和 `templates/` 下新文件复制到正式路径 4. 将 `SKILL_v2_additions.md` 内容追加到 SKILL.md 末尾 5. 将此 CHANGELOG 内容追加到 CHANGELOG.md --- ## v2.0 (2026-03-12) — Aware 触发器 + 运行时工具自发现 ### 核心变更 借鉴 [Clawith](https://github.com/dataelement/clawith) 的 Aware 自治系统,新增两大能力。 ### Aware 触发器系统 声明式事件驱动,在 `triggers.yaml` 中定义规则,CEO 不再手动轮询: | 触发类型 | 用途 | |---------|------| | `cron` | 定时触发 | | `once` | 一次性 deadline | | `interval` | 周期检查 | | `on_message` | Agent A 完成 → 自动启动 Agent B | | `poll` | 外部轮询 | 配合 **Focus 焦点系统**——Focus 下所有 Agent 完成时自动标记完成并清理触发器。 ### 运行时工具自发现 Agent 执行前自动扫描可用 Skill,发现能力缺口时生成推荐报告: - 本地扫描 `~/.openclaw/skills/` 和 `/app/skills/` - 基于 bigram 分词关键词匹配 - 安全检查(可疑模式检测) - 已安装 / 推荐安装 / 需确认 三级分类 ### project_state.py 新增命令(v2.0) - `trigger-evaluate`:评估触发器是否应触发 - `trigger-activate / deactivate`:管理触发器状态 - `focus-set / focus-clear`:焦点管理 - `checkpoint-save / checkpoint-load`:断点管理 ### 新增文件 | 文件 | 说明 | |------|------| | `scripts/trigger_engine.py` | Aware 触发器引擎 | | `scripts/tool_discovery.py` | 工具自发现 | | `references/aware-triggers.md` | 触发器系统文档 | | `references/tool-discovery.md` | 工具发现文档 | | `templates/triggers.yaml` | 触发器模板 | | `templates/focus.yaml` | Focus 模板 | **新增代码行数**:+2308 行 --- ## v3.0 (2026-03-14) — 三层架构重构 + Context Intake + 标签体系 v2 ### 核心变更 #### 三层架构重构 旧结构(references / scripts / templates / scenarios)→ 新三层架构: ``` brain/ ← CEO 决策层(怎么想) engine/ ← 执行引擎层(怎么跑) playbook/ ← 知识与模板层(参考素材) ``` SKILL.md 从 635 行精简至 207 行(-67%) #### Phase 0 Context Intake(强制入口) OPC 被触发后,第一步必须给出推进方案并征询确认,不允许直接 spawn。 - 四维摄入框架(背景/目标/约束/范围) - 标准化方案输出格式 - 复杂度自动判断(1-2 轮确认) #### 工具发现标签体系 v2 `tool_discovery.py` 升级: - 12 个 domain 标签 × 8 个 capability 标签 - 标签匹配(精确)+ 关键词(兜底)双路匹配 - OPC 自排除:不再把自己推荐给任务 - 新增 `enrich` 命令 #### 触发器融入生命周期 Phase 3 每轮循环明确要求执行 `trigger-evaluate`。 ### 新增文件 | 文件 | 说明 | |------|------| | `brain/core-flow.md` | 四阶段完整流程规范 | | `engine/README.md` | 引擎命令速查 | | `playbook/scenarios/research-project.md` | 研究项目实战案例 | ### 验证 格式塔科技深度分析(opc-20260314-002):4 Agent 并行,40K tokens,全链路通过。 --- ## v3.1 — 用户模型自学习(2026-03-14) ### 核心变更:OPC 越用越懂你 **问题**:v3.0 的 Phase 0 每次从零开始理解用户意图,不积累任何经验。 **方案**:双源用户模型 + 项目结束自动写回。 ### 新增:Phase 0 用户模型读取 OPC 触发后,在追问用户之前,先依次读取: | 优先级 | 文件 | 说明 | |--------|------|------| | ① | `workspace/opc-user-model.md` | OPC 专属模型,越用越精准 | | ② | `~/.openclaw/workspace/MEMORY.md` | OpenClaw 官方长期记忆 | | ③ | `~/.openclaw/workspace/USER.md` | 用户扩展文件(可能不存在)| | ④ | `~/.openclaw/workspace/memory/YYYY-MM-DD.md` | 今日日志(可选)| 有预判 → 生成带预填的方案草稿,用户只需校正差异 无预判(首次)→ 正常追问,记录为第一次使用 ### 新增:Phase 4 用户模型写回 项目关闭前,CEO 自动将以下信息写入 `opc-user-model.md`: - 任务类型、角色配置、协作模式 - 实际 token 消耗与耗时 - Persona 效果观察 - 踩坑与经验 偏好区如有新发现,同步更新(覆盖旧条目)。 ### 新增文件 | 文件 | 说明 | |------|------| | `playbook/templates/opc-user-model.md` | 用户模型文件模板 | | `workspace/opc-user-model.md` | 用户实例(含历史5个项目数据)| ### 进化飞轮 ``` 项目越多 → 用户模型越丰富 → Phase 0 预判越准 → 用户越惊喜 → 做更多项目 ``` --- ## v5.0 (2026-03-19) — 六大专业化升级 > 基于 v4.0 实战后大仙的系统性反馈:触发不准、角色不稳、交付不够、复盘缺失。 ### 实战问题 | 问题 | 根因 | v5.0 解决方案 | |------|------|-------------| | OPC 触发时机不准确 | 触发条件是模糊文字 | 触发分级矩阵(L0-L3) | | 轻量任务走完整流程体验重 | 无自适应机制 | 自适应指挥模式 | | 角色卡质量不稳定 | 全靠 CEO 临场发挥 | 角色模板库(8个) | | 产出路径和格式不一致 | 无产出协议 | Output Contract | | 交付只有结果,缺少"接住感" | Phase 4 缺失 | Delivery Package | | 踩坑无法沉淀 | 无复盘机制 | Phase 5 Retrospective | ### Added - **playbook/roles/**(8个新文件)— 角色模板库 - researcher / engineer / writer / analyst / integrator - ux-designer / biz-analyst / critic - **playbook/templates/output-contract.yaml** — 产出协议模板 - **brain/core-flow.md Phase 4** — 交付包 Delivery Package - **brain/core-flow.md Phase 5** — 自动复盘 Retrospective ### Changed - **SKILL.md** — 触发分级矩阵(L0-L3)+ 自适应指挥规则 + 角色/Contract 引用 - **brain/core-flow.md** — 新增 Phase 4 + Phase 5 完整规范 - 版本号:4.0 → 5.0 ### Design Principles - **角色 = 岗位 + Persona 两个维度**:模板定义"做什么",Persona 定义"怎么思考",可自由组合 - **critic 角色**:内容质量审查(主观),区别于 verify(机器验收) - **交付包**:让用户"接住"结果,不只是"结果在这里" - **复盘飞轮**:每个项目的踩坑都沉淀到系统知识,OPC 越用越强 --- ## v5.1 (2026-03-19) — 任务拆解科学化 > 解决 v5.0 遗留的核心问题:任务拆解粒度没标准、依赖不显式、并行判断靠感觉。 ### Added - **engine/project_state.py `task-graph` 命令** — 声明/查看任务依赖图,自动识别可并行节点 - **brain/task-decomposition.md** — 四问框架 + 并行判断规则 + 粒度校验清单 - **playbook/templates/agent-prompt.md** — 标准任务描述六要素格式 + 四问自检 - **brain/collaboration-patterns.md** — task-graph 使用指南 ### Design Principles - **一个 Agent = 一个可独立验收的产出单元**(黄金原则) - **依赖图前置**:Phase 1 规划时就声明,不等到 spawn 时再想 - **并行有条件**:三个条件全满足才并行,否则默认串行 - **四问强制过**:spawn 前必须能回答四问,回答不出来就继续拆 --- ## v5.2 (2026-03-19) — 项目类型速启模板 + critic 铁律 > 大仙提出:无论什么项目类型,都必须有评价和反馈角色。 ### Design Decision **critic 是所有项目的强制项**: - 质量是 OPC 最后一道关,不能只靠 CEO 机器验收(verify) - verify 检查文件存在性和命令通过,critic 审查内容质量 - 评分 < 3 的产出不进交付包,打回重做 ### Added - **playbook/scenarios/research-project.yaml** — 深度研究项目速启模板 - **playbook/scenarios/engineering-project.yaml** — 工程开发项目速启模板 - **playbook/scenarios/content-project.yaml** — 内容创作项目速启模板 - **playbook/scenarios/_README.md** — 模板通用规则(critic 铁律声明) ### Changed - SKILL.md v5.2:新增速启模板速查表 + critic 铁律说明 --- ## v5.3 (2026-03-19) — gstack 三项借鉴 > 来源:Garry Tan (YC CEO) 的 gstack 开源项目分析,提炼三个可直接落地的机制。 ### Added - **brain/core-flow.md Phase 0 扩展** — 问题重构(Office Hours) - 三步:听痛点 → 挑战前提假设 → 提供 2-3 条路径 + 工作量估算 - L2/L3 任务必须执行,防止"用户说做X就做X"而忽略真实需求 - **engine/project_state.py `retro` 命令** — 数据驱动历史复盘 - 聚合:项目完成率、总 token、平均质量评分、角色使用频率、失败模式 - 支持 --days N / --type 过滤 - **brain/verification.md Iron Law 调试协议** — 不调查就不修复 - verify 失败 2 次 → 强制根因分析(RCA),不是重试 - verify 失败 3 次 → 强制用户介入,不再自主绕行 - 与 Phase 5 复盘衔接:失败模式 → retro 聚合分析 ### Philosophy gstack 与 OPC 的共同理念:**AI + 结构化角色 = 一个人的公司** gstack 专注于工程开发流水线(Claude Code),OPC 专注于通用多领域编排。 两者互补,思路相通。engine/aware-triggers.md7.5 KB0f64e9ea8b25upstream ↗
# Aware 触发器系统设计文档 > OPC v2.0 核心新增 — 声明式事件驱动,让项目"自己动起来" ## 概述 Aware 触发器系统让 OPC 项目具备**事件驱动能力**:定义好规则后,CEO 在 heartbeat 时调用 `evaluate()`,满足条件的触发器自动产生动作(spawn agent / 发通知 / 跑脚本)。 配合 Focus 系统,实现项目焦点的自适应管理——agent 全部完成时焦点自动关闭,关联的触发器自动停用。 ## 触发器类型 ### 1. cron — 定时触发 通过 `openclaw cron create` 注册系统级 cron 任务,按 cron 表达式定时执行。 ```yaml - id: daily-report type: cron schedule: "30 9 * * *" timezone: "Asia/Shanghai" action: type: spawn_agent agent_label: "report-writer" task: "生成并发送日报" ``` **注意**: cron 类型触发器在 `register_cron()` 时注册到 OpenClaw 系统,不由 `evaluate()` 检查(因为 cron 是系统级调度)。 ### 2. once — 一次性触发 到达指定时间后触发一次,然后自动标记 `fired: true`。 ```yaml - id: deadline-reminder type: once at: "2026-03-15T10:00:00+08:00" action: type: notify target: "daxiang" message: "KangaBase v0.2.0 deadline 到了" fired: false ``` ### 3. interval — 周期检查 每隔指定分钟数检查一次。适用于需要定期巡逻的场景。 ```yaml - id: status-check type: interval every_minutes: 30 action: type: run_script command: "python3 scripts/project_state.py show opc-20260311-001" ``` ### 4. on_message — 消息触发 当某个 agent 的输出包含特定关键词时触发。支持 contains / regex / exact 三种匹配模式。 ```yaml - id: phase-transition type: on_message from_agent: "core-engineer" contains: "Phase 1 完成" match_mode: "contains" action: type: spawn_agent agent_label: "doc-writer" task: "开始 Phase 2 文档编写" max_fires: 1 ``` **实现机制**: 通过 `subagents list` 获取最近完成的 agent 输出,逐行匹配。 ### 5. poll — 外部状态轮询 HTTP 轮询外部 API,检查特定字段的值。适用于监控 CI/CD、外部服务状态等。 ```yaml - id: ci-check type: poll url: "https://api.github.com/repos/owner/repo/actions/runs?per_page=1" check_path: "workflow_runs[0].conclusion" expected: "success" interval_minutes: 5 timeout_minutes: 60 action: type: notify target: "daxiang" message: "CI 构建成功" ``` ## triggers.yaml 完整 Schema ```yaml version: "1.0" triggers: - id: string # 唯一标识(必填) type: string # cron / once / interval / on_message / poll(必填) enabled: boolean # 是否启用(默认 true) focus_ref: string # 关联的 focus id(可选) # cron 专属 schedule: string # cron 表达式 timezone: string # 时区(默认 Asia/Shanghai) # once 专属 at: string # ISO 8601 时间 fired: boolean # 是否已触发(默认 false) # interval 专属 every_minutes: number # 间隔分钟数 last_fired: string # 上次触发时间(自动维护) # on_message 专属 from_agent: string # 来源 agent label(可选,不填则匹配所有) contains: string # 匹配关键词 match_mode: string # contains / regex / exact(默认 contains) max_fires: number # 最大触发次数(0=无限) # poll 专属 url: string # HTTP URL check_path: string # JSON 路径(如 "data.status") expected: string # 期望值 interval_minutes: number # 轮询间隔 timeout_minutes: number # 超时(0=不超时) # 动作定义(必填) action: type: string # spawn_agent / notify / run_script # spawn_agent: agent_label: string task: string # notify: target: string message: string # run_script: command: string ``` ## Focus 系统 Focus 代表项目中的"焦点"——当前需要关注的工作块。 ### 状态标记 | 标记 | 含义 | |------|------| | `[ ]` | 待办 | | `[/]` | 进行中 | | `[x]` | 完成 | | `[!]` | 阻塞 | ### focus.yaml Schema ```yaml version: "1.0" focus_items: - id: string # 唯一标识 title: string # 标题 status: string # [ ] / [/] / [x] / [!] priority: string # P0 / P1 / P2 agents: [string] # 关联的 agent label 列表 triggers: [string] # 关联的 trigger id 列表 auto_complete: boolean # 所有 agent 完成时自动标记 [x] recurring: boolean # 循环焦点(完成后重置为 [ ]) created: string # 创建时间 completed: string # 完成时间 ``` ## Focus 与 Trigger 联动机制 ``` Agent 完成 → agent-complete 写入 state.json ↓ 自动检查: 该 agent 关联的 focus → 所有 agent 都完成? ↓ 是 Focus 标记 [x] → 关联的 trigger 可按需停用 ↓ 如果是 recurring 重置为 [ ],继续下一轮循环 ``` **实现位置**: `project_state_v2.py` 的 `cmd_agent_complete()` 末尾自动调用 `FocusManager.check_auto_complete()`。 ## CEO 集成规范 ### 何时调用 evaluate() 1. **每次 heartbeat** 时调用一次 2. **收到 agent announce** 后调用(可能触发 on_message 类型) 3. **用户手动请求** "检查触发器" 时 ### CEO 工作流 ```python # heartbeat 中 actions = trigger_engine.evaluate() for action in actions: if action.action_type == "spawn_agent": # spawn sub-agent sessions_spawn(label=action.action_params["agent_label"], task=action.action_params["task"]) elif action.action_type == "notify": # 发送通知 message_send(target=action.action_params["target"], message=action.action_params["message"]) elif action.action_type == "run_script": # 执行脚本 exec(command=action.action_params["command"]) ``` ### 项目初始化时 ```bash # 1. 初始化项目 python3 project_state_v2.py init "项目名" # 2. 复制模板到项目目录 cp templates/triggers.yaml opc-projects/<pid>/triggers.yaml cp templates/focus.yaml opc-projects/<pid>/focus.yaml # 3. 编辑触发器和焦点配置 # 4. 注册 cron 类型触发器 python3 trigger_engine.py register-crons <project_dir> ``` ## 最佳实践 1. **触发器数量控制**: 单项目建议不超过 10 个触发器,避免评估开销过大 2. **interval 合理设置**: 最小间隔建议 5 分钟,避免频繁操作 3. **on_message 防重复**: 始终设置 `max_fires`,避免反复触发 4. **poll 设超时**: HTTP 轮询必须设 `timeout_minutes`,避免无限轮询 5. **Focus auto_complete**: 只有明确的交付型焦点才开启,探索型焦点手动管理 6. **cron vs interval**: 需要精确时间用 cron,需要相对间隔用 interval 7. **触发器状态持久化**: 通过 `trigger_state.json` 自动持久化,compaction 不影响 ## 命令行参考 ```bash # 评估触发器(在 heartbeat 中使用) python3 trigger_engine.py evaluate <project_dir> # 查看状态 python3 trigger_engine.py status <project_dir> # 手动触发 python3 trigger_engine.py fire <project_dir> <trigger_id> # 通过 project_state_v2 集成调用 python3 project_state_v2.py trigger-evaluate <project_id> python3 project_state_v2.py trigger-status <project_id> python3 project_state_v2.py focus-list <project_id> python3 project_state_v2.py focus-update <project_id> <focus_id> "[/]" ```engine/diagnose_agent.py8.2 KB02f4527d0764upstream ↗
#!/usr/bin/env python3 """ OPC Agent Failure Diagnosis — 自动归因工具 根据 agent 的 session history / 状态信息自动判断故障层级: L1 = OpenClaw 平台问题(spawn失败/announce丢失/session超时) L2 = OPC 编排问题(角色定义不清/prompt歧义/依赖管理错误) L3 = 业务 Skill 问题(API报错/认证过期/组件版本/浏览器交互) L4 = 外部依赖问题(网络/内部平台不可用) 用法: python3 diagnose_agent.py <symptoms_json> 示例: python3 diagnose_agent.py '{"spawn":"ok","announce":"missing","subagent_status":"done"}' python3 diagnose_agent.py '{"spawn":"ok","announce":"received","output_quality":"off_topic"}' python3 diagnose_agent.py '{"spawn":"ok","announce":"received","output_quality":"error","error_msg":"CDP connection refused"}' """ import json, sys, re # ─── 归因规则引擎 ─── RULES = [ # L1: Platform { "level": "L1", "name": "Spawn 失败", "condition": lambda s: s.get("spawn") == "error", "diagnosis": "OpenClaw 平台无法 spawn sub-agent", "action": "检查 OpenClaw 状态(openclaw status),确认 session 配额未满,尝试重新 spawn" }, { "level": "L1", "name": "Announce 丢失", "condition": lambda s: s.get("spawn") == "ok" and s.get("announce") == "missing" and s.get("subagent_status") == "done", "diagnosis": "Sub-agent 已完成(done)但 announce 未到达 Main Session", "action": "已知平台问题。用 sessions_history 主动拉取结果;后续所有 spawn 都要加超时检查" }, { "level": "L1", "name": "Session 超时", "condition": lambda s: s.get("subagent_status") == "timeout" or s.get("spawn") == "timeout", "diagnosis": "Sub-agent session 超时退出", "action": "增加 runTimeoutSeconds;检查任务是否过于复杂需要拆分" }, { "level": "L1", "name": "Session 异常终止", "condition": lambda s: s.get("subagent_status") == "error" and not s.get("error_msg"), "diagnosis": "Sub-agent 异常终止,无错误信息", "action": "检查 sessions_history 获取最后几条消息;可能是 context 溢出或 model 问题" }, # L2: Orchestration { "level": "L2", "name": "产出完全跑偏", "condition": lambda s: s.get("output_quality") == "off_topic", "diagnosis": "Sub-agent 完成了任务但产出与预期完全不符", "action": "角色卡定义不清或 task prompt 歧义。优化:1)明确角色职责边界 2)给出具体产出示例 3)增加约束条件" }, { "level": "L2", "name": "产出方向对但质量差", "condition": lambda s: s.get("output_quality") == "low_quality", "diagnosis": "产出方向正确但深度/格式/完整性不够", "action": "1)task描述增加详细要求 2)考虑使用更强model 3)Persona Priming注入专家方法论" }, { "level": "L2", "name": "产出格式不符", "condition": lambda s: s.get("output_quality") == "wrong_format", "diagnosis": "产出内容OK但格式不符合 OPC 规范", "action": "在 task prompt 中增加明确的产出格式示例和 JSON Schema" }, { "level": "L2", "name": "依赖任务未完成就启动", "condition": lambda s: s.get("dependency_error") == True, "diagnosis": "上游任务未完成就 spawn 了下游 agent", "action": "检查编排流程中的依赖检查逻辑,确保串行依赖严格等待" }, # L3: Business Skill { "level": "L3", "name": "API/认证错误", "condition": lambda s: s.get("error_msg") and any(kw in s["error_msg"].lower() for kw in ["auth", "401", "403", "token", "cookie", "sso", "login", "credential", "认证", "登录", "过期", "授权"]), "diagnosis": "业务 API 认证失败或过期", "action": "1)检查 SSO cookie/token 是否过期 2)重新执行认证流程 3)确认 MOA 登录状态" }, { "level": "L3", "name": "浏览器交互失败", "condition": lambda s: s.get("error_msg") and any(kw in s["error_msg"].lower() for kw in ["cdp", "browser", "click", "selector", "element", "timeout", "date", "picker", "mouse", "tab", "日期", "选择器", "超时", "浏览器", "点击", "交互"]), "diagnosis": "浏览器自动化交互失败(CDP/选择器/元素定位)", "action": "1)检查浏览器是否正常运行(curl localhost:9222) 2)Tab竞争?串行化操作 3)元素定位变化?更新选择器" }, { "level": "L3", "name": "组件版本/配置错误", "condition": lambda s: s.get("error_msg") and any(kw in s["error_msg"].lower() for kw in ["component", "version", "snapshot", "props", "schema", "validate", "组件", "版本", "配置"]), "diagnosis": "高达组件版本不匹配或配置参数错误", "action": "1)检查 components-index.json 版本 2)用 query_components.py 验证最新版本 3)检查 props 格式" }, { "level": "L3", "name": "脚本执行错误", "condition": lambda s: s.get("error_msg") and any(kw in s["error_msg"].lower() for kw in ["script", "node", "python", "syntax", "import", "module", "traceback"]), "diagnosis": "业务脚本执行报错", "action": "检查脚本输出日志,定位具体报错行;可能是环境依赖缺失或参数传递错误" }, # L4: External { "level": "L4", "name": "网络/外部服务不可用", "condition": lambda s: s.get("error_msg") and any(kw in s["error_msg"].lower() for kw in ["network", "dns", "connection refused", "unreachable", "502", "503", "504", "econnreset", "网络", "连接"]), "diagnosis": "外部网络或服务不可用", "action": "1)检查网络连通性 2)确认目标服务状态 3)等待恢复后重试" }, # Catch-all { "level": "L?", "name": "未知错误", "condition": lambda s: True, "diagnosis": "无法自动归因", "action": "手动检查 sessions_history 获取详细日志,人工归因" } ] def diagnose(symptoms: dict) -> dict: """对 symptoms 运行规则引擎,返回第一个匹配的诊断""" for rule in RULES: try: if rule["condition"](symptoms): return { "level": rule["level"], "name": rule["name"], "diagnosis": rule["diagnosis"], "action": rule["action"], "symptoms": symptoms } except Exception: continue return {"level": "L?", "name": "未知", "diagnosis": "无法诊断", "action": "人工检查", "symptoms": symptoms} def diagnose_multi(symptoms: dict) -> list: """返回所有匹配的诊断(不含 catch-all)""" results = [] for rule in RULES: if rule["name"] == "未知错误": continue try: if rule["condition"](symptoms): results.append({ "level": rule["level"], "name": rule["name"], "diagnosis": rule["diagnosis"], "action": rule["action"] }) except Exception: continue if not results: results.append(diagnose(symptoms)) return results def format_report(results: list, symptoms: dict) -> str: lines = ["═══ OPC 故障诊断报告 ═══", ""] lines.append(f"症状: {json.dumps(symptoms, ensure_ascii=False)}") lines.append("") for i, r in enumerate(results, 1): icon = {"L1":"🔴","L2":"🟡","L3":"🟠","L4":"⚪"}.get(r["level"],"❓") lines.append(f"诊断 {i}: {icon} [{r['level']}] {r['name']}") lines.append(f" 原因: {r['diagnosis']}") lines.append(f" 建议: {r['action']}") lines.append("") return "\n".join(lines) if __name__ == "__main__": if len(sys.argv) < 2: print(__doc__) sys.exit(1) symptoms = json.loads(sys.argv[1]) results = diagnose_multi(symptoms) print(format_report(results, symptoms))engine/project-state.md3.9 KB424a8680bbf5upstream ↗
# OPC Project State Manager OPC 项目状态持久化管理器,解决 compaction 导致执行状态丢失的问题。 ## 设计原则 1. **每个 Phase 完成后自动持久化** - 写入 `workspace/opc-projects/{project-id}/state.json` 2. **Compaction 后自动恢复** - CEO 启动时检查 state.json,恢复项目上下文 3. **断点续传** - Sub-agent 失败后可从断点继续,而非完全重试 ## 状态文件结构 ```json { "project": { "id": "opc-20260311-001", "name": "愚人节三会场搭建", "createdAt": "2026-03-10T18:33:00Z", "updatedAt": "2026-03-10T18:45:00Z", "currentPhase": "phase_2_execution", "status": "in_progress" }, "plan": { "okr": "KR: 4.1愚人节活动上线", "epics": ["..."] }, "agents": { "builder-main": { "role": "主会场搭建员", "status": "completed", "startedAt": "2026-03-10T18:40:00Z", "finishedAt": "2026-03-10T18:45:00Z", "output": { "activityId": "1014813", "url": "..." }, "tokens": 45000 }, "builder-waimai": { "role": "外卖分会场搭建员", "status": "completed", "startedAt": "2026-03-10T18:40:00Z", "finishedAt": "2026-03-10T18:47:00Z", "output": { "activityId": "1014814", "url": "..." }, "tokens": 52000 }, "builder-dcan": { "role": "到餐分会场搭建员", "status": "failed", "startedAt": "2026-03-10T18:40:00Z", "failedAt": "2026-03-10T18:57:00Z", "error": "日期选择器交互超时", "checkpoint": { "phase": "component_added", "completedSteps": ["create_activity", "add_header", "add_coupon"], "lastStep": "set_date_range" }, "retryCount": 1 } }, "checkpoints": { "builder-dcan": { "phase": "component_added", "completedSteps": ["create_activity", "add_header", "add_coupon"], "context": { "activityId": "1014818", "components": ["..."] } } }, "cost": { "totalTokens": 97000, "byRole": { "策划员": 35000, "搭建员": 62000 }, "budgetLimit": 150000, "budgetUsedPercent": 65 } } ``` ## 目录结构 ``` workspace/opc-projects/ └── {project-id}/ ├── state.json # 项目状态(自动生成) ├── plan.md # 项目计划 ├── outputs/ # Sub-agent 产出 │ ├── planner.md # 策划员产出 │ ├── builder-main.md # 主会场搭建产出 │ └── ... └── logs/ # 执行日志 ``` ## CEO 集成规范 ### Phase 完成后必须调用 ``` Phase 1(项目规划)完成 → project_state.py update-phase <id> phase_1_completed Phase 2(团队组建)完成 → project_state.py update-phase <id> phase_2_started Phase 3(执行监控)完成 → project_state.py update-phase <id> phase_3_completed Phase 4(交付汇总)完成 → project_state.py update-phase <id> completed ``` ### Agent 状态变更必须同步 ``` spawn agent → agent-start agent announce done → agent-complete agent announce error → agent-fail(同时保存 checkpoint) ``` ### Compaction 恢复流程 ``` 1. CEO 启动时检查 workspace/opc-projects/ 2. 找到未完成项目(status != completed) 3. 调用 restore <id> 获取状态摘要 4. 继续执行剩余任务 ``` ## 断点续传规范 ### 何时保存断点 - Agent 失败时 - Agent 被 kill 前 - 长时间无响应(>10min)被标记为可疑时 ### 断点内容 断点必须包含: 1. **completedSteps**: 已完成的步骤列表(顺序) 2. **context**: 关键上下文(活动ID、组件树状态、配置参数) 3. **nextStep**: 下一步要做什么 ### 断点续传 prompt 恢复 agent 时,注入断点信息: ``` [断点续传] 上一个 agent 因以下原因失败:{error} 已完成步骤:{completedSteps} 当前上下文:{context} 请从以下步骤继续:{nextStep} ```engine/project_state.py28 KB20d6bece6f4aupstream ↗
#!/usr/bin/env python3 """ OPC Project State Manager v2.0 — 在 v1.4 基础上扩展 Trigger + Focus + ToolScan 命令 新增命令: python3 project_state_v2.py trigger-evaluate <project_id> # 评估所有触发器 python3 project_state_v2.py trigger-status <project_id> # 查看触发器状态 python3 project_state_v2.py focus-update <project_id> <id> <status> # 更新焦点状态 python3 project_state_v2.py focus-list <project_id> # 列出活跃焦点 python3 project_state_v2.py tool-scan <task_description> # 扫描推荐工具 保持所有 v1.4 原有命令不变(init/show/list/agent-start/agent-complete/...)。 使用方式:将此文件替换或合并到原 project_state.py 中。 """ import json, sys, os, glob from datetime import datetime, timezone, timedelta TZ = timezone(timedelta(hours=8)) BASE_DIR = os.path.expanduser("~/.openclaw/workspace/opc-projects") SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__)) def _now(): return datetime.now(TZ).isoformat(timespec="seconds") def _today(): return datetime.now(TZ).strftime("%Y%m%d") def _project_dir(pid): return os.path.join(BASE_DIR, pid) def _state_path(pid): return os.path.join(_project_dir(pid), "state.json") def _load(pid): p = _state_path(pid) if not os.path.exists(p): print(f"❌ 项目 {pid} 不存在") sys.exit(1) with open(p) as f: return json.load(f) def _save(pid, data): data["project"]["updatedAt"] = _now() d = _project_dir(pid) os.makedirs(d, exist_ok=True) os.makedirs(os.path.join(d, "outputs"), exist_ok=True) os.makedirs(os.path.join(d, "logs"), exist_ok=True) with open(_state_path(pid), "w") as f: json.dump(data, f, indent=2, ensure_ascii=False) # ═══════════════════════════════════════════════════════════════ # v1.4 原有命令(保持不变) # ═══════════════════════════════════════════════════════════════ def cmd_init(name, date=None): date_str = date or _today() seq = 1 while True: pid = f"opc-{date_str}-{seq:03d}" if not os.path.exists(_project_dir(pid)): break seq += 1 data = { "project": { "id": pid, "name": name, "createdAt": _now(), "updatedAt": _now(), "currentPhase": "phase_0_init", "status": "created" }, "plan": {}, "agents": {}, "checkpoints": {}, "cost": {"totalTokens": 0, "byRole": {}, "budgetLimit": 0, "budgetUsedPercent": 0} } _save(pid, data) print(f"✅ 项目初始化: {pid} — {name}") print(f" 路径: {_project_dir(pid)}") return pid def cmd_update_phase(pid, phase): data = _load(pid) old = data["project"]["currentPhase"] data["project"]["currentPhase"] = phase if phase in ("completed", "cancelled"): data["project"]["status"] = phase elif phase.startswith("phase_"): data["project"]["status"] = "in_progress" _save(pid, data) print(f"✅ Phase: {old} → {phase}") def cmd_agent_start(pid, label, meta_json): data = _load(pid) meta = json.loads(meta_json) if meta_json else {} data["agents"][label] = { "role": meta.get("role", label), "status": "active", "startedAt": _now(), "sessionKey": meta.get("sessionKey", ""), "tokens": 0, "output": None, "error": None } _save(pid, data) print(f"✅ Agent started: {label} ({meta.get('role', label)})") def cmd_agent_complete(pid, label, output_json, tokens=0): data = _load(pid) if label not in data["agents"]: data["agents"][label] = {"role": label, "status": "active", "startedAt": _now(), "tokens": 0} agent = data["agents"][label] agent["status"] = "completed" agent["finishedAt"] = _now() agent["output"] = json.loads(output_json) if output_json else {} tokens = int(tokens) if tokens: agent["tokens"] = tokens role = agent.get("role", label) data["cost"]["byRole"].setdefault(role, 0) data["cost"]["byRole"][role] += tokens data["cost"]["totalTokens"] += tokens if data["cost"]["budgetLimit"] > 0: data["cost"]["budgetUsedPercent"] = round( data["cost"]["totalTokens"] / data["cost"]["budgetLimit"] * 100, 1) data["checkpoints"].pop(label, None) _save(pid, data) # v2.0: 自动检查 Focus 是否可以 auto-complete _check_focus_auto_complete(pid, data) print(f"✅ Agent completed: {label} (tokens: {tokens})") def cmd_agent_fail(pid, label, error_json): data = _load(pid) if label not in data["agents"]: data["agents"][label] = {"role": label, "status": "active", "startedAt": _now(), "tokens": 0} agent = data["agents"][label] err = json.loads(error_json) if error_json else {} agent["status"] = "failed" agent["failedAt"] = _now() agent["error"] = err.get("error", str(err)) agent["retryCount"] = agent.get("retryCount", 0) + 1 _save(pid, data) print(f"❌ Agent failed: {label} — {agent['error']}") def cmd_checkpoint(pid, label, cp_json): data = _load(pid) cp = json.loads(cp_json) if cp_json else {} cp["savedAt"] = _now() data["checkpoints"][label] = cp _save(pid, data) print(f"💾 Checkpoint saved: {label}") def cmd_checkpoint_get(pid, label): data = _load(pid) cp = data.get("checkpoints", {}).get(label) if not cp: print(f"⚠️ 无断点: {label}") return print(json.dumps(cp, indent=2, ensure_ascii=False)) def cmd_restore(pid): data = _load(pid) p = data["project"] print(f"═══ 项目恢复: {p['id']} ═══") print(f"名称: {p['name']}") print(f"状态: {p['status']} | 阶段: {p['currentPhase']}") print(f"更新: {p['updatedAt']}") print("\n── Agent ──") for label, ag in data.get("agents", {}).items(): icon = {"completed":"✅","active":"🔄","failed":"❌"}.get(ag["status"],"❓") print(f" {icon} {label} ({ag.get('role','')}) — {ag['status']}") cps = data.get("checkpoints", {}) if cps: print("\n── 断点 ──") for label, cp in cps.items(): print(f" 💾 {label}: steps={cp.get('completedSteps',[])} next={cp.get('nextStep','?')}") c = data.get("cost", {}) if c.get("totalTokens", 0): print(f"\n── 成本 ── total: {c['totalTokens']//1000}K tokens") return data def cmd_show(pid=None): if pid: data = _load(pid) print(json.dumps(data, indent=2, ensure_ascii=False)) else: cmd_list() def cmd_list(): if not os.path.exists(BASE_DIR): print("无项目") return dirs = sorted(glob.glob(os.path.join(BASE_DIR, "opc-*"))) if not dirs: print("无项目") return print(f"{'ID':<22} {'Name':<30} {'Phase':<25} {'Status':<12}") print("─" * 90) for d in dirs: sp = os.path.join(d, "state.json") if not os.path.exists(sp): continue with open(sp) as f: data = json.load(f) p = data["project"] print(f"{p['id']:<22} {p['name']:<30} {p['currentPhase']:<25} {p['status']:<12}") def cmd_cost(pid, add_tokens=None, agent_label=None): data = _load(pid) if add_tokens: tokens = int(add_tokens) label = agent_label or "ceo" data["cost"]["totalTokens"] += tokens data["cost"]["byRole"].setdefault(label, 0) data["cost"]["byRole"][label] += tokens if data["cost"]["budgetLimit"] > 0: data["cost"]["budgetUsedPercent"] = round( data["cost"]["totalTokens"] / data["cost"]["budgetLimit"] * 100, 1) _save(pid, data) print(f"✅ 成本更新: +{tokens} ({label})") c = data["cost"] total = c["totalTokens"] print(f"\n📊 {data['project']['name']} 成本报告") print(f"{'Role':<20} {'Tokens':<12} {'Cost':<10}") print("─" * 42) for role, t in c.get("byRole", {}).items(): cost = t * 2.5 / 1_000_000 print(f"{role:<20} {t//1000}K{'':<8} ${cost:.3f}") total_cost = total * 2.5 / 1_000_000 print("─" * 42) print(f"{'Total':<20} {total//1000}K{'':<8} ${total_cost:.3f}") def cmd_close(pid): data = _load(pid) data["project"]["status"] = "completed" data["project"]["currentPhase"] = "completed" data["project"]["closedAt"] = _now() _save(pid, data) print(f"✅ 项目已关闭: {pid}") def cmd_diagnose(pid): data = _load(pid) failed = {k:v for k,v in data.get("agents",{}).items() if v["status"] == "failed"} if not failed: print("✅ 无失败 agent") return import importlib.util diag_path = os.path.join(os.path.dirname(__file__), "diagnose_agent.py") if not os.path.exists(diag_path): print("⚠️ diagnose_agent.py 未找到,跳过自动归因") return spec = importlib.util.spec_from_file_location("diagnose_agent", diag_path) diag = importlib.util.module_from_spec(spec) spec.loader.exec_module(diag) for label, ag in failed.items(): print(f"\n{'═'*50}") print(f"🔍 归因: {label} ({ag.get('role','')})") error = ag.get("error", "") symptoms = {"spawn":"ok","announce":"received","output_quality":"error","error_msg":str(error)} results = diag.diagnose_multi(symptoms) print(diag.format_report(results, symptoms)) # ═══════════════════════════════════════════════════════════════ # v2.0 新增命令 # ═══════════════════════════════════════════════════════════════ def _get_trigger_engine(pid): """延迟导入 trigger_engine 模块""" trigger_path = os.path.join(SCRIPTS_DIR, "trigger_engine.py") if not os.path.exists(trigger_path): print(f"❌ trigger_engine.py 未找到: {trigger_path}") sys.exit(1) import importlib.util spec = importlib.util.spec_from_file_location("trigger_engine", trigger_path) mod = importlib.util.module_from_spec(spec) import sys as _sys _sys.modules["trigger_engine"] = mod spec.loader.exec_module(mod) return mod.TriggerEngine(_project_dir(pid)), mod.FocusManager(_project_dir(pid)) def _get_tool_discovery(): """延迟导入 tool_discovery 模块""" td_path = os.path.join(SCRIPTS_DIR, "tool_discovery.py") if not os.path.exists(td_path): print(f"❌ tool_discovery.py 未找到: {td_path}") sys.exit(1) import importlib.util spec = importlib.util.spec_from_file_location("tool_discovery", td_path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod.ToolDiscovery() def _check_focus_auto_complete(pid, data): """agent 完成时自动检查 Focus 是否可以 auto-complete""" try: _, fm = _get_trigger_engine(pid) agent_statuses = { label: ag["status"] for label, ag in data.get("agents", {}).items() } completed = fm.check_auto_complete(agent_statuses) if completed: print(f"🎯 Focus 自动完成: {completed}") except Exception: pass # 静默失败,不影响核心流程 def cmd_trigger_evaluate(pid): """评估项目下所有触发器""" engine, _ = _get_trigger_engine(pid) actions = engine.evaluate() if not actions: print("✅ 无待执行动作") return print(f"🔔 {len(actions)} 个触发器就绪:\n") for a in actions: print(f" ▶ {a.trigger_id} — {a.action_type}") print(f" 参数: {json.dumps(a.action_params, ensure_ascii=False)}") if a.focus_ref: print(f" 焦点: {a.focus_ref}") print() # Also JSON output from dataclasses import asdict print("--- JSON ---") print(json.dumps([asdict(a) for a in actions], ensure_ascii=False, indent=2)) def cmd_trigger_status(pid): """查看项目下所有触发器状态""" engine, _ = _get_trigger_engine(pid) st = engine.status() if not st: print("无触发器定义") return print(f"{'ID':<22} {'Type':<12} {'Enabled':<8} {'Fired':<6} {'Count':<6} {'Last Fired':<22}") print("─" * 78) for tid, info in st.items(): enabled = "✅" if info["enabled"] else "❌" fired = "✓" if info["fired"] else "✗" last = info.get("last_fired", "-") or "-" print(f"{tid:<22} {info['type']:<12} {enabled:<8} {fired:<6} {info['fire_count']:<6} {last:<22}") def cmd_focus_update(pid, focus_id, status): """更新焦点状态""" _, fm = _get_trigger_engine(pid) fm.update_status(focus_id, status) def cmd_focus_list(pid): """列出活跃焦点""" _, fm = _get_trigger_engine(pid) active = fm.get_active_focuses() if not active: print("无活跃焦点") return print(f"{'ID':<24} {'Title':<30} {'Status':<8} {'Priority':<8}") print("─" * 72) for f in active: print(f"{f.get('id','?'):<24} {f.get('title',''):<30} {f.get('status','?'):<8} {f.get('priority',''):<8}") def cmd_tool_scan(task_description): """扫描推荐工具""" td = _get_tool_discovery() report = td.generate_tool_report(task_description) print(report) # ═══════════════════════════════════════════════════════════════ # v4.0 新增命令 # ═══════════════════════════════════════════════════════════════ def cmd_verify(pid, label, verify_cmd): """CEO 自主验收:执行验收命令,记录结果到 project_state。返回 0=通过, 非0=失败""" import subprocess data = _load(pid) ag = data.get("agents", {}).get(label) print(f"🔍 验收 [{label}]: {verify_cmd}") try: result = subprocess.run( verify_cmd, shell=True, capture_output=True, text=True, timeout=120 ) passed = result.returncode == 0 output_tail = (result.stdout + result.stderr).strip()[-500:] status_str = "✅ 通过" if passed else "❌ 失败" print(f"{status_str} (exit {result.returncode})") if output_tail: print(output_tail) if ag: if "verifications" not in ag: ag["verifications"] = [] ag["verifications"].append({ "cmd": verify_cmd, "passed": passed, "exitCode": result.returncode, "tail": output_tail[:300], "ts": _now(), }) ag["lastVerifyPassed"] = passed data["agents"][label] = ag _save(pid, data) return 0 if passed else 1 except subprocess.TimeoutExpired: print("⏱️ 验收命令超时(120s)") return 2 except Exception as e: print(f"❌ 验收命令出错: {e}") return 3 def cmd_retro(args): """数据驱动的历史项目统计复盘(灵感来源:gstack /retro) 用法: retro — 全量历史统计 retro --days 7 — 最近 N 天 retro --type research — 按项目类型过滤 """ import glob, datetime days_filter = None type_filter = None for i, a in enumerate(args): if a == "--days" and i + 1 < len(args): days_filter = int(args[i + 1]) if a == "--type" and i + 1 < len(args): type_filter = args[i + 1].lower() state_dir = BASE_DIR if not os.path.exists(state_dir): print('无项目数据') return files = glob.glob(os.path.join(state_dir, "*/state.json")) projects = [] for f in files: try: with open(f) as fh: raw = json.load(fh) proj = raw.get("project", raw) # 兼容嵌套结构 # 日期过滤 created = proj.get("createdAt", proj.get("created", "")) if days_filter and created: try: created_dt = datetime.datetime.strptime(created[:10], "%Y-%m-%d") if (datetime.datetime.now() - created_dt).days > days_filter: continue except Exception: pass # 类型过滤 name = proj.get("name", "").lower() if type_filter and type_filter not in name: continue # 规范化字段 cost = raw.get("cost", {}) data = { "id": proj.get("id", "?"), "name": proj.get("name", "?"), "status": proj.get("status", "?"), "created": created, "total_tokens": cost.get("totalTokens", 0), "agents": raw.get("agents", {}), "retrospective": raw.get("retrospective", {}), } projects.append(data) except Exception: continue if not projects: print("无项目数据") return # 统计 total = len(projects) completed = sum(1 for p in projects if p.get("status") == "completed") total_tokens = sum(p.get("total_tokens", 0) for p in projects) quality_scores = [p.get("retrospective", {}).get("quality_score", 0) for p in projects if p.get("retrospective", {}).get("quality_score")] avg_quality = sum(quality_scores) / len(quality_scores) if quality_scores else None # 角色使用统计 role_counts = {} for p in projects: for agent in p.get("agents", {}).values(): role = agent.get("role", "unknown") role_counts[role] = role_counts.get(role, 0) + 1 # 失败模式 fail_patterns = [] for p in projects: fp = p.get("retrospective", {}).get("failure_patterns", []) fail_patterns.extend(fp if isinstance(fp, list) else [fp] if fp else []) print(f"\n📊 OPC Retro Report") print(f"{'━' * 40}") print(f"项目总数: {total}") print(f"已完成: {completed} ({int(completed/total*100) if total else 0}%)") print(f"总 Token: ~{total_tokens//1000}K") if avg_quality: print(f"平均质量评分: {avg_quality:.1f}/5") print(f"\n🎭 角色使用频率 (Top 5):") for role, count in sorted(role_counts.items(), key=lambda x: -x[1])[:5]: bar = "█" * count print(f" {role:<20} {bar} ({count})") print(f"\n⚠️ 失败模式 (最近 {len(fail_patterns)} 条):") for fp in fail_patterns[-5:]: print(f" • {fp}") print(f"\n📈 项目列表 (最近 10):") recent = sorted(projects, key=lambda p: p.get("created", ""), reverse=True)[:10] for p in recent: status_icon = "✅" if p.get("status") == "completed" else "🔄" if p.get("status") == "active" else "❄️" tokens = p.get("total_tokens", 0) qs = p.get("retrospective", {}).get("quality_score", "-") print(f" {status_icon} {p.get('id','?')[:20]:<22} {p.get('name','')[:30]:<32} ~{tokens//1000}K tok Q:{qs}") def cmd_task_graph(args): """声明或查看项目任务依赖图 用法: task-graph <pid> show — 显示当前依赖图 task-graph <pid> add <label> <depends_on_csv> <output_path> 依赖用逗号分隔,无依赖传空串: task-graph <pid> add researcher_b "" reports/b.md """ if len(args) < 2: print("用法: task-graph <pid> show|add ...") return pid, action = args[0], args[1] state = _load(pid) graph = state.get("task_graph", {}) if action == "show": if not graph: print("(无依赖图声明)") return print(f"\n任务依赖图 [{pid}]:") for label, info in graph.items(): deps = info.get("depends_on", []) out = info.get("output", "?") can_parallel = "并行✅" if not deps else f"串行❌ 依赖: {deps}" print(f" {label}: {can_parallel} → {out}") # 并行组 parallel = [l for l, i in graph.items() if not i.get("depends_on")] if parallel: print(f"\n 可并行启动: {parallel}") elif action == "add": if len(args) < 5: print("用法: task-graph <pid> add <label> <depends_on_csv> <output_path>") return label = args[2] depends_csv = args[3] output = args[4] depends = [d.strip() for d in depends_csv.split(",") if d.strip()] if depends_csv else [] graph[label] = {"depends_on": depends, "output": output} state["task_graph"] = graph _save(pid, state) dep_str = f"依赖 {depends}" if depends else "无依赖(可并行)" print(f"✅ [{label}] {dep_str} → {output}") else: print(f"未知 action: {action}") def cmd_wake_frozen(): """扫描所有 OPC 项目,找出冻结/暂停的项目,给出唤醒建议""" import time as _time import json as _json base = os.path.join(os.path.expanduser("~"), ".openclaw", "workspace", "opc-projects") if not os.path.isdir(base): print("ℹ️ opc-projects/ 目录不存在,无冻结项目。") return frozen, stale = [], [] now_ms = _time.time() * 1000 for pid in sorted(os.listdir(base)): state_file = os.path.join(base, pid, "state.json") if not os.path.exists(state_file): continue try: with open(state_file) as f: data = _json.load(f) proj = data.get("project", data) # fallback to top-level for old schema phase = proj.get("currentPhase", "") status = proj.get("status", "") if phase in ("completed", "closed") or status in ("completed", "closed"): continue updated = proj.get("updatedAt", proj.get("createdAt", 0)) if isinstance(updated, str) or updated == 0: updated = os.path.getmtime(state_file) * 1000 paused_h = (now_ms - float(updated)) / 3_600_000 name = proj.get("name", pid) entry = {"pid": pid, "name": name, "phase": phase, "paused_h": paused_h} (stale if paused_h > 24 else frozen).append(entry) except Exception: continue if not frozen and not stale: print("✅ 无冻结项目。") return if frozen: print(f"\n📌 发现 {len(frozen)} 个冻结项目(暂停 < 24h):") for e in frozen: print(f" [{e['pid']}] {e['name']} — {e['phase']},已暂停 {e['paused_h']:.1f}h") print(" → restore <pid> 恢复上下文,或通知用户确认是否继续\n") if stale: print(f"\n🗄️ 发现 {len(stale)} 个 stale 项目(暂停 > 24h,不自动唤醒):") for e in stale: print(f" [{e['pid']}] {e['name']} — {e['phase']},已暂停 {e['paused_h']:.1f}h") print(" 等待用户明确指示后再处理。\n") # ═══════════════════════════════════════════════════════════════ # Main dispatcher # ═══════════════════════════════════════════════════════════════ USAGE = """ OPC Project State Manager v2.0 v1.4 命令: init <name> [date] — 初始化项目 update-phase <pid> <phase> — 更新阶段 agent-start <pid> <label> [meta_json] — 注册 agent agent-complete <pid> <label> [json] [tokens] — agent 完成 agent-fail <pid> <label> [error_json] — agent 失败 checkpoint <pid> <label> [json] — 保存断点 checkpoint-get <pid> <label> — 获取断点 restore <pid> — 恢复项目上下文 show [pid] — 查看项目 / 项目列表 list — 列出所有项目 cost <pid> [tokens] [label] — 成本报告 / 追加成本 diagnose <pid> — 自动归因 close <pid> — 关闭项目 v2.0 新增命令: trigger-evaluate <pid> — 评估所有触发器 trigger-status <pid> — 查看触发器状态 focus-update <pid> <id> <status> — 更新焦点状态 ([ ] [/] [x] [!]) focus-list <pid> — 列出活跃焦点 tool-scan <task_description> — 扫描推荐工具 v4.0 新增命令: verify <pid> <label> "<cmd>" — CEO 自主验收:执行命令,记录结果 wake-frozen — 扫描冻结/暂停项目,输出唤醒建议 """ if __name__ == "__main__": args = sys.argv[1:] if not args or args[0] in ("--help", "-h"): print(USAGE) sys.exit(0) cmd = args[0] # ── v1.4 commands ── if cmd == "init": cmd_init(args[1] if len(args) > 1 else "unnamed", args[2] if len(args) > 2 else None) elif cmd == "update-phase": cmd_update_phase(args[1], args[2]) elif cmd == "agent-start": cmd_agent_start(args[1], args[2], args[3] if len(args) > 3 else "{}") elif cmd == "agent-complete": cmd_agent_complete(args[1], args[2], args[3] if len(args) > 3 else "{}", args[4] if len(args) > 4 else 0) elif cmd == "agent-fail": cmd_agent_fail(args[1], args[2], args[3] if len(args) > 3 else "{}") elif cmd == "checkpoint": cmd_checkpoint(args[1], args[2], args[3] if len(args) > 3 else "{}") elif cmd == "checkpoint-get": cmd_checkpoint_get(args[1], args[2]) elif cmd == "restore": cmd_restore(args[1]) elif cmd == "show": cmd_show(args[1] if len(args) > 1 else None) elif cmd == "list": cmd_list() elif cmd in ("cost", "report"): cmd_cost(args[1], args[2] if len(args) > 2 else None, args[3] if len(args) > 3 else None) elif cmd == "diagnose": cmd_diagnose(args[1]) elif cmd == "close": cmd_close(args[1]) # ── v2.0 new commands ── elif cmd == "trigger-evaluate": if len(args) < 2: print("用法: trigger-evaluate <project_id>") sys.exit(1) cmd_trigger_evaluate(args[1]) elif cmd == "trigger-status": if len(args) < 2: print("用法: trigger-status <project_id>") sys.exit(1) cmd_trigger_status(args[1]) elif cmd == "focus-update": if len(args) < 4: print("用法: focus-update <project_id> <focus_id> <status>") print(" status: [ ] / [/] / [x] / [!]") sys.exit(1) cmd_focus_update(args[1], args[2], args[3]) elif cmd == "focus-list": if len(args) < 2: print("用法: focus-list <project_id>") sys.exit(1) cmd_focus_list(args[1]) elif cmd == "tool-scan": if len(args) < 2: print("用法: tool-scan <task_description>") sys.exit(1) cmd_tool_scan(" ".join(args[1:])) # ── v4.0 new commands ── elif cmd == "verify": if len(args) < 4: print("用法: verify <pid> <label> \"<verify_cmd>\"") sys.exit(1) rc = cmd_verify(args[1], args[2], " ".join(args[3:])) sys.exit(rc) elif cmd == "wake-frozen": cmd_wake_frozen() elif cmd == "task-graph": cmd_task_graph(args[1:]) elif cmd == "retro": cmd_retro(args[1:]) else: print(f"未知命令: {cmd}") print(USAGE) sys.exit(1)engine/tool-discovery.md4.2 KBa2a475e99befupstream ↗
# 运行时工具自发现机制设计文档 > OPC v2.0 核心新增 — 任务启动前自动发现可用工具,弥补能力缺口 ## 概述 工具自发现系统在 CEO 规划任务时自动扫描可用 Skill,将任务需求与工具能力匹配,生成推荐报告。目标:**永远不要因为"不知道有这个工具"而手动操作**。 ## 工具发现流程 ``` CEO 收到任务 ↓ Phase 0: 工具扫描 ├── 1. 扫描本地已安装 Skill ├── 2. 任务描述 ↔ Skill 描述 关键词匹配 ├── 3. 生成匹配报告 └── 4. 如有能力缺口 → 推荐搜索外部源 ↓ Phase 1: 正常项目规划(带工具建议) ``` ## 搜索源优先级 | 优先级 | 源 | 说明 | |--------|------|------| | 1 | 本地已安装 | `~/.openclaw/skills/` + `/app/skills/` | | 2 | Friday Skill 广场 | 美团内部官方 Skill(需 SSO) | | 3 | ClawHub | 社区公开 Skill(需安全审计) | **规则**: 优先使用本地已安装的 Skill。外部 Skill 仅作为建议,安装需 CEO 确认。 ## 安全策略 ### 原则:安全优先,仅推荐官方源 1. **本地 Skill**: 已安装即已信任,直接推荐 2. **Friday 官方 Skill**: 经公司审核,推荐安装 3. **ClawHub 社区 Skill**: 推荐前需经过安全初筛(`check_skill_safety()`) 4. **安装确认**: 任何新 Skill 安装必须经 CEO(即用户)明确确认 5. **不自动安装**: 系统只推荐,不自动执行安装 ### 安全初筛(快速检查) `tool_discovery.py check <skill_path>` 执行以下检查: - SKILL.md 是否存在 - 文件中是否包含可疑命令模式(curl+token、rm -rf /、nc -e 等) - 是否引用敏感路径(openclaw.json、device-auth.json 等) **注意**: 这只是初筛。完整安全审计应使用 `skill-vetter` Skill。 ## CEO 集成规范 ### 何时调用 1. **项目 Phase 0**(规划前): 自动执行工具扫描 2. **用户显式请求**: "帮我找个能做 X 的工具" 3. **任务分配时**: 为 Sub-agent 推荐可用工具 ### CEO 工作流 ```python # Phase 0: 工具扫描 report = tool_discovery.generate_tool_report(task_description) # 在项目规划中包含工具建议 # 分配任务时 matches = tool_discovery.match_task_to_tools(sub_task, local_skills) if matches: # 在角色卡中注入工具建议 tool_hint = f"推荐工具: {matches[0]['name']}" ``` ### 推荐在角色卡中注入 ``` [OPC 角色卡] - 角色:搭建工程师 - 可用工具:gundam-ops(高达搭建执行 Skill) - 工具来源:本地已安装 ``` ## 使用示例 ### 场景 1:营销活动搭建 ```bash $ python3 tool_discovery.py report "创建高达营销活动并配置组件" # 🔧 OPC 工具建议报告 # **任务**: 创建高达营销活动并配置组件 # # ## ✅ 已安装可用 # | Skill | 相关度 | 匹配原因 | # |-------|--------|----------| # | gundam-ops-202603091158-lzw | ⭐⭐⭐⭐ | 关键词匹配: 活动, 配置, 组件, 营销 | ``` ### 场景 2:搜索新工具 ```bash $ python3 tool_discovery.py search "PDF 文档处理" # 本地匹配: # pdf ⭐⭐⭐ — 关键词匹配: pdf, 文档 # # 搜索 ClawHub... # 找到 2 个外部 Skill: # pdf-merge — https://clawhub.com/skills/pdf-merge ``` ### 场景 3:安全检查 ```bash $ python3 tool_discovery.py check ~/.openclaw/skills/some-skill # ✅ 安全初筛通过: /root/.openclaw/skills/some-skill # 注意: 这只是快速初筛,不替代完整安全审计 (skill-vetter) ``` ## 命令行参考 ```bash # 扫描本地 Skill python3 tool_discovery.py scan # 搜索外部 python3 tool_discovery.py search "关键词" # 生成完整报告 python3 tool_discovery.py report "任务描述" # 安全初筛 python3 tool_discovery.py check <skill_path> # 通过 project_state_v2 集成调用 python3 project_state_v2.py tool-scan "任务描述" ``` ## 缓存机制 - 本地扫描结果缓存到 `opc-projects/.tool-cache.json` - TTL: 1 小时(3600 秒) - 过期后自动重新扫描 - `scan` 命令强制刷新缓存 ## 限制 1. 关键词匹配是简单的词级交集,不做语义理解 2. ClawHub 搜索依赖网络可用性和 openclaw CLI 3. Friday Skill 广场需要 SSO 认证,sandbox 中可能不可用 4. 安全初筛只检查文本模式,不做代码执行分析engine/tool_discovery.py22 KB27bdabccdceeupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
engine/trigger_engine.py28 KBb1af54f1f636upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
engine/troubleshooting.md5.9 KB59030c9a099fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
LICENSE5.4 KBadc0ef548504upstream ↗
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship made available under the License, as indicated by a copyright notice that is included in or attached to the work. "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. "Contribution" shall mean, as submitted to the Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. "Contributor" shall mean Licensor and any Legal Entity on behalf of whom a Contribution has been received by the Licensor and included within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable patent license to make, use, sell, offer for sale, import, and otherwise transfer the Work. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work; and (d) If the Work includes a "NOTICE" text file, you must include a readable copy of the attribution notices contained within such NOTICE file. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall any Contributor be liable to You for damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may offer acceptance of warranty, liability obligations. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor. END OF TERMS AND CONDITIONS Copyright 2026 LZW (Fozu-lzwpattern) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.playbook/persona-priming.md4.9 KB355a9caa4f2bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/personas/lzw.md3.8 KB9b3aff32d8a0upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/philosophy.md19 KB555ef79b2a55upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/roles/analyst.md1.1 KBda5d10e209b2upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/roles/biz-analyst.md1.3 KBe22dd6bb08f9upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/roles/critic.md1.9 KBb9188e5bafb5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/roles/engineer.md1.3 KBbdb35cd355b5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/roles/integrator.md1.3 KBe53f1b41a84eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/roles/researcher.md1.4 KB5a93aff1810fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/roles/ux-designer.md1.4 KB01aeef66bcc0upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/roles/writer.md1.3 KB677779b757d6upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/scenarios/_README.md913 B006c69d3f4f4upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/scenarios/content-project.yaml2.6 KB7d0bc3959020upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/scenarios/engineering-project.yaml2.6 KB04aff0353e58upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/scenarios/marketing-campaign.md7.4 KB4ed03f3cea16upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/scenarios/research-project.yaml2.6 KB2978fc6506d4upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/templates/agent-prompt.md2.8 KB69cbe096061bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/templates/cost-report.md818 Baed084269152upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/templates/focus.yaml742 B12f007818a8cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/templates/opc-user-model.md647 B62f0dba354d8upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/templates/output-contract.yaml2.4 KB1ad8d54b941aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/templates/project-plan.md1.0 KB13fca17b1f59upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
playbook/templates/triggers.yaml1.8 KB9dd8dca84040upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/fozu-openclaw-skills.md