diff --git a/CONTRIBUTING_EN-googletrans.md b/CONTRIBUTING_EN-googletrans.md new file mode 100644 index 00000000..cc7ffb2a --- /dev/null +++ b/CONTRIBUTING_EN-googletrans.md @@ -0,0 +1,202 @@ +∏# 🤝 Participate and contribute + +
+Three provinces and six ministries welcome heroes from all walks of life ⚔️
+Whether it’s fixing a typo or designing a new Agent character, we’re all very grateful
+
+Thank you to every contributor, you are the cornerstone of the three provinces and six departments ⚔️ +
diff --git a/ROADMAP_EN-googletrans.md b/ROADMAP_EN-googletrans.md new file mode 100644 index 00000000..c8f6075e --- /dev/null +++ b/ROADMAP_EN-googletrans.md @@ -0,0 +1,106 @@ +# 🗺️ Three provinces and six departments · Roadmap + +> This roadmap is public. Welcome to claim unfinished projects and submit PRs to participate in the construction. +> +> How to claim: Reply "I'll take this" under the corresponding issue, or submit a PR directly and indicate it in the description. + +--- + +## Phase 1 — Core Architecture ✅ + +> The skeleton of three provinces and six departments: twelve departments + prince sorting + real-time billboard + complete workflow. + +- [x] Twelve-department Agent structure (Prince + Zhongshu·Menxia·Shangshu + Huli Bingxinggong + Officials + Early Dynasty Officials) +- [x] Prince Sorting Layer - Automatically identify chats/commands, reply directly to chats, extract the title of the command and transfer it to Zhongshu Province +- [x] Strict permission matrix - who can send messages to whom, in black and white +- [x] Military Aircraft Department real-time dashboard (10 function panels) +- [x] Task life cycle management (create → sort → plan → review → dispatch → execute → echo) +- [x] Task pause/cancel/resume +- [x] Memorial system (automatic archiving of completed decrees + five-stage timeline) +- [x] Imperial edict template library (9 preset templates + parameter form + estimated time/cost) +- [x] A sense of ritual for going to court (the opening animation will be played for the first time every day + today’s statistics) +- [x] World News (daily automatic collection of technology/financial information + Feishu push + subscription management) +- [x] Model hot switching (one-click switching of each Agent's LLM in the dashboard) +- [x] Skill management (check installed Skills in each province + add new skills) +- [x] Official overview (Token consumption ranking + activity + completion statistics) +- [x] Small tasks/session monitoring (OC-* session real-time tracking) +- [x] Purpose data cleaning - titles/notes are automatically purified, and dirty data is refused to be stored in the database +- [x] Duplicate mission protection - Completed/cancelled missions cannot be overwritten +- [x] E2E Kanban test (all 9 scenarios and 17 assertions passed) +- [x] React 18 front-end refactoring - TypeScript + Vite + Zustand, 13 functional components +- [x] Visualization of Agent's thinking process - real-time display of thinking / tool_result / user messages +- [x] Integrated front-end and back-end deployment - server.py also provides API + static file services + +--- + +## Phase 2 — System deepening 🚧 + +> Upgrade "easy to use" to "irreplaceable": Decentralization and checks and balances are not just a concept, but a complete system with performance evaluation, manual approval, and knowledge accumulation. + +### 🏅 Royal approval mode (manual approval node) +- [ ] The results of the deliberation of the province are submitted to "Yulan", which can be accurately read/rejected manually with one click. +- [ ] Approval panel within the Kanban board (pending approval list + historical approval instructions) +- [ ] Feishu/Telegram push approval notification +- **Difficulty**: ⭐⭐ | **Suitable for first time contributors** + +### 📊 Record of Merits and Demerits (Agent Performance Rating System) +- [ ] Completion rate, rework rate, and time-consuming statistics of each Agent +- [ ] Kanban panel display ranking list + trend chart +- [ ] Automatically mark "competent ministers" and "Agents who need training" +- **Difficulty**: ⭐⭐ + +### 🚀 Express Shop (visualization of real-time message flow between agents) +- [ ] Real-time connection animation in the billboard: Zhongshu → Menxia → Shangshu → Liubu +- [ ] Message type coloring (Dispatch/Consideration/Echo/Reject) +- [ ] Timeline playback mode +- **Difficulty**: ⭐⭐⭐ + +### 📚 National History Museum (knowledge base + citation tracing) +- [ ] The experience of historical will is automatically precipitated +- [ ] Similar intention search + recommendation +- [ ] Traceability chain of memorial citations +- **Difficulty**: ⭐⭐⭐ + +--- + +## Phase 3 — Ecological Expansion + +> From stand-alone tools to ecosystem: more integrations, more users, and more scenarios. + +### 🐳 Docker Compose + Demo Image +- [ ] `docker run` One-line command to experience the complete dashboard (preset simulation data) +- [ ] Docker Compose orchestration (kanban + data synchronization + OpenClaw Gateway) +- [ ] CI/CD automatically builds push images +- **Difficulty**: ⭐⭐ | **Suitable for first time contributors** + +### 🔗 Kanban Adapter +- [ ] Notion Adapter - Turn the Notion database into a military aircraft department billboard +- [ ] Linear adapter - Linear projects are synchronized to three provinces and six departments +- [ ] GitHub Issues two-way synchronization +- **Difficulty**: ⭐⭐⭐ + +### 📱 Mobile + PWA +- [ ] Responsive layout adapted to mobile phones/tablets +- [ ] PWA offline support + push notifications +- **Difficulty**: ⭐⭐ + +### 🏪 ClawHub is available +- [ ] Core Skills submitted to OpenClaw official Skill Market +- [ ] Install three provinces and six Skill Packs with one click +- **Difficulty**: ⭐ + +### 📈 Annual exam +- [ ] Agent annual performance report (total Token consumption, completion rate, most complex intention) +- [ ] Visual annual review screen +- **Difficulty**: ⭐⭐ + +--- + +## How to participate + +1. **Look at Phase 2** - These are the directions that need the most help right now +2. **Look for projects marked with ⭐⭐ or "Suitable for first time contribution"** to get started +3. **Open an Issue** to say what you want to do to avoid duplication of work +4. **Publish PR** - see [CONTRIBUTING.md](CONTRIBUTING.md) for details + +> 💡 Didn’t find the direction you want to go? You are welcome to open an Issue to propose new features, and good ideas will be added to the Roadmap. diff --git a/docs/getting-started_EN-first-version.md b/docs/getting-started_EN-first-version.md new file mode 100644 index 00000000..cdd34bfe --- /dev/null +++ b/docs/getting-started_EN-first-version.md @@ -0,0 +1,189 @@ +# 🚀 Quick Start Guide + +> Start from zero — set up your Three Departments & Six Ministries AI collaboration system in 5 minutes + +--- + +## Step 1: Install OpenClaw + +Three Departments & Six Ministries runs on [OpenClaw](https://openclaw.ai). Install it first: + +```bash +# macOS +brew install openclaw + +# Or download the installer package +# https://openclaw.ai/download +``` +After installation, initialize: + +```bash +openclaw init +``` + +--- + +## Step 2: Clone and install Three Departments & Six Ministries + +```bash +git clone https://github.com/cft0808/edict.git +cd edict +chmod +x install.sh && ./install.sh +``` + +The installer automatically: +- ✅ Creates 12 Agent Workspaces (`~/.openclaw/workspace-*`) +- ✅ Writes each department/office SOUL.md personality file +- ✅ Registers Agents and the permission matrix into `openclaw.json` +- ✅ Configures edict data sanitization rules +- ✅ Builds the React frontend into `dashboard/dist/` (requires Node.js 18+) +- ✅ Initializes the data directory +- ✅ Runs the first data sync +- ✅ Restarts the Gateway so the configuration takes effect + +--- + +## Step 3: Configure messaging channels + +Configure messaging channels in OpenClaw (Feishu / Telegram / Signal), and set the `taizi` (Crown Prince) agent as the edict entrypoint. The Crown Prince automatically separates casual chat from commands; command messages have their titles extracted and are forwarded to the Planning Department (Zhongshu). + +```bash +# View current channels +openclaw channels list + +# Add Feishu channel (set entrypoint to Crown Prince) +openclaw channels add --type feishu --agent taizi +``` + +Refer to OpenClaw docs: https://docs.openclaw.ai/channels + +--- + +## Step 4: Start the services + +```bash +# Terminal 1: data refresh loop (sync every 15 seconds) +bash scripts/run_loop.sh + +# Terminal 2: dashboard server +python3 dashboard/server.py + +# Open browser +open http://127.0.0.1:7891 +``` + +> 💡 Tip: `run_loop.sh` automatically syncs data every 15 seconds. You can run it in the background using `&`. + +> 💡 Dashboard is ready out-of-the-box: `server.py` embeds `dashboard/dashboard.html`, no extra build required. The Docker image includes a prebuilt React frontend. + +--- + +## Step 5: Send your first edict + +Send a task through your messaging channel (the Crown Prince will automatically detect it and forward it to Zhongshu): + +``` +Please help me write a text classifier in Python: +1. Use scikit-learn +2. Support multi-class classification +3. Output a confusion matrix +4. Write complete documentation +``` + +--- + +## Step 6: Observe the execution process + +Open the dashboard: http://127.0.0.1:7891 + +1. **📋 Edicts Kanban** — watch tasks move across states +2. **🔭 Department Dispatch** — view workload distribution across departments +3. **📜 Memorial Archive** — after completion, tasks are automatically archived as memorials + +Task flow path: +``` +Inbox → Crown Prince triage → Zhongshu planning → Menxia review → Assigned → Doing → Done +``` + +--- + +## 🎯 Advanced usage + +### Use edict templates + +> Dashboard → 📜 Templates Library → select template → fill parameters → issue edict + +9 preset templates: weekly report · code review · API design · competitive analysis · data report · blog post · deployment plan · email copy · standup summary + +### Switch an agent’s model + +> Dashboard → ⚙️ Model Config → choose a new model → apply changes + +After ~5 seconds, the Gateway automatically restarts and the change takes effect. + +### Manage skills + +> Dashboard → 🛠️ Skills Config → view installed skills → click “add new skill” + +### Stop / cancel a task + +> In the Edicts Kanban or task detail, click **⏸ Stop** or **🚫 Cancel** + +### Subscribe to “World News” (Daily Briefing) + +> Dashboard → 📰 Daily Briefing → ⚙️ Subscription Management → choose categories / add sources / configure Feishu push + +--- + +## ❓ Troubleshooting + +### Dashboard shows “server not started” +```bash +# Confirm the server is running +python3 dashboard/server.py +``` + +### Agent does not respond +```bash +# Check Gateway status +openclaw gateway status + +# Restart if needed +openclaw gateway restart +``` + +### Data does not update +```bash +# Check whether the refresh loop is running +ps aux | grep run_loop + +# Manually run one sync +python3 scripts/refresh_live_data.py +``` + +### Heartbeat shows red / alert +```bash +# Check the corresponding Agent process +openclaw agent status+Use the open ecosystem to empower institutionalized AI collaboration +
diff --git a/docs/remote-skills-quickstart_EN-googletrans.md b/docs/remote-skills-quickstart_EN-googletrans.md new file mode 100644 index 00000000..29072afd --- /dev/null +++ b/docs/remote-skills-quickstart_EN-googletrans.md @@ -0,0 +1,336 @@ +# Remote Skills Quick Start + +## 5 minutes experience + +### 1. Start the server + +```bash +# Make sure you are in the project root directory +python3 dashboard/server.py +# Output: Three provinces and six departments signboard started → http://127.0.0.1:7891 +``` + +### 2. Add official Skill (CLI) + +```bash +# Add code review skill to Zhongshu Province +python3 scripts/skill_manager.py add-remote \ + --agent zhongshu \ + --name code_review \ + --source https://raw.githubusercontent.com/openclaw-ai/skills-hub/main/code_review/SKILL.md \ + --description "代码审查能力" + +# Output: +# ⏳ Downloading from https://raw.githubusercontent.com/... +# ✅ Skill code_review has been added to zhongshu +# Path: /Users/xxx/.openclaw/workspace-zhongshu/skills/code_review/SKILL.md +# Size: 2048 bytes +``` + +### 3. List all remote Skills + +```bash +python3 scripts/skill_manager.py list-remote + +# Output: +# 📋 Total 1 remote skills: +# +# Agent | Skill name | Description | Add time +# ------------|-----------------------|--------------------------------|---------- +# zhongshu | code_review | Code review capabilities | 2026-03-02 +``` + +### 4. View API response + +```bash +curl http://localhost:7891/api/remote-skills-list | jq . + +# Output: +# { +# "ok": true, +# "remoteSkills": [ +# { +# "skillName": "code_review", +# "agentId": "zhongshu", +# "sourceUrl": "https://raw.githubusercontent.com/...", +# "description": "Code review capability", +# "localPath": "/Users/xxx/.openclaw/workspace-zhongshu/skills/code_review/SKILL.md", +# "addedAt": "2026-03-02T14:30:00Z", +# "lastUpdated": "2026-03-02T14:30:00Z", +# "status": "valid" +# } +# ], +# "count": 1, +# "listedAt": "2026-03-02T14:35:00Z" +# } +``` + +--- + +## Common operations + +### Import all skills in the official library with one click + +```bash +python3 scripts/skill_manager.py import-official-hub \ + --agents zhongshu,menxia,shangshu,bingbu,xingbu +``` + +This automatically adds for each agent: +- **zhongshu**: code_review, api_design, doc_generation +- **menxia**: code_review, api_design, security_audit, data_analysis, doc_generation, test_framework +- **shangshu**: Same as menxia (coordinator) +- **bingbu**: code_review, api_design, test_framework +- **xingbu**: code_review, security_audit, test_framework + +### Update a Skill to the latest version + +```bash +python3 scripts/skill_manager.py update-remote \ + --agent zhongshu \ + --name code_review + +# Output: +# ⏳ Downloading from https://raw.githubusercontent.com/... +# ✅ Skill code_review has been added to zhongshu +# ✅ Skills have been updated +# Path: /Users/xxx/.openclaw/workspace-zhongshu/skills/code_review/SKILL.md +# Size: 2156 bytes +``` + +### Remove a Skill + +```bash +python3 scripts/skill_manager.py remove-remote \ + --agent zhongshu \ + --name code_review + +# Output: +# ✅ Skill code_review has been removed from zhongshu +``` + +--- + +## Kanban UI operation + +### Add Remote Skill to the dashboard + +1. Open http://localhost:7891 +2. Enter the 🔧 **Skill Configuration** panel +3. Click the **➕Add Remote Skill** button +4. Fill out the form: +- **Agent**: Select from the drop-down list (such as zhongshu) +- **Skill Name**: Enter an internal ID such as `code_review` +- **Remote URL**: Paste the GitHub URL such as `https://raw.githubusercontent.com/openclaw-ai/skills-hub/main/code_review/SKILL.md` +- **Chinese description**: optional, such as `code review ability` +5. Click the **Import** button +6. Wait 1-2 seconds to see the ✅ success prompt + +### Manage added Skills + +On the dashboard → 🔧 Skill configuration → **Remote Skills** tab: + +- **View**: Click on the Skill name to view the SKILL.md content +- **UPDATE**: Click 🔄 to re-download the latest version from the source URL +- **DELETE**: Click ✕ to remove the local copy +- **Copy URL**: Quickly share with others + +--- + +## Create your own Skill library + +### Directory structure + +``` +my-skills-hub/ +├── code_review/ +│ └── SKILL.md # Code review capability +├── api_design/ +│ └── SKILL.md #API Design Review +├── data_analysis/ +│ └── SKILL.md # Data Analysis +└── README.md +``` + +### SKILL.md template + +```markdown +--- +name: my_custom_skill +description: short description +version: 1.0.0 +tags: [tag1, tag2] +--- + +# Skill full name + +Detailed description... + +## Input + +Indicates what parameters are received + +## Processing process + +Specific steps... + +## Output specifications + +Output format description +``` + +### Upload to GitHub + +```bash +git init +git add . +git commit -m "Initial commit: my-skills-hub" +git remote add origin https://github.com/yourname/my-skills-hub +git push -u origin main +``` + +### Import your own Skill + +```bash +python3 scripts/skill_manager.py add-remote \ + --agent zhongshu \ + --name my_skill \ + --source https://raw.githubusercontent.com/yourname/my-skills-hub/main/my_skill/SKILL.md \ + --description "我的定制技能" +``` + +--- + +## API complete reference + +### POST /api/add-remote-skill + +Add a remote skill. + +**ask:** +```bash +curl -X POST http://localhost:7891/api/add-remote-skill \ + -H "Content-Type: application/json" \ + -d '{ + "agentId": "zhongshu", + "skillName": "code_review", + "sourceUrl": "https://raw.githubusercontent.com/...", + "description": "代码审查" + }' +``` + +**Response (200):** +```json +{ + "ok": true, + "message": "技能 code_review 已从远程源添加到 zhongshu", + "skillName": "code_review", + "agentId": "zhongshu", + "source": "https://raw.githubusercontent.com/...", + "localPath": "/Users/xxx/.openclaw/workspace-zhongshu/skills/code_review/SKILL.md", + "size": 2048, + "addedAt": "2026-03-02T14:30:00Z" +} +``` + +### GET /api/remote-skills-list + +List all remote skills. + +```bash +curl http://localhost:7891/api/remote-skills-list +``` + +**response:** +```json +{ + "ok": true, + "remoteSkills": [ + { + "skillName": "code_review", + "agentId": "zhongshu", + "sourceUrl": "https://raw.githubusercontent.com/...", + "description": "代码审查能力", + "localPath": "/Users/xxx/.openclaw/workspace-zhongshu/skills/code_review/SKILL.md", + "addedAt": "2026-03-02T14:30:00Z", + "lastUpdated": "2026-03-02T14:30:00Z", + "status": "valid" + } + ], + "count": 1, + "listedAt": "2026-03-02T14:35:00Z" +} +``` + +### POST /api/update-remote-skill + +Update the remote skill to the latest version. + +```bash +curl -X POST http://localhost:7891/api/update-remote-skill \ + -H "Content-Type: application/json" \ + -d '{ + "agentId": "zhongshu", + "skillName": "code_review" + }' +``` + +### DELETE /api/remove-remote-skill + +Remove remote skills. + +```bash +curl -X POST http://localhost:7891/api/remove-remote-skill \ + -H "Content-Type: application/json" \ + -d '{ + "agentId": "zhongshu", + "skillName": "code_review" + }' +``` + +--- + +## Troubleshooting + +### Q: Download failed, prompting "Connection timeout" + +**A:** Check network connection and URL validity + +```bash +curl -I https://raw.githubusercontent.com/... +# Should return HTTP/1.1 200 OK +``` + +### Q: The file format is invalid + +**A:** Make sure SKILL.md starts with YAML frontmatter + +```markdown +--- +name: skill_name +description: description +--- + +# The text begins... +``` + +### Q: I can’t see Skill after importing + +**A:** Refresh the dashboard or check whether the Agent is configured correctly + +```bash +# Check if Agent exists +python3 scripts/skill_manager.py list-remote + +# Check local files +ls -la ~/.openclaw/workspace-zhongshu/skills/ +``` + +--- + +## More information + +- 📚 [Complete Guide](remote-skills-guide.md) +- 🏛️[Architecture Document](task-dispatch-architecture.md) +- 🤝 [Project Contribution](../CONTRIBUTING.md) + diff --git a/docs/task-dispatch-architecture_EN-googletrans.md b/docs/task-dispatch-architecture_EN-googletrans.md new file mode 100644 index 00000000..0f014c9c --- /dev/null +++ b/docs/task-dispatch-architecture_EN-googletrans.md @@ -0,0 +1,1599 @@ +# Task distribution and transfer system for three provinces and six departments · Business and technical structure + +> This document explains in detail how the "Three Provinces and Six Departments" project, from **business system design** to **code implementation details**, completely handles the task distribution and flow of complex multi-Agent collaboration. This is an **institutionalized AI multi-Agent framework** rather than a traditional free discussion collaboration system. + +**Document overview** + +``` +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Business layer: Imperial Governance Model +├─ Separation of powers and checks and balances: Emperor → Prince → Zhongshu → Menxia → Shangshu → Six Books +├─ System constraints: no skipping, status strictly progressive, must be reviewed by subordinates +└─ Quality assurance: capable of rejection, real-time observability, emergency intervention +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Technical layer: OpenClaw Multi-Agent Orchestration (Multi-Agent Orchestration) +├─ State machine: 9 states (Pending → Taizi → Zhongshu → Menxia → Assigned → Doing/Next → Review → Done/Cancelled) +├─ Data fusion: flow_log + progress_log + session JSONL → unified activity stream +├─Permission matrix: strict subagent call permission control +└─ Scheduling layer: automatic dispatch, timeout retry, stalled upgrade, automatic rollback +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Observation layer: React dashboard + real-time API (Dashboard + Real-time Analytics) +├─ Task dashboard: 10 view panels (all/by status/by department/by priority, etc.) +├─ Activity flow: 59 mixed activity records/task (thinking process, tool invocation, state transfer) +└─ Online status: Agent real-time node detection + heartbeat wake-up mechanism +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +--- + +## 📚 Part 1: Business Architecture + +### 1.1 Imperial system: the design philosophy of decentralization and checks and balances + +#### Core Concept + +Traditional multi-Agent frameworks (such as CrewAI, AutoGen) adopt the **"free collaboration" mode**: +- Agent independently selects collaboration partners +- The framework only provides communication channels +- Quality control completely relies on Agent intelligence +- **Problem**: It is easy for agents to create false data for each other, duplicate work, and the quality of solutions is not guaranteed. + +**Three provinces and six ministries** adopt the **"institutionalized collaboration" model**, imitating the ancient imperial bureaucracy: + +``` +emperor +(User) +│ +↓ +Taizi +[Sorting Officer, General Responsible for Message Access] +├─Identification: Is this a decree or just idle chatter? +├─ Execution: Reply directly to chat || Create task → Transfer to Zhongshu +└─ Permission: can only call Zhongshu Province +│ +↓ +Zhongshu +[Planning Officer, Chief Responsible for Plan Drafting] +├─ Analyze needs after receiving orders +├─ Break down into subtasks (todos) +├─ Invoke the Ministry of Menxia for review OR the Ministry of Secretariat for consultation +└─ Permissions: Can only call Menxia + Shangshu +│ +↓ +Menxia +[Reviewer, Quality Assurance Person] +├─ Review the Zhongshu plan (feasibility, completeness, risks) +├─Accept or reject (including modification suggestions) +├─ If rejected → Return to Zhongshu for revision → Re-examine (up to 3 rounds) +└─Permissions: Can only call Shangshu + callback Zhongshu +│ +(✅ Accurate performance) +│ +↓ +Shangshu +[Distribution officer, executive commander] +├─ Receive the accurate plan +├─Analyze which department to distribute to +├─ Call the six departments (rituals/households/soldiers/criminals/workers/officials) to execute +├─ Monitor the progress of each department → Summarize the results +└─Permissions: Only six parts can be called (cannot transfer Zhongshu beyond the authority) +│ +├─ Libu - Documentation Officer +├─Hubu - Data Analysis Officer +├─ Bingbu - Code Implementation Officer +├─ Xingbu - Test Examiner +├─ Ministry of Industry (Gongbu) - Infrastructure Officer +└─ Libu_hr - Human Resources Officer +│ +(Each department is executed in parallel) +↓ +Shangshu Province·Summary +├─ Collect six results +├─ Status changes to Review +├─ Call back to Zhongshu Sheng and report to the Emperor +│ +↓ +Zhongshu Province·Echo +├─ Summarize phenomena, conclusions, and suggestions +├─ Status changes to Done +└─ Reply to Feishu message to the Emperor +``` + +#### Four major guarantees of the system + +| Guarantee mechanism | Implementation details | Protection effect | +|---------|---------|---------| +| **Institutional review** | The province must review all Zhongshu plans and cannot be skipped | Prevent Agent from executing randomly and ensure the feasibility of the plan | +| **Separation of powers and checks and balances** | Authority matrix: Strict definition of who can transfer whom | Prevent abuse of power (such as the minister's overstepping of authority to transfer the middle book reform plan) | +| **Fully Observable** | Task dashboard 10 panels + 59 activities/tasks | See where the task is stuck, who is working, and what the working status is in real time | +| **Real-time intervention** | One-click stop/cancel/resume/advance in the dashboard | Emergency situations (such as finding that the Agent is going in the wrong direction) can be corrected immediately | + +--- + +### 1.2 Complete task transfer process + +#### Process diagram + +```mermaid +stateDiagram-v2 +[*] --> Pending: 皇上下旨 +Pending --> Taizi: 太子接旨 +Taizi --> Zhongshu: 太子转交中书 +Zhongshu --> Menxia: 中书提交审议 +Menxia --> Zhongshu: 门下封驳(可多次) +Menxia --> Assigned: 门下准奏 +Assigned --> Doing: 尚书派发执行 +Doing --> Review: 各部完成 +Review --> Done: 皇上御批通过 +Review --> Menxia: 皇上要求修改 +Done --> [*] +Doing --> [*]: 手动取消 +Review --> [*]: 业务终止 +``` + +#### Specific critical path + +**✅Ideal path** (no blockage, 4-5 days to complete) + +``` +DAY 1: +10:00 - The Emperor Feishu: "Write a complete automated testing plan for three provinces and six departments" +The prince accepted the order. state = Taizi, org = Prince +Automatically dispatch taizi agent → handle this request + +10:30 - Prince sorting is completed. Determined as "work intention" (not chatting) +Build task JJC-20260228-E2E +flow_log record: "Emperor → Prince: Decree" +state: Taizi → Zhongshu, org: Prince → Zhongshu Province +Automatically dispatch zhongshu agent + +DAY 2: +09:00 - Zhongshu Province receives the order. Start planning +Report progress: "Analyze test requirements and dismantle them into three layers: unit/integration/E2E" +progress_log record: "Zhongshu Sheng Zhang San: sub-requirements" + +15:00 - Zhongshu Province completes the plan +todos snapshot: demand analysis✅, solution design✅, to be reviewed🔄 +flow_log record: "Zhongshu Province → Menxia Province: Plan submitted for review" +state: Zhongshu → Menxia, org: Zhongshu Province → Menxia Province +Automatically dispatch menxia agent + +DAY 3: +09:00 - The province begins deliberations +Progress Report: "Now review the plan for completeness and risks" + +14:00 - The review of the Menxia Province is completed +Judgment: "The solution is feasible, but the test of the _infer_agent_id_from_runtime function is missing" +Behavior:✅ Accurate (with modification suggestions) +flow_log record: "Menxia Province → Shangshu Province: ✅ The performance was approved (5 suggestions)" +state: Menxia → Assigned, org: Menxia Province → Shangshu Province +OPTIONAL: Zhongshu Province received suggestions and took the initiative to optimize the plan. +Automatically dispatch shangshu agent + +DAY 4: +10:00 - Shangshu Sheng received the report +Analysis: "This test plan should be sent to the Ministry of Industry + the Ministry of Punishment + the Ministry of Rites to complete it together" +flow_log record: "Shangshu Province → Sixth Department: dispatch and execution (cooperation of soldiers and officials)" +state: Assigned → Doing, org: Shangshu Province → Ministry of War + Ministry of Punishment + Ministry of Rites +Automatically dispatch three agents bingbu/xingbu/libu (in parallel) + +DAY 4-5: +(Each department is executed in parallel) +- Bingbu: Implement pytest + unittest testing framework +- Xingbu (xingbu): Write tests to cover all key functions +- Libu: Organize test documents and use case descriptions + +Real-time report (hourly progress): +- Ministry of War: "✅ 16 unit tests implemented" +- Ministry of Justice: "🔄 Writing integration tests (completed on 8/12)" +- Ministry of Rites: "Wait until the Ministry of War is completed before writing a report." + +DAY 5: +14:00 - All parts completed +state: Doing → Review, org: Ministry of War → Ministry of Education +Summary from Shangshu Province: "All tests have been completed, and the pass rate is 98.5%" +Transfer back to Zhongshu Province + +15:00 - Zhongshu Province responds to the Emperor +state: Review → Done +Template reply to Feishu, including final result link and summary +``` + +**❌ Frustration Path** (including rejection and retry, 6-7 days) + +``` +DAY 2 Same as above + +DAY 3 [rejection scene]: +14:00 - The review of the Menxia Province is completed +Judgment: "The plan is incomplete and lacks performance testing + stress testing" +Behavior: 🚫 Block +review_round += 1 +flow_log record: "Menxia Province → Zhongshu Province: 🚫 Failed (need to supplement performance testing)" +state: Menxia → Zhongshu # Return to Zhongshu for modification +Automatically dispatch zhongshu agent (replanning) + +DAY 3-4: +16:00 - Zhongshu Province receives the rejection notice (wakes up the agent) +Analyze improvement suggestions and supplement performance testing plans +progress: "Performance testing requirements have been integrated, and the correction plan is as follows..." +flow_log record: "Zhongshu Province → Menxia Province: Revised plan (2nd round of review)" +state: Zhongshu → Menxia +Automatically dispatch menxia agent + +18:00 - Menxia Province reconsideration +Judgment: "✅ Passed this time" +flow_log record: "Menxia Province → Shangshu Province: ✅ Passed (2nd round)" +state: Menxia → Assigned → Doing +The follow-up is the same as the ideal path... + +DAY 7: All completed (1-2 days later than ideal path) +``` + +--- + +### 1.3 Task Specification and Business Contract + +#### Task Schema field description + +```json +{ + "id": "JJC-20260228-E2E", // 任务全局唯一ID (JJC-日期-序号) + "title": "为三省六部编写完整自动化测试方案", + "official": "中书令", // 负责官职 + "org": "中书省", // 当前负责部门 + "state": "Assigned", // 当前状态(见 _STATE_FLOW) + + // ──── 质量与约束 ──── + "priority": "normal", // 优先级:critical/high/normal/low + "block": "无", // 当前阻滞原因(如"等待工部反馈") + "reviewRound": 2, // 门下审议第几轮 + "_prev_state": "Menxia", // 若被 stop,记录之前状态用于 resume + + // ──── 业务产出 ──── + "output": "", // 最终任务成果(URL/文件路径/总结) + "ac": "", // Acceptance Criteria(验收标准) + "priority": "normal", + + // ──── 流转记录 ──── + "flow_log": [ + { + "at": "2026-02-28T10:00:00Z", + "from": "皇上", + "to": "太子", + "remark": "下旨:为三省六部编写完整自动化测试方案" + }, + { + "at": "2026-02-28T10:30:00Z", + "from": "太子", + "to": "中书省", + "remark": "分拣→传旨" + }, + { + "at": "2026-02-28T15:00:00Z", + "from": "中书省", + "to": "门下省", + "remark": "规划方案提交审议" + }, + { + "at": "2026-03-01T09:00:00Z", + "from": "门下省", + "to": "中书省", + "remark": "🚫 封驳:需补充性能测试" + }, + { + "at": "2026-03-01T15:00:00Z", + "from": "中书省", + "to": "门下省", + "remark": "修订方案(第2轮审议)" + }, + { + "at": "2026-03-01T20:00:00Z", + "from": "门下省", + "to": "尚书省", + "remark": "✅ 准奏通过(第2轮,5条建议已采纳)" + } + ], + + // ──── Agent 实时汇报 ──── + "progress_log": [ + { + "at": "2026-02-28T10:35:00Z", + "agent": "zhongshu", // 汇报agent + "agentLabel": "中书省", + "text": "已接旨。分析测试需求,拟定三层测试方案...", + "state": "Zhongshu", // 汇报时的状态快照 + "org": "中书省", + "tokens": 4500, // 资源消耗 + "cost": 0.0045, + "elapsed": 120, + "todos": [ // 待办任务快照 + {"id": "1", "title": "需求分析", "status": "completed"}, + {"id": "2", "title": "方案设计", "status": "in-progress"}, + {"id": "3", "title": "await审议", "status": "not-started"} + ] + }, + // ... 更多 progress_log 条目 ... + ], + + // ──── 调度元数据 ──── + "_scheduler": { + "enabled": true, + "stallThresholdSec": 180, // 停滞超过180秒自动升级 + "maxRetry": 1, // 自动重试最多1次 + "retryCount": 0, + "escalationLevel": 0, // 0=无升级 1=门下协调 2=尚书协调 + "lastProgressAt": "2026-03-01T20:00:00Z", + "stallSince": null, // 何时开始停滞 + "lastDispatchStatus": "success", // queued|success|failed|timeout|error + "snapshot": { + "state": "Assigned", + "org": "尚书省", + "note": "review-before-approve" + } + }, + + // ──── 生命周期 ──── + "archived": false, // 是否归档 + "now": "门下省准奏,移交尚书省派发", // 当前实时状态描述 + "updatedAt": "2026-03-01T20:00:00Z" +} +``` + +#### Business Contract + +| Contract | Meaning | Consequences of breach | +|------|------|---------| +| **Not allowed to skip levels** | The prince can only transfer the middle secretary, the middle secretary can only transfer the subordinates/changshu, and the six departments cannot be called externally | Over-authorized calls are rejected and the system automatically intercepts them | +| **Status progresses in one direction** | Pending → Taizi → Zhongshu → ... → Done, cannot skip or go back | You can only return to the previous step through review_action(reject) | +| **Must be reviewed by the subordinates** | All plans proposed by the Zhongshu must be reviewed by the subordinates and cannot be skipped | The Zhongshu cannot directly transfer to the Minister, and the subordinates must enter | +| **No changes once Done** | The task cannot be modified after it enters the Done/Cancelled state | If you need to modify it, you need to create a new task or cancel and rebuild | +| **task_id uniqueness** | JJC-date-serial number is globally unique, the same task will not be created repeatedly on the same day | Kanban anti-duplication, automatic deduplication | +| **Transparent resource consumption** | Every progress report must be reported tokens/cost/elapsed | Facilitate cost accounting and performance optimization | + +--- + +## 🔧 Part 2: Technical Architecture + +### 2.1 State machine and automatic dispatch + +#### Complete definition of state transfer + +```python +_STATE_FLOW = { + 'Pending': ('Taizi', '皇上', '太子', '待处理旨意转交太子分拣'), + 'Taizi': ('Zhongshu','太子', '中书省', '太子分拣完毕,转中书省起草'), + 'Zhongshu': ('Menxia', '中书省', '门下省', '中书省方案提交门下省审议'), + 'Menxia': ('Assigned','门下省', '尚书省', '门下省准奏,转尚书省派发'), + 'Assigned': ('Doing', '尚书省', '六部', '尚书省开始派发执行'), + 'Next': ('Doing', '尚书省', '六部', '待执行任务开始执行'), + 'Doing': ('Review', '六部', '尚书省', '各部完成,进入汇总'), + 'Review': ('Done', '尚书省', '太子', '全流程完成,回奏太子转报皇上'), +} +``` + +Each state is automatically associated with an Agent ID (see `_STATE_AGENT_MAP`): + +```python +_STATE_AGENT_MAP = { + 'Taizi': 'taizi', + 'Zhongshu': 'zhongshu', + 'Menxia': 'menxia', + 'Assigned': 'shangshu', + 'Doing': None, # 从 org 推断(六部之一) + 'Next': None, # 从 org 推断 + 'Review': 'shangshu', + 'Pending': 'zhongshu', +} +``` + +#### Automatic distribution process + +When the task state transfers (through `handle_advance_state()` or approval), the background automatically executes dispatch: + +``` +1. State transfer triggers distribution +├─ Look up the table _STATE_AGENT_MAP to get the target agent_id +├─ If it is Doing/Next, look up the table _ORG_AGENT_MAP from task.org to infer the specific department agent +└─ If it cannot be inferred, skip dispatch (such as Done/Cancelled) + +2. Construct and distribute messages (targeted to prompt Agent to work immediately) +├─ taizi: "📜 The emperor’s decree needs you to handle..." +├─ zhongshu: "📜 The decree has been sent to Zhongshu Province, please draft a plan..." +├─ menxia: "📋 Zhongshu Provincial Plan is submitted for review..." +├─ shangshu: "📮 The Ministry of Menxia has approved the report, please dispatch it for execution..." +└─ Part 6: "📌 Please handle the task..." + +3. Background asynchronous dispatch (non-blocking) +├─ spawn daemon thread +├─ Tag _scheduler.lastDispatchStatus = 'queued' +├─ Check if the Gateway process is open +├─ Run openclaw agent --agent {id} -m "{msg}" --deliver --timeout 300 +├─ Retry up to 2 times (failure interval 5 seconds back off) +├─ Update _scheduler status and error messages +└─ flow_log records dispatch results + +4. Distribution status transfer +├─ success: update immediately _scheduler.lastDispatchStatus = 'success' +├─ failed: Record the reason for failure. Agent will not block the kanban when it times out. +├─ timeout: Mark timeout to allow users to manually retry/upgrade +├─ gateway-offline: Gateway is not started, skip this distribution (you can try again later) +└─ error: abnormal situation, record stack for debugging + +5. Processing of reaching the target Agent +├─ Agent receives notification from Feishu message +├─ Interact with Kanban (update status/record progress) through kanban_update.py +└─ After completing the work, it will be triggered again and dispatched to the next Agent. +``` + +--- + +### 2.2 Permission matrix and Subagent call + +#### Permission definition (configured in openclaw.json) + +```json +{ + "agents": [ + { + "id": "taizi", + "label": "太子", + "allowAgents": ["zhongshu"] + }, + { + "id": "zhongshu", + "label": "中书省", + "allowAgents": ["menxia", "shangshu"] + }, + { + "id": "menxia", + "label": "门下省", + "allowAgents": ["shangshu", "zhongshu"] + }, + { + "id": "shangshu", + "label": "尚书省", + "allowAgents": ["libu", "hubu", "bingbu", "xingbu", "gongbu", "libu_hr"] + }, + { + "id": "libu", + "label": "礼部", + "allowAgents": [] + }, + // ... 其他六部同样 allowAgents = [] ... + ] +} +``` + +#### Permission checking mechanism (code level) + +In addition to `dispatch_for_state()`, there is a set of defensive permission checks: + +```python +def can_dispatch_to(from_agent, to_agent): + """检查 from_agent 是否有权调用 to_agent。""" + cfg = read_json(DATA / 'agent_config.json', {}) + agents = cfg.get('agents', []) + + from_record = next((a for a in agents if a.get('id') == from_agent), None) + if not from_record: + return False, f'{from_agent} 不存在' + + allowed = from_record.get('allowAgents', []) + if to_agent not in allowed: + return False, f'{from_agent} 无权调用 {to_agent}(允许列表:{allowed})' + + return True, 'OK' +``` + +#### Examples and handling of permission violations + +| Scenario | Request | Result | Reason | +|------|------|------|------| +| **Normal** | Zhongshu Province → Menxia Province Review | ✅ Allow | Menxia is in Zhongshu’s allowAgents | +| **Violation** | Zhongshu Province → Shangshu Province Reform Plan | ❌ Reject | Zhongshu can only transfer the subordinates/ministers, but cannot manually change the ministerial work | +| **Violation** | Ministry of Industry → Shangshu Province "I'm done" | ✅ Change status | Through flow_log and progress_log (not cross-Agent call) | +| **Violation** | Shangshu Province → Zhongshu Province "Re-Change Plan" | ❌ Reject | Shangshu is not under the sect/Zhongshu's allowAgents | +| **Prevention and Control** | Agent forges distribution of other agents | ❌ Interception | API layer verification HTTP request source/signature | + +--- + +### 2.3 Data fusion: progress_log + session JSONL + +#### Phenomenon + +When a task is executed, there are three layers of data sources: + +``` +1️⃣ flow_log +└─ Pure record state transfer (Zhongshu → Menxia) +└─ Data source: flow_log field of task JSON +└─ From: Agent reported through kanban_update.py flow command + +2️⃣ progress_log +└─ Agent’s real-time work report (text progress, todos snapshot, resource consumption) +└─ Data source: progress_log field of task JSON +└─ From: Agent reported through kanban_update.py progress command +└─ Period: usually reported once every 30 minutes or key nodes + +3️⃣ session JSONL (new!) +└─ Agent’s internal thinking process (thinking), tool invocation (tool_result), and conversation history (user) +└─ Data source: ~/.openclaw/agents/{agent_id}/sessions/*.jsonl +└─ From: OpenClaw framework automatically records, the agent does not need to actively operate +└─ Cycle: message level, the finest granularity +``` + +#### Problem Diagnosis + +In the past, only flow_log + progress_log was used to show progress: +- ❌ Can’t see the Agent’s specific thinking process +- ❌ Can’t see the results of each tool call +- ❌ Cannot see the conversation history between Agents +- ❌ Agent exhibits "black box status" + +For example: progress_log records "analyzing requirements", but users cannot see what is being analyzed. + +#### Solution: Session JSONL Fusion + +Add fusion logic in `get_task_activity()` (line 40): + +```python +def get_task_activity(task_id): + #...The previous code is the same as above... + + # ── Integrate Agent Session activities (thinking/tool_result/user)── + session_entries = [] + + # Active tasks: try to match exactly by task_id + if state not in ('Done', 'Cancelled'): + if agent_id: + entries = get_agent_activity( + agent_id, limit=30, task_id=task_id + ) + session_entries.extend(entries) + + # Also obtained from related Agents + for ra in related_agents: + if ra != agent_id: + entries = get_agent_activity( + ra, limit=20, task_id=task_id + ) + session_entries.extend(entries) + else: + # Completed task: matching based on keywords + title = task.get('title', '') + keywords = _extract_keywords(title) + if keywords: + for ra in related_agents[:5]: + entries = get_agent_activity_by_keywords( + ra, keywords, limit=15 + ) + session_entries.extend(entries) + + # Deduplication (avoid duplication through at+kind deduplication) + existing_keys = {(a.get('at', ''), a.get('kind', '')) for a in activity} + for se in session_entries: + key = (se.get('at', ''), se.get('kind', '')) + if key not in existing_keys: + activity.append(se) + existing_keys.add(key) + + # Reorder + activity.sort(key=lambda x: x.get('at', '')) + + # Mark the data source when returning + return { + 'activity': activity, + 'activitySource': 'progress+session', # 新标记 + # ...other fields ... + } +``` + +#### Session JSONL format parsing + +The items extracted from JSONL are uniformly converted into Kanban activity items: + +```python +def _parse_activity_entry(item): + """将 session jsonl 的 message 统一解析成看板活动条目。""" + msg = item.get('message', {}) + role = str(msg.get('role', '')).strip().lower() + ts = item.get('timestamp', '') + + # 🧠 Assistant role - Agent thinking process + if role == 'assistant': + entry = { + 'at': ts, + 'kind': 'assistant', + 'text': '...主回复...', + 'thinking': '💭 Agent考虑到...', # 内部思维链 + 'tools': [ + {'name': 'bash', 'input_preview': 'cd /src && npm test'}, + {'name': 'file_read', 'input_preview': 'dashboard/server.py'}, + ] + } + return entry + + # 🔧 Tool Result - Tool call result + if role in ('toolresult', 'tool_result'): + entry = { + 'at': ts, + 'kind': 'tool_result', + 'tool': 'bash', + 'exitCode': 0, + 'output': '✓ All tests passed (123 tests)', + 'durationMs': 4500 # 执行时长 + } + return entry + + # 👤 User - human feedback or conversation + if role == 'user': + entry = { + 'at': ts, + 'kind': 'user', + 'text': '请实现测试用例的异常处理' + } + return entry +``` + +#### Fusion activity flow structure + +59 activity streams for a single task (JJC-20260228-E2E example): + +``` +kind count represents events +──────────────────────────────────────────── +flow 10 state transfer chain (Pending→Taizi→Zhongshu→...) +progress 11 Agent work report ("analyzing", "completed") +todos 11 to-do task snapshot (each item when the progress is updated) +user 1 user feedback (such as "need to supplement performance testing") +assistant 10 Agent thinking process (💭 reasoning chain) +tool_result 16 Tool call record (bash running result, API call result) +──────────────────────────────────────────── +Total 59 complete work tracks +``` + +When the board is displayed, users can: +- 📋 Look at the circulation chain to understand which stage the task is in +- 📝 Watch progress to understand what the Agent said in real time +- ✅ View todos to learn about task dismantling and completion progress +- 💭 See assistant/thinking to understand the Agent’s thinking process +- 🔧 See tool_result to understand the result of each tool call +- 👤 Look at user to see if there is manual intervention + +--- + +### 2.4 Scheduling system: timeout retry, stalled upgrade, automatic rollback + +#### Scheduling metadata structure + +```python +_scheduler = { + # Configuration parameters + 'enabled': True, + 'stallThresholdSec': 180, # 停滞多久后自动升级(默认180秒) + 'maxRetry': 1, # 自动重试次数(0=不重试,1=重试1次) + 'autoRollback': True, # 是否自动回滚到快照 + + # Runtime status + 'retryCount': 0, # 当前已重试几次 + 'escalationLevel': 0, # 0=无升级 1=门下协调 2=尚书协调 + 'stallSince': None, # 何时开始停滞的时间戳 + 'lastProgressAt': '2026-03-01T...', # 最后一次获得进展的时间 + 'lastEscalatedAt': '2026-03-01T...', + 'lastRetryAt': '2026-03-01T...', + + # Dispatch Tracking + 'lastDispatchStatus': 'success', # queued|success|failed|timeout|gateway-offline|error + 'lastDispatchAgent': 'zhongshu', + 'lastDispatchTrigger': 'state-transition', + 'lastDispatchError': '', # 错误堆栈(如有) + + # Snapshot (for automatic rollback) + 'snapshot': { + 'state': 'Assigned', + 'org': '尚书省', + 'now': '等待派发...', + 'savedAt': '2026-03-01T...', + 'note': 'scheduled-check' + } +} +``` + +#### Scheduling algorithm + +Run `handle_scheduler_scan(threshold_sec=180)` every 60 seconds: + +``` +FOR EACH task: +IF state in (Done, Canceled, Blocked): +SKIP # The final state is not processed + +elapsed_since_progress = NOW - lastProgressAt + +IF elapsed_since_progress < stallThreshold: +SKIP # There has been recent progress, no need to deal with it + +# ── Stall processing logic ── +IF retryCount < maxRetry: +✅ Execute【Retry】 +- increment retryCount +- dispatch_for_state(task, new_state, trigger='taizi-scan-retry') +- flow_log: "Stayed for 180 seconds, triggering automatic retry for the Nth time" +- NEXT task + +IF escalationLevel < 2: +✅ Execute【Upgrade】 +- nextLevel = escalationLevel + 1 +- target_agent = menxia (if L=1) else shangshu (if L=2) +- wake_agent(target_agent, "💬 The task is stalled, please step in to coordinate and advance") +- flow_log: "Upgrade to {target_agent} coordination" +- NEXT task + +IF escalationLevel >= 2 AND autoRollback: +✅ Execute [Automatic Rollback] +- restore task to snapshot.state +- retryCount = 0 +- escalationLevel = 0 +- dispatch_for_state(task, snapshot.state, trigger='taiji-auto-rollback') +- flow_log: "Continuous stagnation, automatic rollback to {snapshot.state}" +``` + +#### Example scenario + +**Scenario: Zhongshu Province Agent process crashes and the task is stuck in Zhongshu** + +``` +T+0: +Zhongshu Province is planning a plan +lastProgressAt = T +dispatch status=success + +T+30: +Agent process crashes unexpectedly (or becomes overloaded and unresponsive) +lastProgressAt still = T (no new progress) + +T+60: +Scheduler_scan scanned it and found: +elapsed = 60 < 180, skip + +T+180: +Scheduler_scan scanned it and found: +elapsed = 180 >= 180, trigger processing + +✅ Phase 1: Try again +- retryCount: 0 → 1 +- dispatch_for_state('JJC-20260228-E2E', 'Zhongshu', trigger='taizi-scan-retry') +- Distribute messages to Zhongshu Province (wake up the agent or restart it) +- flow_log: "Stayed for 180 seconds, automatically retry for the first time" + +T+240: +Zhongshu Province Agent is restored (or restarted manually) and retry distribution is received. +Report progress: "Recovered, continue planning..." +lastProgressAt is updated to T+240 +retryCount reset to 0 + +✓ Problem solving + +T+360 (if still not recovered): +scheduler_scan scan again and find: +elapsed = 360 >= 180, retryCount already = 1 + +✅ Phase 2: Upgrade +- escalationLevel: 0 → 1 +- wake_agent('menxia', "💬 Task JJC-20260228-E2E is stalled, there is no response from Zhongshu Province, please intervene") +- flow_log: "Upgrade to Menxia Province Coordination" + +When the Menxia Province Agent is awakened, it can: +- Check whether Zhongshu Province is online +- If online, ask about progress +- If offline, emergency procedures may be initiated (such as being temporarily drafted by a subordinate) + +T+540 (if still unresolved): +scheduler_scan scan again and find: +escalationLevel = 1, can also be upgraded to 2 + +✅ Phase 3: Upgrade again +- escalationLevel: 1 → 2 +- wake_agent('shangshu', "💬 The task has been stalled for a long time. Neither Zhongshu Province nor Menxia Province can advance it. Shangshu Province please intervene and coordinate") +- flow_log: "Upgrade to Shangshu Provincial Coordination" + +T+720 (if still unresolved): +scheduler_scan scan again and find: +escalationLevel = 2 (maximum), autoRollback = true + +✅ Phase 4: Automatic rollback +- snapshot.state = 'Assigned' (previous stable state) +- task.state: Zhongshu → Assigned +- dispatch_for_state('JJC-20260228-E2E', 'Assigned', trigger='taizi-auto-rollback') +- flow_log: "Continuous stagnation, automatically rolled back to Assigned, and redistributed by Shangshu Sheng" + +result: +- The Shangshu Province redistributed it to the six ministries for execution +- Zhongshu Province’s solution is retained in the previous snapshot version +- Users can see the rollback operation and decide whether to intervene +``` + +--- + +## 🎯 Part 3: Core API and CLI Tools + +### 3.1 Task operation API endpoint + +#### Task creation: `POST /api/create-task` + +``` +ask: +{ +"title": "Written a complete automated test plan for three provinces and six departments", +"org": "Zhongshu Sheng", // optional, defaults to Prince +"official": "Zhongshu Ling", // optional +"priority": "normal", +"template_id": "test_plan", // optional +"params": {}, +"target_dept": "Ministry of War + Ministry of Punishment" // Optional, send suggestions +} + +response: +{ +"ok": true, +"taskId": "JJC-20260228-001", +"message": "Decree JJC-20260228-001 has been issued and is being distributed to the prince" +} +``` + +#### Task activity flow: `GET /api/task-activity/{task_id}` + +``` +ask: +GET /api/task-activity/JJC-20260228-E2E + +response: +{ +"ok": true, +"taskId": "JJC-20260228-E2E", +"taskMeta": { +"title": "Written a complete automated test plan for three provinces and six departments", +"state": "Assigned", +"org": "Shang Shu Sheng", +"output": "", +"block": "none", +"priority": "normal" +}, +"agent ID": "above", +"agentLabel": "Shang Shu Sheng", + +//── Complete activity flow (59 examples)── +"activity": [ +// flow_log (10 items) +{ +"at": "2026-02-28T10:00:00Z", +"kind": "flow", +"from": "Your Majesty", +"to": "Prince", +"remark": "Declaration: Write a complete automated testing plan for three provinces and six departments" +}, +// progress_log (11 items) +{ +"at": "2026-02-28T10:35:00Z", +"kind": "progress", +"text": "Accepted the order. Analyze the test requirements and formulate a three-layer test plan...", +"Argentina": "Heat stroke", +"agentLabel": "Zhongshu Province", +"state": "Z sweet potato", +"org": "中书省", +"tokens": 4500, +"cost": 0.0045, +"elapsed": 120 +}, +// todos (11 items) +{ +"at": "2026-02-28T15:00:00Z", +"kind": "todos", +"items": [ +{"id": "1", "title": "Requirements Analysis", "status": "completed"}, +{"id": "2", "title": "Project Design", "status": "in-progress"}, +{"id": "3", "title": "await review", "status": "not-started"} +], +"Argentina": "Heat stroke", +"diff": { +"changed": [{"id": "2", "from": "not-started", "to": "in-progress"}], +"added": [], +"removed": [] +} +}, +// session activities (26 items in total) +// - assistant (10 items) +{ +"at": "2026-02-28T14:23:00Z", +"kind": "assistant", +"text": "Based on requirements, I recommend using a three-tier testing architecture:\n1. Unit tests cover core functions\n2. Integration tests cover API endpoints\n3. E2E tests cover the complete process", +"thinking": "💭 Considering the complexity of the project, the interaction logic of seven Agents needs to be covered. The unit test should use pytest, and the integration test should use the HTTP test after server.py is started...", +"tools": [ +{"name": "bash", "input_preview": "find . -name '*.py' -type f | wc -l"}, +{"name": "file_read", "input_preview": "dashboard/server.py (first 100 lines)"} +] +}, +// - tool_result (16 items) +{ +"at": "2026-02-28T14:24:00Z", +"kind": "tool_result", +"tool": "bash", +"exitCode": 0, +"output": "83", +"durationMs": 450 +} +], + +"activitySource": "progress+session", +"related agents": ["Prince", "Heatstroke", "Menxia"], +"phaseDurations": [ +{ +"phase": "Prince", +"durationText": "30 minutes", +"ongoing": false +}, +{ +"phase": "中书省", +"durationText": "4 hours and 32 minutes", +"ongoing": false +}, +{ +"phase": "门下胜", +"durationText": "1 hour and 15 minutes", +"ongoing": false +}, +{ +"phase": "Shang Shu Sheng", +"durationText": "4 hours and 10 minutes", +"ongoing": true +} +], +"totalDuration": "10 hours and 27 minutes", +"todosSummary": { +"total": 3, +"completed": 2, +"inProgress": 1, +"notStarted": 0, +"percent": 67 +}, +"resourceSummary": { +"totalTokens": 18500, +"totalCost": 0.0187, +"totalElapsedSec": 480 +} +} +``` + +#### State advancement: `POST /api/advance-state/{task_id}` + +``` +ask: +{ +"comment": "It's clearly time to move forward with the mission." +} + +response: +{ +"ok": true, +"message": "JJC-20260228-E2E has been advanced to the next stage (Agent has been automatically dispatched)", +"old state": "Z sweet potato", +"newState": "Menxia", +"targetAgent": "menxia" +} +``` + +#### Approval operation: `POST /api/review-action/{task_id}` + +``` +Request (accurate): +{ +"action": "approve", +"comment": "The solution is feasible and improvement suggestions have been adopted" +} + +OR request (rejection): +{ +"action": "reject", +"comment": "Supplementary performance testing is required, Nth round of review" +} + +response: +{ +"ok": true, +"message": "JJC-20260228-E2E has been played (Agent has been automatically dispatched)", +"state": "Assigned", +"reviewRound": 1 +} +``` + +--- + +### 3.2 CLI tool: kanban_update.py + +Agent interacts with the Kanban board through this tool, with a total of 7 commands: + +#### Command 1: Create task (manual by Prince or Zhongshu) + +```bash +python3 scripts/kanban_update.py create \ + JJC-20260228-E2E \ + "为三省六部编写完整自动化测试方案" \ + Zhongshu \ + 中书省 \ + 中书令 + +# Note: Usually there is no need to run it manually (the Kanban API is automatically triggered), unless debugging +``` + +#### Command 2: Update status + +```bash +python3 scripts/kanban_update.py state \ + JJC-20260228-E2E \ + Menxia \ + "方案提交门下省审议" + +# illustrate: +# - First parameter: task_id +# - Second parameter: new status (Pending/Taizi/Zhongshu/...) +# - The third parameter: optional, description information (will be recorded in the now field) +# +# Effect: +# - task.state = Menxia +# - task.org automatically infers "MenxiaSheng" +# - Trigger dispatch of menxia agent +# - flow_log record transfer +``` + +#### Command 3: Add transfer record + +```bash +python3 scripts/kanban_update.py flow \ + JJC-20260228-E2E \ + "中书省" \ + "门下省" \ + "📋 方案提交审核,请审议" + +# illustrate: +# - Parameter 1: task_id +# - Parameter 2: from_dept (who is reporting) +# - Parameter 3: to_dept (who to transfer to) +# - Parameter 4: remark (remarks, can include emoji) +# +# Note: only record flow_log, do not change task.state +# (Mostly used for detail transfer, such as coordination between departments) +``` + +#### Command 4: Real-time progress report (emphasis!) + +```bash +python3 scripts/kanban_update.py progress \ + JJC-20260228-E2E \ + "已完成需求分析和方案初稿,现正征询工部意见" \ + "1.需求分析✅|2.方案设计✅|3.工部咨询🔄|4.待门下审议" + +# illustrate: +# - Parameter 1: task_id +# - Parameter 2: Progress text description +# - Parameter 3: todos current snapshot (separate each item with |, supports emoji) +# +# Effect: +# - progress_log adds new entries: +# { +# "at": now_iso(), +# "agent": inferred_agent_id, +# "text": "The needs analysis and first draft of the plan have been completed, and the opinions of the Ministry of Industry are now being sought", +# "state": task.state, +# "org": task.org, +# "todos": [ +# {"id": "1", "title": "Requirements Analysis", "status": "completed"}, +# {"id": "2", "title": "Project Design", "status": "completed"}, +# {"id": "3", "title": "Ministry of Industry Consulting", "status": "in-progress"}, +# {"id": "4", "title": "To be reviewed", "status": "not-started"} +# ], +# "tokens": (automatically read from openclaw session data), +# "cost": (automatically calculated), +# "elapsed": (automatically calculated) +# } +# +# Kanban effect: +# - Render as active item on the fly +# - todos progress bar update (67% completed) +# - Accumulated display of resource consumption +``` + +#### Command 5: Task completed + +```bash +python3 scripts/kanban_update.py done \ + JJC-20260228-E2E \ + "https://github.com/org/repo/tree/feature/auto-test" \ + "自动化测试方案已完成,涵盖单元/集成/E2E三层,通过率98.5%" + +# illustrate: +# - Parameter 1: task_id +# - Parameter 2: output URL (can be a code repository, document link, etc.) +# - Parameter 3: Final summary +# +# Effect: +# - task.state = Done (advance from Review) +# - task.output = "https://..." +# - Automatically send Feishu message to the emperor (reported by the prince) +# - flow_log records the completed transfer +``` + +#### Command 6 & 7: Stop/Cancel Task + +```bash +# Stop (can be resumed at any time) +python3 scripts/kanban_update.py stop \ + JJC-20260228-E2E \ + "等待工部反馈继续" + +# illustrate: +# - task.state temporary storage (_prev_state) +# - task.block = "Waiting for feedback from the Ministry of Engineering to continue" +# - The board shows "⏸️ Stopped" +# +# recover: +python3 scripts/kanban_update.py resume \ + JJC-20260228-E2E \ + "工部已反馈,继续执行" +# +# - task.state is restored to _prev_state +# - redispatch agent + +# Cancel (unrecoverable) +python3 scripts/kanban_update.py cancel \ + JJC-20260228-E2E \ + "业务需求变更,任务作废" +# +# - task.state = Canceled +# - flow_log records cancellation reasons +``` + +--- + +## 💡 Part 4: Benchmarking and Comparison + +### The traditional approach of CrewAI / AutoGen vs the institutionalized approach of Three Provinces and Six Departments + +| Dimensions | CrewAI | AutoGen | **Three provinces and six departments** | +|------|--------|---------|----------| +| **Collaboration mode** | Free discussion (Agent independently selects collaboration objects) | Panel + callback (Human-in-the-loop) | **Institutionalized collaboration (authority matrix + state machine)** | +| **Quality Assurance** | Rely on Agent intelligence (no review) | Human review (frequent interruptions) | **Automatic review (required review by the province) + Intervention possible** | +| **Permission Control** | ❌ None | ⚠️ Hard-coded | **✅ Configurable Permission Matrix** | +| **Observability** | Low (Agent message black box) | Medium (Human sees the conversation) | **Extremely high (59 activities/tasks)** | +| **Interventionability** | ❌ No (difficult to stop after running) | ✅ Yes (manual approval required) | **✅ Yes (one-click stop/cancel/advance)** | +| **Task Distribution** | Uncertain (Agent selects independently) | Confirmed (Human manual classification) | **Automatically determined (authority matrix + state machine)** | +| **Throughput** | 1 task 1Agent (serial discussion) | 1 task 1Team (requires manual management) | **Multiple tasks in parallel (six tasks executed simultaneously)** | +| **Failure recovery** | ❌ (restart) | ⚠️ (requires manual debugging) | **✅ (automatic retry 3 stages)** | +| **Cost Control** | Opaque (no cost upper limit) | Medium (Human can stop) | **Transparent (cost reported for each progress)** | + +### Strictness of business contracts + +**CrewAI's "gentle" approach** +```python +# Agent can freely choose the next step of work +if task_seems_done: + # Agent decides whether to report to other Agents + send_message_to_someone() # 可能发错人,可能重复 +``` + +**The "strict" approach of three provinces and six ministries** +```python +# The task status is strictly limited, and the next step is determined by the system +if task.state == 'Zhongshu' and agent_id == 'zhongshu': + # Can only do what Zhongshu should do (drafting plan) + deliver_plan_to_menxia() + + #State transfer can only be done through API and cannot be bypassed + # Zhongshu cannot directly transfer to the Minister, it must be reviewed by the subordinates. + + # If you want to bypass the deliberation under the door + try: + dispatch_to(shangshu) # ❌ 权限检查拦截 + except PermissionError: + log.error(f'zhongshu 无权越权调用 shangshu') +``` + +--- + +## 🔍 Part 5: Failure Scenarios and Recovery Mechanism + +### Scenario 1: Agent process crashes + +``` +Symptom: The task is stuck in a certain state and there is no new progress for 180 seconds. +Alarm: Prince dispatch system detects stagnation + +Automatic processing flow: +T+0: crash +T+180: scan detects stall +✅ Phase 1: Automatic retry +- Send messages to the agent (wake up or restart) +- If the agent recovers, the process continues + +T+360: If it is not restored yet +✅ Phase 2: Upgrade coordination +- Wake up the door-to-door agent +- Report: "No response from Zhongshu Province, please intervene" +- The subordinate may take over or act as an agent + +T+540: If it is not restored yet +✅ Phase 3: Upgrade again +- Wake up Shangshu Province agent +- Report: "The task is completely stuck, please coordinate at the enterprise level" + +T+720: If it is not restored yet +✅ Stage 4: Automatic rollback +-Restore to previous stable state +- Distributed to Shangshu Province for reprocessing +- User can see full rollback link +``` + +### Scenario 2: Agent does evil (forged data) + +Suppose the `zhongshu` agent wants to cheat the system: + +```python +# Try to forge the correct performance of Menxiasheng (change JSON directly) +task['flow_log'].append({ + 'from': '门下省', # ❌ 假冒身份 + 'to': '尚书省', + 'remark': '✅ 准奏' +}) + +# System defense: +# 1. Permission verification: API layer checks the identity of the HTTP requester +# ├─ Requests from zhongshu agent cannot flow directly +# ├─ Must be recorded through flow_log and signature verification +# └─ Reject if the signature does not match +# 2. State machine verification: state transition is controlled +# ├─ Even if flow_log is tampered with, the state is still Zhongshu +# ├─ The next step can only be transferred by the gate-keeper system +# └─ zhongshu has no right to change the state by himself + +# Result: ❌ Agent’s forgery is intercepted by the system +``` + +### Scenario 3: Business process violation (such as Zhongshu exceeding his authority and adjusting the Shangshu's reform plan) + +```python +# Zhongshu Sheng wants to bypass the deliberation of the subordinates and directly consult the Shangshu Sheng +try: + result = dispatch_to_agent('shangshu', '请帮我审查一下这个方案') +except PermissionError: + # ❌ Permission matrix interception + log.error('zhongshu 无权调用 shangshu (仅限: menxia, shangshu)') + +# Menxia Sheng wants to upgrade to the Emperor +try: + result = dispatch_to_agent('taizi', '我需要皇上的指示') +except PermissionError: + # ❌ Permission matrix interception + log.error('menxia 无权调用 taizi') +``` + +--- + +## 📊 Part 6: Monitoring and Observability + +### Kanban’s 10 view panels + +``` +1. Full task list +└─ Summary view of all tasks (in reverse order of creation time) +└─ Quick filter: active/completed/rejected + +2. Classification by status +├─ Pending +├─ Taizi (Prince sorting) +├─ Zhongshu (under planning in Zhongshu) +├─ Menxia (under review) +├─ Assigned (distributed by Shangshu) +├─ Doing (six parts in progress) +├─ Review (Shang Shu summary) +└─ Done/Cancelled + +3. Classification by department +├─ Prince’s mission +├─ Zhongshu Provincial Mission +├─ Save tasks under the door +├─ Mission of Shangshu Province +├─ Six tasks (parallel view) +└─ Task assigned + +4. Sort by priority +├─ 🔴 Critical +├─ 🟠 High +├─ 🟡Normal +└─ 🔵 Low (low quality) + +5. Agent online status +├─ 🟢 Running (processing tasks) +├─ 🟡 On call (recently active, idle) +├─ ⚪ Idle (no activity for more than 10 minutes) +├─ 🔴 Offline (Gateway is not started) +└─ ❌ Not configured (workspace does not exist) + +6. Task details panel +├─ Basic information (title, creator, priority) +├─ Complete activity flow (flow_log + progress_log + session) +├─Stage time consumption statistics (residence time of each Agent) +├─ Todos progress bar +└─ Resource consumption (tokens/cost/elapsed) + +7. Monitoring of stalled tasks +├─ List all tasks that have exceeded the threshold and have not been advanced +├─ Show the pause duration +├─ Quick actions: Retry/Upgrade/Rollback + +8. Approval work order pool +├─ List all tasks waiting for approval in Menxia +├─ Sort by length of stay +├─ One-touch accuracy/rejection + +9. Today’s Overview +├─ Number of new tasks created today +├─Number of tasks completed today +├─ Average circulation time +├─ Activity frequency of each Agent + +10. Historical reports +├─ Weekly report (output per capita, average cycle) +├─ Monthly report (department collaboration efficiency) +└─ Cost analysis (API call cost, Agent workload) +``` + +### Real-time API: Agent online detection + +``` +GET /api/agents-status + +response: +{ +"ok": true, +"gateway": { +"alive": true, // The process exists +"probe": true, // HTTP response is normal +"status": "🟢 Running" +}, +"agents": [ +{ +"ID": "Prince", +"label": "Prince", +"status": "running", // running|idle|offline|unconfigured +"statusLabel": "🟢 Running", +"lastActive": "03-02 14:30", // Last active time +"lastActiveTs": 1708943400000, +"sessions": 42, //Number of active sessions +"hasWorkspace": true, +"processAlive": true +}, +// ... other agents ... +] +} +``` + +--- + +## 🎓 Part 7: Usage examples and best practices + +### Complete case: Create→Distribute→Execute→Complete + +```bash +# ═════════════════════════════ ══════════════════════════════ +# Step 1: The Emperor issues an edict (Feishu message or Kanban API) +# ═════════════════════════════ ══════════════════════════════ + +curl -X POST http://127.0.0.1:7891/api/create-task \ + -H "Content-Type: application/json" \ + -d '{ + "title": "编写三省六部协议文档", + "priority": "high" + }' + +# Response: JJC-20260302-001 created +# Prince Agent received the notification: "📜 The Emperor's decree..." + +# ═════════════════════════════ ══════════════════════════════ +# Step 2: The prince receives the order and sorts it (Agent automatically) +# ═════════════════════════════ ══════════════════════════════ + +#Prince Agent's judgment: This is "work intention" (not chatting) +# Automatically run: +python3 scripts/kanban_update.py state \ + JJC-20260302-001 \ + Zhongshu \ + "分拣完毕,转中书省起草" + +# Zhongshu Province Agent received the distribution notification + +# ═════════════════════════════ ══════════════════════════════ +# Step 3: Drafting the letter (Agent work) +# ═════════════════════════════ ══════════════════════════════ + +# Zhongshu Agent analyzes requirements and dismantles tasks + +# First report (after 30 minutes): +python3 scripts/kanban_update.py progress \ + JJC-20260302-001 \ + "已完成需求分析,拟定三部分文档:概述|技术栈|使用指南" \ + "1.需求分析✅|2.文档规划✅|3.内容编写🔄|4.审查待完成" + +# Kanban display: +# - Progress bar: 50% complete +# - Activity flow: add progress + todos entries +# - Consumption: 1200 tokens, $0.0012, 18 minutes + +# Second report (in another 90 minutes): +python3 scripts/kanban_update.py progress \ + JJC-20260302-001 \ + "文档初稿已完成,现提交门下省审议" \ + "1.需求分析✅|2.文档规划✅|3.内容编写✅|4.待审查" + +python3 scripts/kanban_update.py flow \ + JJC-20260302-001 \ + "中书省" \ + "门下省" \ + "提交审议" + +python3 scripts/kanban_update.py state \ + JJC-20260302-001 \ + Menxia \ + "方案提交门下省审议" + +# Men Xia Province Agent received the distribution notice and started deliberation. + +# ═════════════════════════════ ══════════════════════════════ +# Step 4: Deliberation under the sect (Agent work) +# ═════════════════════════════ ══════════════════════════════ + +# MenxiaAgent reviews document quality + +# Review results (after 30 minutes): + +# Scenario A: Accurate performance +python3 scripts/kanban_update.py state \ + JJC-20260302-001 \ + Assigned \ + "✅ 准奏,已采纳改进建议" + +python3 scripts/kanban_update.py flow \ + JJC-20260302-001 \ + "门下省" \ + "尚书省" \ + "✅ 准奏:文档质量良好,建议补充代码示例" + +# Shangshu Province Agent received the distribution + +# Scenario B: Denial +python3 scripts/kanban_update.py state \ + JJC-20260302-001 \ + Zhongshu \ + "🚫 封驳:需补充协议规范部分" + +python3 scripts/kanban_update.py flow \ + JJC-20260302-001 \ + "门下省" \ + "中书省" \ + "🚫 封驳:协议部分过于简略,需补充权限矩阵示例" + +# Zhongshu Province Agent receives the awakening and re-modifies the plan +# (After 3 hours → resubmit for review) + +# ═════════════════════════════ ══════════════════════════════ +# Step 5: Distribution by Minister (Agent work) +# ═════════════════════════════ ══════════════════════════════ + +# Shangshu Province Agent analyzes who the document should be sent to: +# - Department of Rites: Document layout and formatting +# - Ministry of War: Supplementary code examples +# - Ministry of Industry: Deployment Documents + +python3 scripts/kanban_update.py state \ + JJC-20260302-001 \ + Doing \ + "派发给礼部+兵部+工部三部并行执行" + +python3 scripts/kanban_update.py flow \ + JJC-20260302-001 \ + "尚书省" \ + "六部" \ + "派发执行:礼部排版|兵部代码示例|工部基础设施部分" + +# Six Agents received distribution respectively + +# ═════════════════════════════ ══════════════════════════════ +# Step 6: Six executions (parallel) +# ═════════════════════════════ ══════════════════════════════ + +# Etiquette Department Progress Report (20 minutes): +python3 scripts/kanban_update.py progress \ + JJC-20260302-001 \ + "已完成文档排版和目录调整,现待其他部门内容补充" \ + "1.排版✅|2.目录调整✅|3.等待代码示例|4.等待基础设施部分" + +# Ministry of War progress report (40 minutes): +python3 scripts/kanban_update.py progress \ + JJC-20260302-001 \ + "已编写5个代码示例(权限检查、派发流程、session融合等),待集成到文档" \ + "1.分析需求✅|2.编码示例✅|3.集成文档🔄|4.测试验证" + +# Ministry of Industry Progress Report (60 minutes): +python3 scripts/kanban_update.py progress \ + JJC-20260302-001 \ + "已编写Docker+K8s部署部分,Nginx配置和让证书更新文案完成" \ + "1.Docker编写✅|2.K8s配置✅|3.一键部署脚本🔄|4.部署文档待完成" + +# ═════════════════════════════ ══════════════════════════════ +# Step 7: Summary of Shangshu (Agent work) +# ═════════════════════════════ ══════════════════════════════ + +# After all departments have completed their reports, Shangshu Province will summarize all results + +python3 scripts/kanban_update.py progress \ + JJC-20260302-001 \ + "全部部门已完成。汇总成果:\n- 文档已排版,包含9个章节\n- 15个代码示例已集成\n- 完整部署指南已编写\n通过率:100%" \ + "1.排版✅|2.代码示例✅|3.基础设施✅|4.汇总✅" + +python3 scripts/kanban_update.py state \ + JJC-20260302-001 \ + Review \ + "所有部门完成,进入审查阶段" + +# The emperor/prince receives the notice and reviews the final results + +# ═════════════════════════════ ══════════════════════════════ +# Step 8: Completion (final state) +# ═════════════════════════════ ══════════════════════════════ + +python3 scripts/kanban_update.py done \ + JJC-20260302-001 \ + "https://github.com/org/repo/docs/architecture.md" \ + "三省六部协议文档已完成,包含89页,5个阶段历时3天,总消耗成本$2.34" + +# Kanban display: +# - Status: Done ✅ +# - Total time taken: 3 days, 2 hours and 45 minutes +# - Complete activity stream: 79 activity records +# - Resource statistics: 87500 tokens, $2.34, 890 minutes of total working time + +# ═════════════════════════════ ══════════════════════════════ +# Query the final results +# ═════════════════════════════ ══════════════════════════════ + +curl http://127.0.0.1:7891/api/task-activity/JJC-20260302-001 + +# Response: +# { +# "taskMeta": { +# "state": "Done", +# "output": "https://github.com/org/repo/docs/architecture.md" +# }, +# "activity": [79 complete circulation chains], +# "totalDuration": "3 days, 2 hours and 45 minutes", +# "resourceSummary": { +# "totalTokens": 87500, +# "totalCost": 2.34, +# "totalElapsedSec": 53700 +# } +# } +``` + +--- + +## 📋 Summary + +**Three Provinces and Six Ministries is an institutionalized AI multi-Agent system**, not a traditional "free discussion" framework. It passes: + +1. **Business layer**: imitate the ancient imperial bureaucracy and establish an organizational structure with decentralized checks and balances. +2. **Technical layer**: state machine + permission matrix + automatic dispatch + scheduling retry to ensure the process is controllable +3. **Observation layer**: React dashboard + complete activity flow (59 items/task), grasp the overall situation in real time +4. **Intervention layer**: One-click stop/cancel/advance, and can immediately correct any anomalies encountered + +**Core Value**: Use systems to ensure quality, use transparency to ensure confidence, and use automation to ensure efficiency. + +Compared with the "freedom + manual management" of CrewAI/AutoGen, San Province and Six Ministries provides an **enterprise-level AI collaboration framework**. diff --git a/docs/task-dispatch-architecture_EN.md b/docs/task-dispatch-architecture_EN.md new file mode 100644 index 00000000..68cb7484 --- /dev/null +++ b/docs/task-dispatch-architecture_EN.md @@ -0,0 +1,1126 @@ +# Three Departments & Six Ministries Task Dispatch & Flow System · Business and Technical Architecture + +> This document explains in detail how the “Three Departments & Six Ministries” project goes from **institutional/business design** to **code-level implementation details**, and how it handles task dispatch and lifecycle flow for complex multi-Agent collaboration. This is an **institutionalized AI multi-Agent framework**, not a traditional free-form discussion-based collaboration system. + +**Document overview diagram** + +``` +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Business Layer: Imperial Governance Model + ├─ Checks & balances: Emperor → Taizi → Zhongshu → Menxia → Shangshu → Six Ministries + ├─ Institutional constraints: no skipping levels, strict state progression, Menxia must review + └─ Quality guarantees: can veto/reject and send back, fully observable, emergency intervention +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Technical Layer: OpenClaw Multi-Agent Orchestration + ├─ State machine: 9 states (Pending → Taizi → Zhongshu → Menxia → Assigned → Doing/Next → Review → Done/Cancelled) + ├─ Data fusion: flow_log + progress_log + session JSONL → unified activity stream + ├─ Permission matrix: strict controls over subagent invocation + └─ Scheduling layer: auto-dispatch, timeout retries, stall escalation, auto-rollback +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Observability Layer: React Dashboard + Real-time API (Dashboard + Real-time Analytics) + ├─ Task Kanban: 10 view panels (all/by state/by department/by priority, etc.) + ├─ Activity stream: ~59 mixed activity records per task (thinking, tool calls, state transitions) + └─ Online status: real-time agent node detection + heartbeat wake-up mechanism +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +--- + +## 📚 Part 1: Business Architecture + +### 1.1 Imperial Institution: the design philosophy of checks and balances + +#### Core concepts + +Traditional multi-Agent frameworks (such as CrewAI, AutoGen) use a **“free collaboration”** model: +- Agents autonomously pick collaborators +- The framework only provides communication channels +- Quality control depends entirely on agent intelligence +- **Problem**: agents can easily fabricate data, duplicate work, and there is no quality guarantee for plans/solutions + +**Three Departments & Six Ministries** uses an **“institutionalized collaboration”** model, inspired by the ancient imperial bureaucracy: + +``` + Emperor + (User) + │ + ↓ + Taizi (Crown Prince) + [Triage officer, entrypoint owner] + ├─ Identify: is this an edict (command) or casual chat? + ├─ Execute: reply to chat directly || create a task → forward to Zhongshu + └─ Permission: may only call Zhongshu + │ + ↓ + Zhongshu (Secretariat) + [Planning officer, primary drafter] + ├─ Analyze requirements after receiving the edict + ├─ Decompose into subtasks (todos) + ├─ Request Menxia review OR consult Shangshu + └─ Permission: may only call Menxia + Shangshu + │ + ↓ + Menxia (Chancellery) + [Review officer, quality owner] + ├─ Review Zhongshu plan (feasibility, completeness, risks) + ├─ Approve OR Reject (with modification suggestions) + ├─ If rejected → return to Zhongshu to revise → re-review (up to 3 rounds) + └─ Permission: may only call Shangshu + call back Zhongshu + │ + (✅ Approved) + │ + ↓ + Shangshu (Department of State Affairs) + [Dispatch officer, execution commander] + ├─ Receive the approved plan + ├─ Decide which department should execute + ├─ Call the Six Ministries (Rites/Revenue/War/Justice/Works/Personnel) + ├─ Monitor each ministry’s progress → aggregate results + └─ Permission: may only call the Six Ministries (cannot overstep to call Zhongshu) + │ + ├─ Libu (Ministry of Rites) - documentation officer + ├─ Hubu (Ministry of Revenue) - data analysis officer + ├─ Bingbu (Ministry of War) - code implementation officer + ├─ Xingbu (Ministry of Justice) - testing & review officer + ├─ Gongbu (Ministry of Works) - infrastructure officer + └─ Libu_hr (Ministry of Personnel) - HR officer + │ + (Ministries execute in parallel) + ↓ + Shangshu · Aggregation + ├─ Collect results from the ministries + ├─ Transition state to Review + ├─ Call back Zhongshu to report upward to the Emperor + │ + ↓ + Zhongshu · Final report + ├─ Summarize observations, conclusions, suggestions + ├─ Transition state to Done + └─ Reply to the Emperor via Feishu +``` + +#### Four guarantees provided by the institution + +| Guarantee mechanism | Implementation detail | Protection effect | +|---|---|---| +| **Institutional review** | Menxia must review all Zhongshu plans; cannot be skipped | Prevents agents from executing arbitrarily; ensures the plan is feasible | +| **Checks & balances** | Permission matrix: who can call whom is strictly defined | Prevents abuse of power (e.g., Shangshu overstepping to Zhongshu to rewrite the plan) | +| **Full observability** | 10 dashboard panels + ~59 activities per task | See in real-time where the task is stuck, who is working, and current status | +| **Real-time intervention** | One-click stop/cancel/resume/advance inside the dashboard | Emergency correction when an agent goes off-track | + +--- + +### 1.2 Full task lifecycle flow + +#### Flow diagram + +```mermaid +stateDiagram-v2 +[*] --> Pending: Emperor issues an edict +Pending --> Taizi: Taizi receives edict +Taizi --> Zhongshu: Taizi hands to Zhongshu +Zhongshu --> Menxia: Zhongshu submits for review +Menxia --> Zhongshu: Menxia rejects (can repeat) +Menxia --> Assigned: Menxia approves +Assigned --> Doing: Shangshu dispatches execution +Doing --> Review: Ministries complete +Review --> Done: Emperor approves +Review --> Menxia: Emperor requests changes +Done --> [*] +Doing --> [*]: Manual cancellation +Review --> [*]: Business termination +``` + +#### Concrete critical paths + +**✅ Ideal path** (no blocking; completes in 4–5 days) + +``` +DAY 1: + 10:00 - Emperor on Feishu: "Write a full automated testing plan for Three Departments & Six Ministries" + Taizi receives the edict. state = Taizi, org = Taizi + Auto-dispatch taizi agent → handle this edict + + 10:30 - Taizi finishes triage. Determines it is a "work edict" (not casual chat) + Create task JJC-20260228-E2E + flow_log: "Emperor → Taizi: edict issued" + state: Taizi → Zhongshu, org: Taizi → Zhongshu + Auto-dispatch zhongshu agent + +DAY 2: + 09:00 - Zhongshu receives. Starts planning + Progress: "Analyze test requirements; decompose into unit/integration/E2E layers" + progress_log: "Zhongshu Zhang San: split requirements" + + 15:00 - Zhongshu completes the proposal + todos snapshot: requirements analysis✅, plan design✅, pending review🔄 + flow_log: "Zhongshu → Menxia: submit proposal for review" + state: Zhongshu → Menxia, org: Zhongshu → Menxia + Auto-dispatch menxia agent + +DAY 3: + 09:00 - Menxia begins review + Progress: "Now reviewing completeness and risk" + + 14:00 - Menxia completes review + Judgement: "Plan is feasible, but missing tests for _infer_agent_id_from_runtime" + Action: ✅ Approve (with modification suggestions) + flow_log: "Menxia → Shangshu: ✅ Approved (5 suggestions)" + state: Menxia → Assigned, org: Menxia → Shangshu + OPTIONAL: Zhongshu receives suggestions and proactively improves the plan + Auto-dispatch shangshu agent + +DAY 4: + 10:00 - Shangshu receives the approved plan + Analysis: "This test plan should be assigned to Gongbu + Xingbu + Libu" + flow_log: "Shangshu → Six Ministries: dispatch execution (ministry collaboration)" + state: Assigned → Doing, org: Shangshu → Bingbu+Xingbu+Libu + Auto-dispatch bingbu/xingbu/libu agents (parallel) + +DAY 4-5: + (All ministries execute in parallel) + - Bingbu: implement pytest + unittest test frameworks + - Xingbu: write tests covering all key functions + - Libu: produce documentation and test-case descriptions + + Real-time progress (hourly): + - Bingbu: "✅ Implemented 16 unit tests" + - Xingbu: "🔄 Writing integration tests (8/12 completed)" + - Libu: "Waiting for Bingbu to finish before writing report" + +DAY 5: + 14:00 - Ministries finish + state: Doing → Review, org: Bingbu → Shangshu + Shangshu aggregates: "All tests completed; pass rate 98.5%" + Handoff back to Zhongshu + + 15:00 - Zhongshu reports back to the Emperor + state: Review → Done + Template reply to Feishu, including final links and summary +``` + +**❌ Setback path** (includes rejection and retry; 6–7 days) + +``` +DAY 2 same as above + +DAY 3 [rejection scenario]: + 14:00 - Menxia completes review + Judgement: "Plan is incomplete; missing performance tests + stress tests" + Action: 🚫 Reject + review_round += 1 + flow_log: "Menxia → Zhongshu: 🚫 Rejected (must add performance testing)" + state: Menxia → Zhongshu # return to Zhongshu for revision + Auto-dispatch zhongshu agent (re-plan) + +DAY 3-4: + 16:00 - Zhongshu receives the rejection notice (wake agent) + Analyze improvement feedback; add performance testing plan + progress: "Integrated performance testing; revised plan as follows..." + flow_log: "Zhongshu → Menxia: revised plan (round 2 review)" + state: Zhongshu → Menxia + Auto-dispatch menxia agent + + 18:00 - Menxia re-reviews + Judgement: "✅ Approved this time" + flow_log: "Menxia → Shangshu: ✅ Approved (round 2)" + state: Menxia → Assigned → Doing + Subsequent steps follow the ideal path... + +DAY 7: Everything completes (1–2 days later than ideal) +``` + +--- + +### 1.3 Task specification & business contract + +#### Task Schema field description + +```json +{ + "id": "JJC-20260228-E2E", // 任务全局唯一ID (JJC-日期-序号) + "title": "为三省六部编写完整自动化测试方案", + "official": "中书令", // 负责官职 + "org": "中书省", // 当前负责部门 + "state": "Assigned", // 当前状态(见 _STATE_FLOW) + + // ──── 质量与约束 ──── + "priority": "normal", // 优先级:critical/high/normal/low + "block": "无", // 当前阻滞原因(如"等待工部反馈") + "reviewRound": 2, // 门下审议第几轮 + "_prev_state": "Menxia", // 若被 stop,记录之前状态用于 resume + + // ──── 业务产出 ──── + "output": "", // 最终任务成果(URL/文件路径/总结) + "ac": "", // Acceptance Criteria(验收标准) + "priority": "normal", + + // ──── 流转记录 ──── + "flow_log": [ + { + "at": "2026-02-28T10:00:00Z", + "from": "皇上", + "to": "太子", + "remark": "下旨:为三省六部编写完整自动化测试方案" + }, + { + "at": "2026-02-28T10:30:00Z", + "from": "太子", + "to": "中书省", + "remark": "分拣→传旨" + }, + { + "at": "2026-02-28T15:00:00Z", + "from": "中书省", + "to": "门下省", + "remark": "规划方案提交审议" + }, + { + "at": "2026-03-01T09:00:00Z", + "from": "门下省", + "to": "中书省", + "remark": "🚫 封驳:需补充性能测试" + }, + { + "at": "2026-03-01T15:00:00Z", + "from": "中书省", + "to": "门下省", + "remark": "修订方案(第2轮审议)" + }, + { + "at": "2026-03-01T20:00:00Z", + "from": "门下省", + "to": "尚书省", + "remark": "✅ 准奏通过(第2轮,5条建议已采纳)" + } + ], + + // ──── Agent 实时汇报 ──── + "progress_log": [ + { + "at": "2026-02-28T10:35:00Z", + "agent": "zhongshu", // 汇报agent + "agentLabel": "中书省", + "text": "已接旨。分析测试需求,拟定三层测试方案...", + "state": "Zhongshu", // 汇报时的状态快照 + "org": "中书省", + "tokens": 4500, // 资源消耗 + "cost": 0.0045, + "elapsed": 120, + "todos": [ // 待办任务快照 + {"id": "1", "title": "需求分析", "status": "completed"}, + {"id": "2", "title": "方案设计", "status": "in-progress"}, + {"id": "3", "title": "await审议", "status": "not-started"} + ] + } + // ... 更多 progress_log 条目 ... + ], + + // ──── 调度元数据 ──── + "_scheduler": { + "enabled": true, + "stallThresholdSec": 180, // 停滞超过180秒自动升级 + "maxRetry": 1, // 自动重试最多1次 + "retryCount": 0, + "escalationLevel": 0, // 0=无升级 1=门下协调 2=尚书协调 + "lastProgressAt": "2026-03-01T20:00:00Z", + "stallSince": null, // 何时开始停滞 + "lastDispatchStatus": "success", // queued|success|failed|timeout|error + "snapshot": { + "state": "Assigned", + "org": "尚书省", + "note": "review-before-approve" + } + }, + + // ──── 生命周期 ──── + "archived": false, // 是否归档 + "now": "门下省准奏,移交尚书省派发", // 当前实时状态描述 + "updatedAt": "2026-03-01T20:00:00Z" +} +``` + +#### Business contracts + +| Contract | Meaning | Consequence if violated | +|---|---|---| +| **No skipping levels** | Taizi may only call Zhongshu; Zhongshu may only call Menxia/Shangshu; Ministries may not call outward | Overreach calls are rejected; system intercepts automatically | +| **Unidirectional state progression** | Pending → Taizi → Zhongshu → Menxia → Assigned → Doing/Next → Review → Done, cannot skip or backtrack | Only allowed to return one step via review_action(reject) | +| **Menxia must review** | All Zhongshu plans must be reviewed by Menxia; cannot be skipped | Zhongshu cannot send directly to Shangshu; Menxia is mandatory | +| **No changes after Done** | Once Done/Cancelled, state cannot be modified | To change, create a new task or cancel + recreate | +| **task_id uniqueness** | JJC-date-seq is globally unique; no duplicates on same day | Dashboard dedup + auto de-dup | +| **Transparent resource usage** | Every progress report must include tokens/cost/elapsed | Enables cost accounting and performance optimization | + +--- + +## 🔧 Part 2: Technical Architecture + +### 2.1 State machine and automatic dispatch + +#### Complete state transition definition + +```python +_STATE_FLOW = { + 'Pending': ('Taizi', '皇上', '太子', '待处理旨意转交太子分拣'), + 'Taizi': ('Zhongshu','太子', '中书省', '太子分拣完毕,转中书省起草'), + 'Zhongshu': ('Menxia', '中书省', '门下省', '中书省方案提交门下省审议'), + 'Menxia': ('Assigned','门下省', '尚书省', '门下省准奏,转尚书省派发'), + 'Assigned': ('Doing', '尚书省', '六部', '尚书省开始派发执行'), + 'Next': ('Doing', '尚书省', '六部', '待执行任务开始执行'), + 'Doing': ('Review', '六部', '尚书省', '各部完成,进入汇总'), + 'Review': ('Done', '尚书省', '太子', '全流程完成,回奏太子转报皇上'), +} +``` + +Each state automatically maps to an Agent ID (see `_STATE_AGENT_MAP`): + +```python +_STATE_AGENT_MAP = { + 'Taizi': 'taizi', + 'Zhongshu': 'zhongshu', + 'Menxia': 'menxia', + 'Assigned': 'shangshu', + 'Doing': None, # infer from org (one of Six Ministries) + 'Next': None, # infer from org + 'Review': 'shangshu', + 'Pending': 'zhongshu', +} +``` + +#### Automatic dispatch flow + +When a task transitions state (via `handle_advance_state()` or approval), the backend automatically executes dispatch: + +``` +1. State transition triggers dispatch + ├─ Look up _STATE_AGENT_MAP to get target agent_id + ├─ If Doing/Next, infer ministry agent from task.org via _ORG_AGENT_MAP + └─ If cannot infer, skip dispatch (e.g., Done/Cancelled) + +2. Build dispatch message (to push the agent to start immediately) + ├─ taizi: "📜 Emperor's edict needs you to triage..." + ├─ zhongshu: "📜 Edict arrived at Zhongshu; please draft a plan..." + ├─ menxia: "📋 Zhongshu plan submitted for review..." + ├─ shangshu: "📮 Menxia approved; please dispatch execution..." + └─ ministries: "📌 Please handle the task..." + +3. Asynchronous dispatch (non-blocking) + ├─ spawn daemon thread + ├─ set _scheduler.lastDispatchStatus = 'queued' + ├─ verify Gateway process is running + ├─ run: openclaw agent --agent {id} -m "{msg}" --deliver --timeout 300 + ├─ retry up to 2 times (5s backoff between failures) + ├─ update _scheduler status & error information + └─ record dispatch result into flow_log + +4. Dispatch status outcomes + ├─ success: set lastDispatchStatus = 'success' + ├─ failed: record failure reason; agent timeout does not block the dashboard + ├─ timeout: mark timeout; allow manual retry/escalation + ├─ gateway-offline: Gateway not running; skip dispatch (retry later) + └─ error: record stack trace for debugging + +5. Target agent handling + ├─ agent receives notification in Feishu + ├─ interacts with dashboard using kanban_update.py (update state/log progress) + └─ upon completion, triggers dispatch to next agent/state +``` + +--- + +### 2.2 Permission matrix and subagent invocation + +#### Permission definition (configured in openclaw.json) + +```json +{ + "agents": [ + { + "id": "taizi", + "label": "太子", + "allowAgents": ["zhongshu"] + }, + { + "id": "zhongshu", + "label": "中书省", + "allowAgents": ["menxia", "shangshu"] + }, + { + "id": "menxia", + "label": "门下省", + "allowAgents": ["shangshu", "zhongshu"] + }, + { + "id": "shangshu", + "label": "尚书省", + "allowAgents": ["libu", "hubu", "bingbu", "xingbu", "gongbu", "libu_hr"] + }, + { + "id": "libu", + "label": "礼部", + "allowAgents": [] + } + // ... other ministries also have allowAgents = [] ... + ] +} +``` + +#### Permission check mechanism (code-level) + +In addition to `dispatch_for_state()`, there is a defensive permission check layer: + +```python +def can_dispatch_to(from_agent, to_agent): + """Check whether from_agent is allowed to call to_agent.""" + cfg = read_json(DATA / 'agent_config.json', {}) + agents = cfg.get('agents', []) + + from_record = next((a for a in agents if a.get('id') == from_agent), None) + if not from_record: + return False, f'{from_agent} 不存在' + + allowed = from_record.get('allowAgents', []) + if to_agent not in allowed: + return False, f'{from_agent} 无权调用 {to_agent}(允许列表:{allowed})' + + return True, 'OK' +``` + +#### Examples of permission violations and handling + +| Scenario | Request | Result | Reason | +|---|---|---|---| +| **Normal** | Zhongshu → Menxia review | ✅ Allowed | Menxia is in Zhongshu allowAgents | +| **Violation** | Zhongshu → Shangshu to "rewrite plan" | ❌ Denied | Zhongshu cannot override Shangshu work | +| **Violation** | Gongbu → Shangshu: "I'm done" | ✅ State update allowed | via flow_log/progress_log (not cross-agent call) | +| **Violation** | Shangshu → Zhongshu: "rewrite plan" | ❌ Denied | Shangshu is not allowed to call Zhongshu | +| **Defense** | Agent forges another agent’s dispatch | ❌ Intercepted | API layer validates request source/signature | + +--- + +### 2.3 Data fusion: progress_log + session JSONL + +#### Phenomenon + +During execution, there are three layers of data sources: + +``` +1️⃣ flow_log + └─ Pure state transitions (Zhongshu → Menxia) + └─ Source: task JSON field flow_log + └─ Reported by: agents via kanban_update.py flow + +2️⃣ progress_log + └─ Real-time work reports (text progress, todos snapshots, resource usage) + └─ Source: task JSON field progress_log + └─ Reported by: agents via kanban_update.py progress + └─ Frequency: typically every ~30 minutes or at key milestones + +3️⃣ session JSONL (NEW!) + └─ Internal reasoning (thinking), tool calls (tool_result), dialogue history (user) + └─ Source: ~/.openclaw/agents/{agent_id}/sessions/*.jsonl + └─ Produced by: OpenClaw automatically; agents do not need to report manually + └─ Frequency: message-level; finest granularity +``` + +#### Problem diagnosis + +Previously, using only flow_log + progress_log: +- ❌ You cannot see the agent’s concrete reasoning process +- ❌ You cannot see tool calls and their outputs +- ❌ You cannot see intermediate conversation history +- ❌ Agents appear as a “black box” + +Example: progress_log says “analyzing requirements”, but the user cannot see *what* was analyzed. + +#### Solution: fuse session JSONL + +In `get_task_activity()`, fusion logic was added (~40 lines): + +```python +def get_task_activity(task_id): + # ... previous code ... + + # ── Fuse Agent Session activity (thinking / tool_result / user) ── + session_entries = [] + + # Active tasks: attempt exact task_id matching + if state not in ('Done', 'Cancelled'): + if agent_id: + entries = get_agent_activity( + agent_id, limit=30, task_id=task_id + ) + session_entries.extend(entries) + + # Also fetch from related agents + for ra in related_agents: + if ra != agent_id: + entries = get_agent_activity( + ra, limit=20, task_id=task_id + ) + session_entries.extend(entries) + else: + # Completed tasks: keyword matching + title = task.get('title', '') + keywords = _extract_keywords(title) + if keywords: + for ra in related_agents[:5]: + entries = get_agent_activity_by_keywords( + ra, keywords, limit=15 + ) + session_entries.extend(entries) + + # De-dup (use at+kind as key) + existing_keys = {(a.get('at', ''), a.get('kind', '')) for a in activity} + for se in session_entries: + key = (se.get('at', ''), se.get('kind', '')) + if key not in existing_keys: + activity.append(se) + existing_keys.add(key) + + # Re-sort + activity.sort(key=lambda x: x.get('at', '')) + + # Mark activity source + return { + 'activity': activity, + 'activitySource': 'progress+session', + # ... other fields ... + } +``` + +#### Session JSONL format parsing + +Items extracted from JSONL are normalized into dashboard activity entries: + +```python +def _parse_activity_entry(item): + """Normalize a session jsonl message into a dashboard activity entry.""" + msg = item.get('message', {}) + role = str(msg.get('role', '')).strip().lower() + ts = item.get('timestamp', '') + + # 🧠 Assistant role - agent thinking + if role == 'assistant': + entry = { + 'at': ts, + 'kind': 'assistant', + 'text': '...main reply...', + 'thinking': '💭 Agent considered...', + 'tools': [ + {'name': 'bash', 'input_preview': 'cd /src && npm test'}, + {'name': 'file_read', 'input_preview': 'dashboard/server.py (first 100 lines)'}, + ] + } + return entry + + # 🔧 Tool Result + if role in ('toolresult', 'tool_result'): + entry = { + 'at': ts, + 'kind': 'tool_result', + 'tool': 'bash', + 'exitCode': 0, + 'output': '✓ All tests passed (123 tests)', + 'durationMs': 4500 + } + return entry + + # 👤 User + if role == 'user': + entry = { + 'at': ts, + 'kind': 'user', + 'text': 'Please implement exception handling for the test cases' + } + return entry +``` + +#### Activity stream structure after fusion + +Example (task JJC-20260228-E2E) ends up with ~59 activity entries: + +``` +kind count representative events +──────────────────────────────────────────────── +flow 10 state transition chain (Pending→Taizi→Zhongshu→...) +progress 11 agent work reports +todos 11 todo snapshots +user 1 user intervention +assistant 10 agent reasoning/thinking entries +tool_result 16 tool invocation outputs +──────────────────────────────────────────────── +Total 59 full execution trace +``` + +Dashboard benefits: +- 📋 Flow chain: understand which phase the task is in +- 📝 Progress: what the agent says in real time +- ✅ Todos: how the task is decomposed + completion % +- 💭 Assistant/thinking: how the agent reasoned +- 🔧 tool_result: tool call outputs +- 👤 user: whether a human intervened + +--- + +### 2.4 Scheduling system: timeout retries, stall escalation, auto rollback + +#### Scheduler metadata structure + +```python +_scheduler = { + # configuration + 'enabled': True, + 'stallThresholdSec': 180, + 'maxRetry': 1, + 'autoRollback': True, + + # runtime state + 'retryCount': 0, + 'escalationLevel': 0, + 'stallSince': None, + 'lastProgressAt': '2026-03-01T...', + 'lastEscalatedAt': '2026-03-01T...', + 'lastRetryAt': '2026-03-01T...', + + # dispatch tracking + 'lastDispatchStatus': 'success', # queued|success|failed| + 'lastDispatchAgent': 'zhongshu', + 'lastDispatchTrigger': 'state-transition', + 'lastDispatchError': '', + + # snapshot for rollback + 'snapshot': { + 'state': 'Assigned', + 'org': '尚书省', + 'now': '等待派发...', + 'savedAt': '2026-03-01T...', + 'note': 'scheduled-check' + } +} +``` + +#### Scheduling algorithm + +Every 60 seconds, `handle_scheduler_scan(threshold_sec=180)` runs: + +``` +FOR EACH task: + IF state in (Done, Cancelled, Blocked): + SKIP + + elapsed_since_progress = NOW - lastProgressAt + + IF elapsed_since_progress < stallThreshold: + SKIP + + # ── Stall handling ── + IF retryCount < maxRetry: + ✅ RETRY + - increment retryCount + - dispatch_for_state(task, new_state, trigger='taizi-scan-retry') + - flow_log: "stalled 180s, auto-retry #N" + - NEXT + + IF escalationLevel < 2: + ✅ ESCALATE + - nextLevel = escalationLevel + 1 + - target_agent = menxia (if L=1) else shangshu (if L=2) + - wake_agent(target_agent, "💬 task stalled; please intervene") + - flow_log: "escalated to {target_agent}" + - NEXT + + IF escalationLevel >= 2 AND autoRollback: + ✅ AUTO ROLLBACK + - restore task to snapshot.state + - retryCount = 0 + - escalationLevel = 0 + - dispatch_for_state(task, snapshot.state, trigger='taizi-auto-rollback') + - flow_log: "continuous stall; rollback to {snapshot.state}" +``` + +#### Example scenario + +Scenario: Zhongshu agent crashes; task stuck at Zhongshu + +``` +T+0: + Zhongshu planning + lastProgressAt = T + dispatch status = success + +T+30: + agent crashes + +T+60: + scheduler_scan: elapsed 60 < 180, skip + +T+180: + scheduler_scan: elapsed 180 >= 180 + + ✅ Stage 1: retry + - retryCount 0 → 1 + - dispatch_for_state(..., 'Zhongshu', trigger='taizi-scan-retry') + - flow_log records auto-retry + +T+240: + agent recovers; reports progress; lastProgressAt updates + retryCount resets to 0 + +T+360 (if still not recovered): + ✅ Stage 2: escalate to Menxia + +T+540 (if still not resolved): + ✅ Stage 3: escalate to Shangshu + +T+720 (if still not resolved): + ✅ Stage 4: auto rollback to snapshot.state +``` + +--- + +## 🎯 Part 3: Core APIs and CLI tools + +### 3.1 Task operation API endpoints + +#### Create task: `POST /api/create-task` + +``` +Request: +{ + "title": "为三省六部编写完整自动化测试方案", + "org": "中书省", + "official": "中书令", + "priority": "normal", + "template_id": "test_plan", + "params": {}, + "target_dept": "兵部+刑部" +} + +Response: +{ + "ok": true, + "taskId": "JJC-20260228-001", + "message": "旨意 JJC-20260228-001 已下达,正在派发给太子" +} +``` + +#### Task activity stream: `GET /api/task-activity/{task_id}` + +``` +Request: +GET /api/task-activity/JJC-20260228-E2E + +Response: +{ + "ok": true, + "taskId": "JJC-20260228-E2E", + "taskMeta": { + "title": "为三省六部编写完整自动化测试方案", + "state": "Assigned", + "org": "尚书省", + "output": "", + "block": "无", + "priority": "normal" + }, + "agentId": "shangshu", + "agentLabel": "尚书省", + "activity": [ + { + "at": "2026-02-28T10:00:00Z", + "kind": "flow", + "from": "皇上", + "to": "太子", + "remark": "下旨:为三省六部编写完整自动化测试方案" + } + ], + "activitySource": "progress+session" +} +``` + +#### Advance state: `POST /api/advance-state/{task_id}` + +``` +Request: +{ + "comment": "This task should advance" +} + +Response: +{ + "ok": true, + "message": "JJC-20260228-E2E advanced to next stage (agent auto-dispatched)", + "oldState": "Zhongshu", + "newState": "Menxia", + "targetAgent": "menxia" +} +``` + +#### Review action: `POST /api/review-action/{task_id}` + +``` +Request (approve): +{ + "action": "approve", + "comment": "Feasible plan; improvements adopted" +} + +OR request (reject): +{ + "action": "reject", + "comment": "Must add performance testing; round N" +} + +Response: +{ + "ok": true, + "message": "JJC-20260228-E2E approved (agent auto-dispatched)", + "state": "Assigned", + "reviewRound": 1 +} +``` + +--- + +### 3.2 CLI tool: `kanban_update.py` + +Agents use this tool to interact with the dashboard. There are 7 commands. + +#### Command 1: create task (manual by Taizi/Zhongshu) + +```bash +python3 scripts/kanban_update.py create \ + JJC-20260228-E2E \ + "为三省六部编写完整自动化测试方案" \ + Zhongshu \ + 中书省 \ + 中书令 + +# Usually not needed manually (dashboard API triggers it), except for debugging. +``` + +#### Command 2: update state + +```bash +python3 scripts/kanban_update.py state \ + JJC-20260228-E2E \ + Menxia \ + "方案提交门下省审议" +``` + +#### Command 3: add flow log record (without changing state) + +```bash +python3 scripts/kanban_update.py flow \ + JJC-20260228-E2E \ + "中书省" \ + "门下省" \ + "📋 方案提交审核,请审议" +``` + +#### Command 4: real-time progress report (key) + +```bash +python3 scripts/kanban_update.py progress \ + JJC-20260228-E2E \ + "已完成需求分析和方案初稿,现正征询工部意见" \ + "1.需求分析✅|2.方案设计✅|3.工部咨询🔄|4.待门下审议" +``` + +#### Command 5: mark done + +```bash +python3 scripts/kanban_update.py done \ + JJC-20260228-E2E \ + "https://github.com/org/repo/tree/feature/auto-test" \ + "自动化测试方案已完成,涵盖单元/集成/E2E三层,通过率98.5%" +``` + +#### Commands 6 & 7: stop/cancel + resume + +```bash +python3 scripts/kanban_update.py stop \ + JJC-20260228-E2E \ + "等待工部反馈继续" + +python3 scripts/kanban_update.py resume \ + JJC-20260228-E2E \ + "工部已反馈,继续执行" + +python3 scripts/kanban_update.py cancel \ + JJC-20260228-E2E \ + "业务需求变更,任务作废" +``` + +--- + +## 💡 Part 4: Benchmark and comparison + +### CrewAI / AutoGen (traditional) vs institutionalized approach + +| Dimension | CrewAI | AutoGen | **Three Departments & Six Ministries** | +|---|---|---|---| +| Collaboration model | free discussion | panel + callbacks (human-in-loop) | **institutionalized (permission matrix + state machine)** | +| Quality | depends on agents | human review interrupts often | **automatic review (Menxia must review) + intervention** | +| Permissions | ❌ none | ⚠️ hard-coded | **✅ configurable matrix** | +| Observability | low | medium | **very high (~59 activities/task)** | +| Intervention | ❌ hard | ✅ with approvals | **✅ 1-click stop/cancel/advance** | +| Dispatch | uncertain | human manual | **automatic (matrix + state machine)** | +| Throughput | serial-ish | needs human management | **parallel (ministries execute concurrently)** | +| Recovery | restart | manual debug | **✅ retries + escalation + rollback** | +| Cost control | opaque | medium | **transparent (progress reports include cost)** | + +### Strictness of business contracts + +**CrewAI “soft” approach** + +```python +# Agent chooses next step freely +if task_seems_done: + send_message_to_someone() # may pick wrong agent, may duplicate +``` + +**Institutional “strict” approach** + +```python +# State machine controls next step +if task.state == 'Zhongshu' and agent_id == 'zhongshu': + deliver_plan_to_menxia() + + # Attempt to skip Menxia review + try: + dispatch_to(shangshu) # ❌ permission check blocks + except PermissionError: + log.error('zhongshu cannot overstep to shangshu') +``` + +--- + +## 🔍 Part 5: Failure scenarios and recovery mechanisms + +### Scenario 1: agent process crash + +``` +Symptom: task stuck in a state; no progress for 180 seconds +Alert: Taizi scheduler detects stall + +Auto-handling: + T+0: crash + T+180: scan detects stall + ✅ Stage 1: auto retry + ✅ Stage 2: escalate to Menxia + ✅ Stage 3: escalate to Shangshu + ✅ Stage 4: auto rollback +``` + +### Scenario 2: malicious agent (forging data) + +```python +# Fake Menxia approval by directly editing JSON +task['flow_log'].append({ + 'from': '门下省', + 'to': '尚书省', + 'remark': '✅ 准奏' +}) + +# Defenses: +# 1) API layer validates request identity/signature +# 2) State machine remains controlled: even if flow_log is tampered, task.state is unchanged +``` + +### Scenario 3: business violation (overstepping) + +```python +# Zhongshu tries to bypass Menxia and consult Shangshu +try: + dispatch_to_agent('shangshu', 'Please review this plan') +except PermissionError: + log.error('zhongshu cannot call shangshu') + +# Menxia tries to call Taizi +try: + dispatch_to_agent('taizi', 'Need Emperor guidance') +except PermissionError: + log.error('menxia cannot call taizi') +``` + +--- + +## 📊 Part 6: Monitoring and observability + +### 10 dashboard view panels + +``` +1. All tasks list +2. By state +3. By department +4. By priority +5. Agent online status +6. Task detail panel (full activity stream) +7. Stalled task monitor +8. Review queue +9. Today overview +10. Historical reports +``` + +### Real-time API: agent status detection + +``` +GET /api/agents-status + +Response: +{ + "ok": true, + "gateway": { + "alive": true, + "probe": true, + "status": "🟢 running" + }, + "agents": [ + { + "id": "taizi", + "label": "太子", + "status": "running", + "statusLabel": "🟢 running", + "lastActive": "03-02 14:30", + "lastActiveTs": 1708943400000, + "sessions": 42, + "hasWorkspace": true, + "processAlive": true + } + ] +} +``` + +--- + +## 🎓 Part 7: Usage examples and best practices + +### End-to-end example: create → dispatch → execute → complete + +```bash +# Create task via API +curl -X POST http://127.0.0.1:7891/api/create-task \ + -H "Content-Type: application/json" \ + -d '{ + "title": "编写三省六部协议文档", + "priority": "high" + }' + +# ... then agent-driven kanban_update.py usage as shown ... +``` + +--- + +## 📋 Summary + +**Three Departments & Six Ministries is an institutionalized AI multi-Agent system**, not a traditional “free discussion” framework. It provides: + +1. **Business layer**: a bureaucracy-inspired org structure with checks and balances +2. **Technical layer**: state machine + permission matrix + auto-dispatch + scheduler retries to keep workflow controlled +3. **Observability layer**: React dashboard + rich activity streams (≈59 entries/task) +4. **Intervention layer**: one-click stop/cancel/advance to correct issues fast + +**Core value**: ensure quality through institution, ensure confidence through transparency, and ensure efficiency through automation. + +Compared to CrewAI/AutoGen’s “free + human management”, this is an **enterprise-grade AI collaboration framework**. diff --git a/docs/wechat-article_EN-googletrans.md b/docs/wechat-article_EN-googletrans.md new file mode 100644 index 00000000..bb54f6aa --- /dev/null +++ b/docs/wechat-article_EN-googletrans.md @@ -0,0 +1,302 @@ +# I redesigned the AI multi-agent collaboration architecture using the three provinces and six departments system + +> The system design from 1,300 years ago understood decentralization better than the modern AI framework. + + + +--- + +## 1. A strange idea + +At the end of last year, I started using AI Agent heavily for work - writing code, doing analysis, and generating documents. It uses some of the most popular multi-agent frameworks on the market. + +After using it for a month, I discovered a fundamental problem: + +**These frameworks do not have the concept of "audit". ** + +The model of CrewAI is: several Agents work on their own, and then hand over the work after completion. AutoGen is better, it has Human-in-the-loop, but essentially you are your own QA. MetaGPT has roles, but review is optional. + +Just like a company without a QA department, engineers write the code and deploy it directly online. + +Then you get the final result, and you don’t know what happened in the middle. You can’t reproduce it, audit it, or intervene. If something goes wrong, you can only run again. + +I have been wondering: Is there a structure that naturally embeds auditing into the process, not as an optional plug-in, but as a level that must be passed? + +Then one day, when I was reading "Zi Zhi Tong Jian", I suddenly thought - + +**Three provinces and six ministries. ** + +Emperor Taizong of the Tang Dynasty designed this system 1,300 years ago: Zhongshu Province drafts decrees, Menxia Province reviews and approves them, and Shangshu Province executes them. The three departments check and balance each other, and any decree must be reviewed before being issued. + +Isn't this the architecture I'm looking for? + + +*▲ When you open the billboard for the first time every day, there will be an opening animation of "Going to court" - full of sense of ritual* + +--- + +## 2. Architectural design of the ancients + +The system of three provinces and six ministries is not a metaphor, it is a system of decentralized checks and balances that has been tested in practice for 1,400 years. + +To simplify, the information flow looks like this: + +``` +Your Majesty (you) +↓ Decree +Zhongshu Sheng (Planning) ← Break your sentence into executable subtasks +↓ Submit for review +Menxia Province (Deliberation) ← Review the quality of the plan, and reject it if it is not good +↓ Accurate performance +Shangshu Province (distribution) ← assigned to six ministries for execution +↓ +Six Departments (Execution) ← The Ministry of Accounts is in charge of data, the Ministry of Rites is in charge of documents, the Ministry of War is in charge of development, the Ministry of Punishment is in charge of compliance, and the Ministry of Industry is in charge of infrastructure. +↓ +Summary of responses from Shangshu Province ← The results will be reported to you +``` + +Pay attention to the most critical step here: **Provincial review**. + +After the Zhongshu Ministry plans the plan, it is not thrown directly to the executive level - it must first be reviewed by the subordinate ministry. Provincial inspection under the door: + +- Is the splitting of subtasks reasonable? Are there any missing requirements? +- Are department assignments accurate? Was the one assigned to the Military Department mistakenly assigned to the Ministry of Rites? +- Is the plan executable? Is there anything unrealistic? + +If it is unqualified, the Ministry of Education can reject it - directly reject it and ask Zhongshu Province to make a new plan. It's not a warning, it's a forced rework. + +This is why the Tang Dynasty functioned for 289 years. **Unrestrained power is bound to make mistakes**, Tang Taizong thought clearly. + +--- + +## 3. I made it an open source project + +I used OpenClaw to build a real system with three provinces and six departments. The 9 AI Agents each perform their own duties and communicate strictly in accordance with the permission matrix. + +The project is called **Edict (three provinces and six departments)** and has been open source: + +**GitHub: https://github.com/cft0808/edict** + +The core architecture is simple: + +- **Zhongshu Sheng**: receive orders (your instructions), plan plans, and dismantle subtasks +- **Menxiasheng**: Review the plan, check the quality, and reject it directly if it is not qualified. +- **Shang Shu Sheng**: After the report is accurate, it will be distributed to the six departments to coordinate the implementation and summarize the results. +- **Six departments**: Ministry of Finance (data analysis), Ministry of Rites (document writing), Ministry of War (code development), Ministry of Justice (security and compliance), Ministry of Industry (CI/CD deployment) +- **Morning Official**: Send you a news briefing every day + +Each Agent has independent Workspace, independent Skills, and independent LLM model. Strict permission matrix - who can send messages to whom, written in black and white: + +| Who ↓ To whom → | Zhongshu | Menxia | Shangshu | Liubu | +|:---:|:---:|:---:|:---:|:---:| +| **中书省** | — | ✅ | ✅ | ❌ | +| **MenxiaSheng** | ✅ | — | ✅ | ❌ | +| **Shang Shu Sheng** | ✅ | ✅ | — | ✅ | +| **六片** | ❌ | ❌ | ✅ | ❌ | + +The Zhongshu Provincial Department cannot directly command the Sixth Department, and the Sixth Department cannot report to the Zhongshu Provincial Department directly. All cross-layer communications must be relayed through Shangshu Province. + +**This is not a decorative setting, it is a mandatory constraint at the architectural level. ** + + +*▲ 30-second Demo: a complete tour from the court ceremony to the decree board, memorial archives, and model configuration* + +--- + +## 4. Comparison with existing frameworks + +You may ask: Compared with CrewAI and AutoGen, what is the difference? + +| | CrewAI | AutoGen | **Three provinces and six departments** | +|---|:---:|:---:|:---:| +| Audit mechanism | ❌ | ⚠️ Optional | ✅ Mandatory audit in Menha Province | +| Live dashboard | ❌ | ❌ | ✅ 10 panels | +| Task Intervention | ❌ | ❌ | ✅ Stop/Cancel/Resume | +| Transfer audit | ⚠️ | ❌ | ✅ Complete memorial archive | +| Agent Health Monitoring | ❌ | ❌ | ✅ Heartbeat Detection | +| Hot Switch LLM | ❌ | ❌ | ✅ One-click switching within the board | + +The core difference is **the provincial review mechanism**. + +This is not Human-in-the-loop (that’s asking yourself to be the QA), this is a dedicated AI Agent responsible for reviewing the output of another AI Agent. Institutional, mandatory, architectural level. + +An AI collaboration system without review is like a team without code review - it runs fast and overturns quickly. + +--- + +## 5. Bulletin Board at the Military Aircraft Department - Make everything observable + +It’s not enough to have a structure, you also have to be able to see it. + +So I made a **Military Aircraft Department Dashboard** - a web panel that monitors the flow of all tasks in real time. Zero dependencies, single file HTML, Python standard library backend, just open the browser and use it. + +10 function panels: + +**📋 Purpose Board**: All tasks are displayed in the form of cards, sorted by status, and filter search is supported. Each card has a heartbeat badge - 🟢 Active, 🟡 Stalled, 🔴 Alarm. Click to see the complete circulation timeline, and you can stop or cancel at any time. + + +*▲ Purpose board: task cards are sorted by status, and heartbeat badges are clear at a glance* + +**🔭 Provincial and Department Scheduling**: Visualize the number of tasks, department distribution, and Agent health cards in each status. See at a glance who is busy, who is idle, and who is down. + + +*▲ Provincial dispatch: status distribution + department load + Agent health card* + +**📜 Memorial Pavilion**: All completed edicts are automatically archived as "Memorials", showing a complete five-stage timeline - Imperial edict → Zhongshu planning → Subordinate review → Six-part execution → Echo. Copy to Markdown with one click. + + +*▲ Memorial Pavilion: Complete five-stage timeline, one-click export to Markdown* + +**📜 Edict Library**: 9 preset edict templates. Choose one, fill in the parameters, preview, and make an order with one click. Covers: common scenarios such as weekly report generation, code review, API design, competitive product analysis, etc. + + +*▲Purpose library: 9 preset templates, fill in the parameters and make a decree with one click* + +**⚙️ Model configuration**: Each Agent can switch LLM models independently. The Ministry of Education uses Claude for planning, the Ministry of War uses GPT-4o to write code, and the Ministry of Household Affairs uses DeepSeek to calculate data - each draws on its strengths. + + +*▲ Model configuration: Each Agent switches LLM independently, each taking advantage of their own strengths* + +There are also official overview (Token consumption ranking list), skill management, world news (automatic news aggregation), session monitoring, and court ceremony (the Easter egg animation that is opened for the first time every day). + +**All zero dependencies**, no React or Vue, pure HTML + CSS + JavaScript, completed in 2200 lines. + + +*▲ Official Overview: Token Consumption Ranking + Activity Statistics* + + +*▲World News: Daily automatic aggregation of technology/financial information* + +--- + +## 6. Let me show you a real case + +Just talking without practicing is not enough. Let’s take a look at a real operating record - let three provinces and six departments analyze competing products. + +**Purpose**: Analyze the differences between the three frameworks CrewAI, AutoGen and LangGraph and output a comparison report. + + +*▲ Click on any task card to see the complete flow chain and real-time status* + +### Zhongshu Provincial Planning (45 seconds) + +After receiving the order, Zhongshu Province split it into four sub-tasks: +1. Ministry of War → Research on architecture and communication mechanism +2. Account Department → Data collection and quantitative comparison (GitHub Stars, Contributors, etc.) +3. Ministry of War → In-depth evaluation of developer experience +4. Department of Etiquette → Summarize and write a comparison report + +### Menxia Provincial Review (32 seconds) - rejected! + +**The first round of Menxia Province was directly returned:** + +> *"The plan has three problems: 1) The purpose clearly requires the evaluation of 'observability', but there is no corresponding sub-task in the plan; 2) Sub-tasks 1 and 3 are both Ministry of War research, there is overlap, and it is recommended to merge; 3) There is a lack of conclusive sub-task of recommended scenarios - analysis without conclusion means no analysis. Rejected."* + +After the Zhongshu Province revised the plan, the second round of the Menxia Province was accurate. + +**This is the value of door-to-door savings. ** Without this step, the Ministry of War will conduct two surveys, and there will be no recommended scenarios in the final report - because there is no requirement in the original plan. + +### Execution of each department (17 minutes) + +- **Ministry of War**: In-depth technical comparison, covering the three dimensions of architecture, communication, and observability +- **Household Department**: Quantitative data table - Stars, Contributors, Issue response time, Hello World construction time +- **Ministry of Rites**: Integrate data from the Ministry of War + Ministry of Household Affairs and write the final report + +### Echo + +22 minutes, 15800 Tokens, a structured comparison report. The conclusion is very interesting: + +| Scenario | Recommendation | Reason | +|------|------|------| +| Rapid Prototyping | CrewAI | The fastest to get started | +| Conversational collaboration | AutoGen | Naturally suitable for multi-round discussions | +| Complex workflow | LangGraph | State machine is the most flexible | +| **Reliability first** | **Three provinces and six departments** | The only built-in mandatory audit | + +--- + +## 7. Some technical choices + +When working on this project, I made several deliberate technical decisions: + +**1. Zero dependencies** + +The Kanban front-end is an HTML file, 2200 lines long, without any framework. The backend is `http.server` of the Python standard library, without Flask or FastAPI. + +Why? Because I don't want people to `pip install` a bunch of things before running. The target users of this project may just want to quickly experience the circulation effect of three provinces and six movies, and do not want to set up the environment. + +**2. One SOUL.md for each Agent** + +Each Agent's personality, responsibilities, and workflow rules are written in a Markdown file. Want to modify the review standards of Phnom Penh Province? Edit `agents/menxia/SOUL.md` and it will automatically take effect next time you start it. + +This means that you can customize your own three provinces and six departments - maybe your "Ministry of War" is not responsible for engineering, but for market analysis. Just change SOUL.md. + +**3. Permission matrix is mandatory** + +It is not "recommended" not to communicate across levels between agents, it is a mandatory restriction at the architectural level. The Sixth Ministry cannot send messages to the Zhongshu Province, and the Zhongshu Province cannot bypass the Menxia Province and directly ask the Shangshu Province to implement it. OpenClaw's configuration file says in black and white who can talk to whom. + +--- + +## 8. Now you can try + +The project is open source and licensed under the MIT license. + +**GitHub: https://github.com/cft0808/edict** + +The fastest way to experience: + +```bash +# Docker starts with one line +docker run -p 7891:7891 cft0808/edict + +# Open browser +open http://localhost:7891 +``` + +If you have OpenClaw installed, you can install it completely: + +```bash +git clone https://github.com/cft0808/edict.git +cd edict +chmod +x install.sh && ./install.sh +``` + +The installation script automatically creates 9 Agent Workspaces, writes personality files, registers the permission matrix, and restarts the Gateway. + + +*▲Skills management: List of installed Skills in each province and department, you can view details and add new skills* + +--- + +## 9. Next step + +Phase 1 (core architecture) has been completed. Next few things to do: + +- **Imperial Approval Mode**: The review results of Menxiasheng can be pushed to your Feishu/Telegram, and you can decide whether to approve or reject it yourself. +- **Accomplishment and Failure Book**: Each Agent's performance score - completion rate, rework rate, time-consuming statistics +- **Express Delivery Shop**: Add a real-time Agent communication flow diagram to the bulletin board - when Zhongshu Province sends a message to Menxia Province, the connection will light up +- **National History Museum**: historical decrees and memorials are accumulated into a knowledge base, and new decrees can refer to historical experience + +The complete Roadmap is on GitHub. Each sub-item of Phase 2 and Phase 3 is marked with difficulty. You are welcome to claim it. + +--- + +## at last + +The core issue of AI Agent collaboration is not "making the Agent smarter", but "making the Agent's collaboration have rules." + +CrewAI solves the problem of "multiple Agents working together". AutoGen solves the problem of "agents being able to talk to each other". + +But who will solve the problem of "Agent's output quality is guaranteed"? + +Emperor Taizong of the Tang Dynasty gave the answer 1,300 years ago: **separation of powers, checks and balances**. What is planned is not reviewed, what is reviewed is not implemented, and what is implemented is not planned. Someone is watching every step, and every decision must be reviewed. + +This is probably the most elegant "AI governance" solution I've ever seen - because it wasn't designed for AI at all. + +It is designed for governance itself. + +--- + +**GitHub: https://github.com/cft0808/edict** + +Open Source · MIT · Welcome Star ⚔️ diff --git a/docs/wechat_EN-googletrans.md b/docs/wechat_EN-googletrans.md new file mode 100644 index 00000000..6855217d --- /dev/null +++ b/docs/wechat_EN-googletrans.md @@ -0,0 +1,77 @@ +# 📮 My Dibao——Public account "cft0808" + +> *In ancient times, there were official reports to spread government decrees, but now there are public accounts talking about AI architecture. * + +
+
+
+👆 Scan the QR code on WeChat and enter North Korea immediately
+
+⚔️ I asked the AI to go to court, but the result was that the AI was worse than me
+Follow the official account and see how I control the 12 AI ministers
+
+
({liveStatus:null,agentConfig:null,changeLog:[],officialsData:null,agentsStatusData:null,morningBrief:null,subConfig:null,activeTab:"edicts",edictFilter:"active",sessFilter:"all",tplCatFilter:"全部",selectedOfficial:null,modalTaskId:null,countdown:5,toasts:[],setActiveTab:u=>{o({activeTab:u});const k=p();["models","skills","sessions"].includes(u)&&!k.agentConfig&&k.loadAgentConfig(),u==="officials"&&!k.officialsData&&k.loadOfficials(),u==="monitor"&&k.loadAgentsStatus(),u==="morning"&&!k.morningBrief&&k.loadMorning()},setEdictFilter:u=>o({edictFilter:u}),setSessFilter:u=>o({sessFilter:u}),setTplCatFilter:u=>o({tplCatFilter:u}),setSelectedOfficial:u=>o({selectedOfficial:u}),setModalTaskId:u=>o({modalTaskId:u}),setCountdown:u=>o({countdown:u}),toast:(u,k="ok")=>{const S=++Ff;o(D=>({toasts:[...D.toasts,{id:S,msg:u,type:k}]})),setTimeout(()=>{o(D=>({toasts:D.toasts.filter(F=>F.id!==S)}))},3e3)},loadLive:async()=>{try{const u=await fe.liveStatus();o({liveStatus:u}),p().officialsData||fe.officialsStats().then(S=>o({officialsData:S})).catch(()=>{})}catch{}},loadAgentConfig:async()=>{try{const u=await fe.agentConfig(),k=await fe.modelChangeLog();o({agentConfig:u,changeLog:k})}catch{}},loadOfficials:async()=>{try{const u=await fe.officialsStats();o({officialsData:u})}catch{}},loadAgentsStatus:async()=>{try{const u=await fe.agentsStatus();o({agentsStatusData:u})}catch{o({agentsStatusData:null})}},loadMorning:async()=>{try{const[u,k]=await Promise.all([fe.morningBrief(),fe.morningConfig()]);o({morningBrief:u,subConfig:k})}catch{}},loadSubConfig:async()=>{try{const u=await fe.morningConfig();o({subConfig:u})}catch{}},loadAll:async()=>{const u=p();await u.loadLive();const k=u.activeTab;["models","skills"].includes(k)&&await u.loadAgentConfig()}}));let Er=null;function Bf(){Er||(q.getState().loadAll(),Er=setInterval(()=>{const o=q.getState(),p=o.countdown-1;p<=0?(o.setCountdown(5),o.loadAll()):o.setCountdown(p)},1e3))}function Wf(){Er&&(clearInterval(Er),Er=null)}function Uf(o){if(!o)return"";try{const p=new Date(o.includes("T")?o:o.replace(" ","T")+"Z");if(isNaN(p.getTime()))return"";const u=Date.now()-p.getTime(),k=Math.floor(u/6e4);if(k<1)return"刚刚";if(k<60)return k+"分钟前";const S=Math.floor(k/60);return S<24?S+"小时前":Math.floor(S/24)+"天前"}catch{return""}}const ic={Doing:0,Review:1,Assigned:2,Menxia:3,Zhongshu:4,Taizi:5,Inbox:6,Blocked:7,Next:8,Done:9,Cancelled:10};function Hf({task:o}){const p=Gi(o);return l.jsx("div",{className:"ec-pipe",children:p.map((u,k)=>l.jsxs("span",{style:{display:"contents"},children:[l.jsxs("div",{className:`ep-node ${u.status}`,children:[l.jsx("div",{className:"ep-icon",children:u.icon}),l.jsx("div",{className:"ep-name",children:u.dept})]}),k
+ 用 开放 的生态,赋能 制度化 的 AI 协作 +
+{t.output}
+ {task.output}
+
+
+
+ 👆 微信扫码,即刻入朝
+
+ ⚔️ 朕让 AI 上朝,结果 AI 比朕还卷
+ 关注公众号,看朕如何驾驭 12 个 AI 大臣
+
+
https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/skills/brainstorming/SKILL.md
+
+ 三省六部欢迎各路英雄好汉 ⚔️
+ 无论是修一个 typo 还是设计一个新的 Agent 角色,我们都万分感谢
+
+ 感谢每一位贡献者,你们是三省六部的基石 ⚔️ +
+
+ I modeled an AI multi-agent system after China's 1,300-year-old imperial governance.
Turns out, ancient bureaucracy understood separation of powers better than modern AI frameworks.
+
+ 12 AI agents (11 business roles + 1 compatibility role) form the Three Departments & Six Ministries: Crown Prince triages, Planning proposes, Review vetoes, Dispatch assigns, Ministries execute.
Built-in institutional review gates that CrewAI doesn't have. A real-time dashboard that AutoGen doesn't have.
+
+ 🎬 Demo · + 🚀 Quick Start · + 🏛️ Architecture · + 📋 Features · + 中文 · + Contributing +
+ +
+
+
+
+
+
+
+
+
+
+
+
+ 🎥 Full demo: AI Multi-Agent collaboration with Three Departments & Six Ministries
+
+
+
+ Issue edict → Crown Prince triage → Planning → Review → Ministries execute → Report back (30s)
+
+
+
+ Scan to follow · cft0808
+
+ ⚔️ Governing AI with the wisdom of ancient empires
+ 以古制御新技,以智慧驾驭 AI
+
+
+ 我用 1300 年前的帝国制度,重新设计了 AI 多 Agent 协作架构。
结果发现,古人比现代 AI 框架更懂分权制衡。
+
+ 12 个 AI Agent(11 个业务角色 + 1 个兼容角色)组成三省六部:太子分拣、中书省规划、门下省审核封驳、尚书省派发、六部+吏部并行执行。
比 CrewAI 多一层制度性审核,比 AutoGen 多一个实时看板。
+
+ 🎬 看 Demo · + 🚀 30 秒体验 · + 🏛️ 架构 · + 📋 看板功能 · + 📚 架构文档 · + English · + 参与贡献 +
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+ 🎥 三省六部 AI 多 Agent 协作全流程演示
+
+
+
+ 飞书下旨 → 太子分拣 → 中书省规划 → 门下省审议 → 六部并行执行 → 奏折回报(30 秒)
+
| + +**📋 旨意看板 · Kanban** +- 按状态列展示全部任务 +- 省部过滤 + 全文搜索 +- 心跳徽章(🟢活跃 🟡停滞 🔴告警) +- 任务详情 + 完整流转链 +- 叫停 / 取消 / 恢复操作 + + | + +**🔭 省部调度 · Monitor** +- 可视化各状态任务数量 +- 部门分布横向条形图 +- Agent 健康状态实时卡片 + + |
| + +**📜 奏折阁 · Memorials** +- 已完成旨意自动归档为奏折 +- 五阶段时间线:圣旨→中书→门下→六部→回奏 +- 一键复制为 Markdown +- 按状态筛选 + + | + +**📜 旨库 · Template Library** +- 9 个预设圣旨模板 +- 分类筛选 · 参数表单 · 预估时间和费用 +- 预览旨意 → 一键下旨 + + |
| + +**👥 官员总览 · Officials** +- Token 消耗排行榜 +- 活跃度 · 完成数 · 会话统计 + + | + +**📰 天下要闻 · News** +- 每日自动采集科技/财经资讯 +- 分类订阅管理 + 飞书推送 + + |
| + +**⚙️ 模型配置 · Models** +- 每个 Agent 独立切换 LLM +- 应用后自动重启 Gateway(~5秒生效) + + | + +**🛠️ 技能配置 · Skills** +- 各省部已安装 Skills 一览 +- 查看详情 + 添加新技能 + + |
| + +**💬 小任务 · Sessions** +- OC-* 会话实时监控 +- 来源渠道 · 心跳 · 消息预览 + + | + +**🎬 上朝仪式 · Ceremony** +- 每日首次打开播放开场动画 +- 今日统计 · 3.5秒自动消失 + + |
exec format error?(点击展开)
+
+
+ 👆 扫码关注「cft0808」—— 朕的技术邸报
+
+ ⚔️ 以古制御新技,以智慧驾驭 AI
+ Governing AI with the wisdom of ancient empires
+
+