doukui 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +42 -0
  3. package/README.md +147 -2
  4. package/bin/commands/build.js +178 -0
  5. package/bin/commands/config.js +88 -0
  6. package/bin/commands/help.js +83 -0
  7. package/bin/commands/init.js +194 -0
  8. package/bin/commands/install.js +202 -0
  9. package/bin/commands/interactive.js +352 -0
  10. package/bin/commands/list.js +108 -0
  11. package/bin/commands/loop-server.js +357 -0
  12. package/bin/commands/loop.js +1398 -0
  13. package/bin/commands/migrate.js +120 -0
  14. package/bin/commands/setup-global.js +81 -0
  15. package/bin/commands/status.js +140 -0
  16. package/bin/commands/team-cleanup.js +190 -0
  17. package/bin/commands/validate-config.js +35 -0
  18. package/bin/commands/validate.js +21 -0
  19. package/bin/commands/version.js +22 -0
  20. package/bin/context.js +143 -0
  21. package/bin/doukui.js +216 -0
  22. package/package.json +47 -4
  23. package/plugins/contracts/capabilities.js +268 -0
  24. package/plugins/contracts/checkresult-schema.json +75 -0
  25. package/plugins/contracts/config-schema.json +179 -0
  26. package/plugins/contracts/plugin-interface.js +262 -0
  27. package/plugins/contracts/plugin-schema.json +104 -0
  28. package/plugins/core/hook-session-start/index.js +281 -0
  29. package/plugins/core/hook-session-start/plugin.json +7 -0
  30. package/plugins/core/hook-skill-gate/index.js +661 -0
  31. package/plugins/core/hook-skill-gate/plugin.json +12 -0
  32. package/plugins/core/provider-loop-engine/index.js +1397 -0
  33. package/plugins/core/provider-loop-engine/plugin.json +15 -0
  34. package/plugins/core/provider-memory-store/index.js +510 -0
  35. package/plugins/core/provider-memory-store/plugin.json +9 -0
  36. package/plugins/core/provider-role-registry/index.js +376 -0
  37. package/plugins/core/provider-role-registry/plugin.json +9 -0
  38. package/plugins/core/provider-state-store/index.js +244 -0
  39. package/plugins/core/provider-state-store/plugin.json +9 -0
  40. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +32 -0
  41. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +676 -0
  42. package/plugins/core/provider-watchdog/assets/watchdog.js +754 -0
  43. package/plugins/core/provider-watchdog/index.js +151 -0
  44. package/plugins/core/provider-watchdog/plugin.json +13 -0
  45. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +214 -0
  46. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +249 -0
  47. package/plugins/core/skill-agent-dispatcher/plugin.json +13 -0
  48. package/plugins/core/skill-agent-dispatcher/roles-reference.md +253 -0
  49. package/plugins/core/skill-agent-dispatcher/skill.md +1291 -0
  50. package/plugins/core/skill-agentic-loop/plugin.json +20 -0
  51. package/plugins/core/skill-agentic-loop/skill.md +572 -0
  52. package/plugins/core/skill-batch-task-creator/plugin.json +15 -0
  53. package/plugins/core/skill-batch-task-creator/skill.md +620 -0
  54. package/plugins/core/skill-checklist/plugin.json +10 -0
  55. package/plugins/core/skill-checklist/skill.md +171 -0
  56. package/plugins/core/skill-completion-report/plugin.json +10 -0
  57. package/plugins/core/skill-completion-report/skill.md +331 -0
  58. package/plugins/core/skill-doukui-plan/plugin.json +15 -0
  59. package/plugins/core/skill-doukui-plan/skill.md +233 -0
  60. package/plugins/core/skill-doukui-sync/plugin.json +10 -0
  61. package/plugins/core/skill-doukui-sync/skill.md +76 -0
  62. package/plugins/core/skill-experience-logger/plugin.json +10 -0
  63. package/plugins/core/skill-experience-logger/skill.md +235 -0
  64. package/plugins/core/skill-human-checkpoint/plugin.json +10 -0
  65. package/plugins/core/skill-human-checkpoint/skill.md +194 -0
  66. package/plugins/core/skill-progress-tracker/plugin.json +10 -0
  67. package/plugins/core/skill-progress-tracker/skill.md +228 -0
  68. package/plugins/core/skill-role-manager/plugin.json +10 -0
  69. package/plugins/core/skill-role-manager/skill.md +252 -0
  70. package/plugins/core/skill-split-work-package/plugin.json +15 -0
  71. package/plugins/core/skill-split-work-package/skill.md +441 -0
  72. package/plugins/core/skill-task-archive/plugin.json +10 -0
  73. package/plugins/core/skill-task-archive/skill.md +116 -0
  74. package/plugins/core/skill-task-creator/plugin.json +15 -0
  75. package/plugins/core/skill-task-creator/skill.md +886 -0
  76. package/plugins/core/skill-team-cleanup/plugin.json +10 -0
  77. package/plugins/core/skill-team-cleanup/skill.md +266 -0
  78. package/plugins/core/skill-watchdog-manager/plugin.json +10 -0
  79. package/plugins/core/skill-watchdog-manager/skill.md +143 -0
  80. package/plugins/core/skill-workflow-orchestrator/plugin.json +13 -0
  81. package/plugins/core/skill-workflow-orchestrator/skill.md +273 -0
  82. package/plugins/core/validator-doc-sync/index.js +248 -0
  83. package/plugins/core/validator-doc-sync/plugin.json +12 -0
  84. package/plugins/core/validator-work-package/index.js +300 -0
  85. package/plugins/core/validator-work-package/plugin.json +12 -0
  86. package/plugins/plugin-registry.json +186 -0
  87. package/plugins/runtime/agent-def-generator.js +150 -0
  88. package/plugins/runtime/audit-logger.js +311 -0
  89. package/plugins/runtime/build-cli.js +89 -0
  90. package/plugins/runtime/checkresult-validator.js +131 -0
  91. package/plugins/runtime/claude-md-injector.js +159 -0
  92. package/plugins/runtime/cleanup-utils.js +293 -0
  93. package/plugins/runtime/config-manager.js +317 -0
  94. package/plugins/runtime/config-validator.js +320 -0
  95. package/plugins/runtime/context-window.js +81 -0
  96. package/plugins/runtime/event-bus.js +207 -0
  97. package/plugins/runtime/executor-claude.js +828 -0
  98. package/plugins/runtime/executor-default.js +448 -0
  99. package/plugins/runtime/executor-local.js +178 -0
  100. package/plugins/runtime/executor-sdk.js +390 -0
  101. package/plugins/runtime/harness-build.js +1037 -0
  102. package/plugins/runtime/hook-dispatcher.js +315 -0
  103. package/plugins/runtime/logger.js +192 -0
  104. package/plugins/runtime/loop-actuator.js +292 -0
  105. package/plugins/runtime/loop-coordinator.js +347 -0
  106. package/plugins/runtime/loop-defaults.js +29 -0
  107. package/plugins/runtime/loop-dispatch-batch.js +247 -0
  108. package/plugins/runtime/loop-executor.js +120 -0
  109. package/plugins/runtime/loop-report.js +327 -0
  110. package/plugins/runtime/loop-server-core.js +750 -0
  111. package/plugins/runtime/loop-snapshot.js +581 -0
  112. package/plugins/runtime/loop-trace.js +242 -0
  113. package/plugins/runtime/loop-worktree.js +404 -0
  114. package/plugins/runtime/manifest-resolver.js +457 -0
  115. package/plugins/runtime/multi-window-coordinator.js +560 -0
  116. package/plugins/runtime/objective-verifier.js +136 -0
  117. package/plugins/runtime/plan-reader.js +763 -0
  118. package/plugins/runtime/plugin-loader.js +798 -0
  119. package/plugins/runtime/plugin-trust.js +182 -0
  120. package/plugins/runtime/plugin-validator.js +491 -0
  121. package/plugins/runtime/provider-failover.js +114 -0
  122. package/plugins/runtime/provider-resolver.js +342 -0
  123. package/plugins/runtime/reflection-evaluator.js +540 -0
  124. package/plugins/runtime/resolve-plugin-path.js +297 -0
  125. package/plugins/runtime/safe-path.js +119 -0
  126. package/plugins/runtime/sandbox-context.js +235 -0
  127. package/plugins/runtime/sandbox-manager.js +609 -0
  128. package/plugins/runtime/sandbox-worker.js +215 -0
  129. package/plugins/runtime/settings-merger.js +172 -0
  130. package/plugins/runtime/state-store.js +527 -0
  131. package/plugins/runtime/team-cleanup.js +497 -0
  132. package/plugins/runtime/text-tokenize.js +25 -0
  133. package/plugins/runtime/validator-pipeline.js +475 -0
  134. package/plugins/runtime/yaml-parser.js +692 -0
  135. package/templates/harness-config.yaml +388 -0
@@ -0,0 +1,151 @@
1
+ 'use strict';
2
+
3
+ const ProviderPlugin = require('../../contracts/plugin-interface').ProviderPlugin;
4
+
5
+ /**
6
+ * Watchdog Provider Plugin
7
+ *
8
+ * Provides watchdog daemon status query API.
9
+ * When enabled and built, deploys watchdog assets to .claude/watchdog/.
10
+ */
11
+ class WatchdogProvider extends ProviderPlugin {
12
+ constructor() {
13
+ super();
14
+ this.name = 'provider-watchdog';
15
+ this.version = '0.1.0';
16
+ this.description = 'Watchdog Daemon Provider';
17
+ this.provides = 'provider:watchdog';
18
+ }
19
+
20
+ async onActivate(context) {
21
+ this._context = context;
22
+ context.logger.info('WatchdogProvider activated');
23
+ }
24
+
25
+ async factory(context) {
26
+ const fs = require('fs');
27
+ const path = require('path');
28
+
29
+ return {
30
+ /**
31
+ * 读取配置中的 heartbeat_dir,回退到默认值
32
+ * @private
33
+ * @returns {string}
34
+ */
35
+ _getHeartbeatDir: function () {
36
+ const configPath = path.join('.claude-daemon', 'daemon-config.json');
37
+ if (fs.existsSync(configPath)) {
38
+ try {
39
+ const cfg = JSON.parse(fs.readFileSync(configPath, 'utf8'));
40
+ return cfg.heartbeat_dir || '.claude-daemon';
41
+ } catch (e) {
42
+ // 解析失败,使用默认值
43
+ }
44
+ }
45
+ return '.claude-daemon';
46
+ },
47
+
48
+ /**
49
+ * 检查 watchdog 是否已部署到目标项目
50
+ * @returns {boolean}
51
+ */
52
+ isDeployed: function () {
53
+ const watchdogPath = path.join('.claude', 'watchdog', 'watchdog.js');
54
+ return fs.existsSync(watchdogPath);
55
+ },
56
+
57
+ /**
58
+ * 获取 watchdog 部署路径
59
+ * @returns {string}
60
+ */
61
+ getDeployPath: function () {
62
+ return path.join('.claude', 'watchdog');
63
+ },
64
+
65
+ /**
66
+ * 获取守护进程状态文件路径
67
+ * @returns {string}
68
+ */
69
+ getStatusFilePath: function () {
70
+ return path.join(this._getHeartbeatDir(), 'daemon-status.json');
71
+ },
72
+
73
+ /**
74
+ * 读取守护进程状态对象(原始 status.json),失败降级为 null。
75
+ * 供 getHealth / isRunning 共用,避免重复解析。
76
+ * @private
77
+ * @returns {object|null}
78
+ */
79
+ _readStatus: function () {
80
+ const statusFile = this.getStatusFilePath();
81
+ if (!fs.existsSync(statusFile)) {
82
+ return null;
83
+ }
84
+ try {
85
+ return JSON.parse(fs.readFileSync(statusFile, 'utf8'));
86
+ } catch (e) {
87
+ return null;
88
+ }
89
+ },
90
+
91
+ /**
92
+ * 查询守护进程健康(design.md §6.3.2,WP-174-5)。
93
+ *
94
+ * 返回三态健康模型,供 loop-engine 熔断判定区分 degraded:
95
+ * - 'healthy' : health 未终止,且心跳不过期
96
+ * - 'degraded' : health 非终止但心跳过期(持续 degraded 触发熔断)
97
+ * - 'terminated' : health === 'terminated',或状态文件缺失/损坏
98
+ *
99
+ * 同时保留 `running` 布尔(等价于旧的 isRunning 语义:health !== 'terminated'),
100
+ * 便于只关心"是否完全挂掉"的调用方平滑迁移。
101
+ *
102
+ * @returns {{ state: 'healthy'|'degraded'|'terminated', running: boolean, health?: string, stale?: boolean, raw?: object }}
103
+ */
104
+ getHealth: function () {
105
+ const STALE_THRESHOLD_MS = 120000; // 与 multi-window-coordinator 心跳过期阈值一致
106
+ const status = this._readStatus();
107
+ if (!status) {
108
+ return { state: 'terminated', running: false };
109
+ }
110
+ const health = status.health || 'unknown';
111
+ if (health === 'terminated') {
112
+ return { state: 'terminated', running: false, health: health, raw: status };
113
+ }
114
+ // 非终止:检查心跳新鲜度以区分 healthy / degraded
115
+ var stale = false;
116
+ if (status.last_update || status.last_heartbeat || status.updated_at) {
117
+ var ts = status.last_update || status.last_heartbeat || status.updated_at;
118
+ var age = Date.now() - new Date(ts).getTime();
119
+ if (!isNaN(age) && age > STALE_THRESHOLD_MS) {
120
+ stale = true;
121
+ }
122
+ }
123
+ return {
124
+ state: stale ? 'degraded' : 'healthy',
125
+ running: true,
126
+ health: health,
127
+ stale: stale,
128
+ raw: status,
129
+ };
130
+ },
131
+
132
+ /**
133
+ * 检查守护进程是否正在运行(向后兼容)。
134
+ *
135
+ * 语义保持不变:health !== 'terminated'(即未完全挂掉即视为 running,
136
+ * 不因心跳过期返回 false —— 否则会破坏现有只关心"完全终止"的调用方)。
137
+ * 需要区分 healthy/degraded 的调用方应改用 getHealth()。
138
+ * @returns {boolean}
139
+ */
140
+ isRunning: function () {
141
+ const status = this._readStatus();
142
+ if (!status) {
143
+ return false;
144
+ }
145
+ return status.health !== 'terminated';
146
+ }
147
+ };
148
+ }
149
+ }
150
+
151
+ module.exports = WatchdogProvider;
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "provider-watchdog",
3
+ "version": "1.0.0",
4
+ "type": "provider",
5
+ "description": "Watchdog 守护进程 Provider - 为 Agent Teams 提供外部监控、故障检测和自动重启能力",
6
+ "dependencies": [],
7
+ "provides": ["provider:watchdog"],
8
+ "metadata": {
9
+ "deploy_assets": true,
10
+ "deploy_path": "watchdog"
11
+ },
12
+ "config": {}
13
+ }
@@ -0,0 +1,214 @@
1
+ # Agent Dispatcher — 清理参考(逻辑销毁 + 历史残留目录清理)
2
+
3
+ > 本文档由 `skill-agent-dispatcher` 在 Step 7 阶段按需读取,不作为独立 skill 触发。
4
+
5
+ ---
6
+
7
+ ## ⚠️ 权限要求
8
+
9
+ 本 skill 的 Step 7 清理流程需要 Bash 工具权限来:
10
+ - 验证目录是否存在 (`test -d`)
11
+ - 调用 `team-cleanup` CLI 执行文件系统级删除(**CLI 直接走 fs.rmSync,不调用 TeamDelete**——该工具已从 harness 移除)
12
+
13
+ > **Step 7f 的文件系统删除由 `node bin/doukui.js team-cleanup <team> --force` 执行**——该 CLI 是 Node 进程,**绕过 harness Bash 权限系统**,无需在 settings.json 添加 `Bash(rm -rf ...)` 权限条目。只需 `Bash(node bin/doukui.js team-cleanup ...)` 一条。
14
+
15
+ > ⚠️ **implicit session team 模式下的清理范围**: 当前 session 的 implicit team 随 session 自动清理,**本流程主要针对历史残留的显式/UUID 团队目录**(如旧的 `cybershop-wp101`、UUID 命名团队)。若 `team_name` 是当前 session 的批次标签(非真实 harness 团队目录),目录可能不存在,Step 7a 条件 2 会返回 `NOT_FOUND` 并正常跳过。
16
+
17
+ **建议权限配置**(添加到 settings.json 的 `permissions.allow` 中):
18
+ ```json
19
+ {
20
+ "allow": [
21
+ "Bash(test -d $HOME/.claude/teams/*)",
22
+ "Bash(test -d $HOME/.claude/tasks/*)",
23
+ "Bash(rm -rf $HOME/.claude/teams/*)",
24
+ "Bash(rm -rf $HOME/.claude/tasks/*)"
25
+ ]
26
+ }
27
+ ```
28
+
29
+ 如果权限被拒绝,清理流程会提示用户手动执行 `清理团队`。
30
+
31
+ ---
32
+
33
+ ## Step 7: 清理团队 (🔴 强制执行 + 验证)
34
+
35
+ <HARD-GATE>
36
+ Teamee 逻辑销毁必须完成 + 残留目录清理必须验证结果!
37
+ 注意:大部分 Teamee 已在 Step 6.5 监控循环中即时销毁。
38
+ 此步骤负责:① 确认 teamee_map 已空;② 对历史残留团队目录执行 team-cleanup CLI 并验证。
39
+ 当前 session 的 implicit team 随 session 自动清理,无需 TeamDelete(工具也已移除)。
40
+ 不信任 CLI 返回值,必须用 Bash 检查目录是否真的被删除!
41
+ 以下步骤必须按顺序逐一执行,不可跳过!
42
+ </HARD-GATE>
43
+
44
+ > **设计说明**: 以下使用显式步骤而非循环,确保 AI agent 能忠实执行每一步。
45
+ > 路径使用 `$HOME` 变量(Git Bash 兼容 Windows)。
46
+
47
+ ---
48
+
49
+ ### Step 7a: 安全检查(3 个前置条件)
50
+
51
+ **条件 1** — `team_name` 非空且仅含合法字符 `[a-zA-Z0-9_-]`
52
+ - 失败 → 打印 `❌ 错误:team_name 无效` → 提示手动执行 `清理团队` → **停止**
53
+
54
+ **条件 2** — 历史残留团队目录存在(当前 session team 通常不存在于此路径)
55
+ - 用 Bash 检查: `test -d "$HOME/.claude/teams/$team_name" && echo "EXISTS" || echo "NOT_FOUND"`
56
+ - 返回 `NOT_FOUND` → 打印 `ℹ️ 团队目录不存在(当前 session implicit team 由 session 自动管理,此路径仅历史残留显式团队占用),跳过` → **停止**
57
+
58
+ **条件 3** — 路径安全验证
59
+ - 用 Bash 检查: `basename "$HOME/.claude/teams/$team_name"` 应返回 `$team_name`
60
+ - 不匹配 → 打印 `❌ 安全检查失败:路径异常` → 提示手动执行 `清理团队` → **停止**
61
+
62
+ 全部通过 → 继续 Step 7b
63
+
64
+ ---
65
+
66
+ ### Step 7b: 清空映射表 (逻辑销毁残留 Teamee)
67
+
68
+ 残留 Teamee 已无需发送协议帧——直接清空映射表,in-process Teamee 随 session 终止:
69
+ ```
70
+ # 无协议帧;in-process Teamee 随 session 自然终止
71
+ teamee_map.clear()
72
+ # ── 状态输出(直接文本输出,禁止使用 SendMessage)──
73
+ # 输出: "映射表已清空(残留 Teamee 随 session 终止)"
74
+ ```
75
+
76
+ > 不再读取团队配置发 orphan shutdown——映射表不一致的孤儿成员会在后续 team-cleanup CLI 的目录级清理中被一并删除。
77
+
78
+ ---
79
+
80
+ ### Step 7c: (已删除) 无需等待 shutdown 响应
81
+
82
+ 逻辑销毁(Step 7b `teamee_map.clear()`)无协议帧,无需等待响应,直接进入残留目录清理(Step 7d)。
83
+
84
+ ---
85
+
86
+ ### Step 7d: 执行 team-cleanup CLI(第 1 次)
87
+
88
+ > TeamDelete 工具已从 harness 移除,本步骤直接调用 team-cleanup CLI 执行文件系统删除(CLI 内部走 fs.rmSync,**不调用 TeamDelete**)。
89
+
90
+ ```
91
+ Bash(command="node {package_root}/bin/doukui.js team-cleanup {team_name} --force")
92
+ ```
93
+
94
+ **验证** — 用 Bash 检查目录是否真的被删除:
95
+ ```bash
96
+ test -d "$HOME/.claude/teams/$team_name" && echo "EXISTS" || echo "GONE"
97
+ test -d "$HOME/.claude/tasks/$team_name" && echo "EXISTS" || echo "GONE"
98
+ ```
99
+
100
+ - 两个都返回 `GONE`(或 Step 7a 已确认 NOT_FOUND 而本次 CLI 返回 "No team artifacts found")→ 打印 `✅ 清理成功(验证通过)` → **跳到 Step 7g**
101
+ - 任一返回 `EXISTS` → 继续 Step 7e
102
+
103
+ ---
104
+
105
+ ### Step 7e: 执行 team-cleanup CLI(第 2 次,等待 2 秒后重试)
106
+
107
+ ```
108
+ Bash(command="node {package_root}/bin/doukui.js team-cleanup {team_name} --force")
109
+ ```
110
+
111
+ **验证** — 同 Step 7d 的 Bash 检查。
112
+
113
+ - 两个都返回 `GONE` → 打印 `✅ 清理成功(第 2 次尝试)` → **跳到 Step 7g**
114
+ - 任一返回 `EXISTS` → 继续 Step 7f
115
+
116
+ ---
117
+
118
+ ### Step 7f: 再次执行 team-cleanup CLI(Step 7d/7e 失败后的最终重试)
119
+
120
+ 打印 `🔥 team-cleanup CLI 两次未完成清理,执行最终重试...`
121
+
122
+ **安全确认** — 再次验证路径:
123
+ ```bash
124
+ basename "$HOME/.claude/teams/$team_name"
125
+ ```
126
+ - 返回值不等于 `$team_name` → 打印 `❌ 安全检查失败` → 提示手动执行 `清理团队` → **停止**
127
+
128
+ **执行删除**(调用确定性 CLI,封装跨平台 `fs.rmSync` + 安全校验,绕过 Bash 权限系统):
129
+ ```
130
+ Bash(command="node {package_root}/bin/doukui.js team-cleanup {team_name} --force")
131
+ ```
132
+
133
+ 该 CLI 直接走文件系统删除(fs.rmSync,带 basename / 字符集 / 路径穿越校验,**不调用 TeamDelete**——工具已移除)。如果 CLI 仍失败:
134
+ - 打印 `⚠️ team-cleanup CLI 执行失败`
135
+ - 提示用户手动执行 `清理团队` 或 `rm -rf "$HOME/.claude/teams/$team_name" "$HOME/.claude/tasks/$team_name"`
136
+
137
+ ---
138
+
139
+ ### Step 7g: 最终验证
140
+
141
+ 用 Bash 确认两个目录都已清除:
142
+ ```bash
143
+ test -d "$HOME/.claude/teams/$team_name" && echo "STILL_EXISTS" || echo "CLEAN"
144
+ test -d "$HOME/.claude/tasks/$team_name" && echo "STILL_EXISTS" || echo "CLEAN"
145
+ ```
146
+
147
+ - 两个都返回 `CLEAN` → 打印 `✅ 清理流程完成`
148
+ - 任一返回 `STILL_EXISTS` → 打印 `❌ 清理失败!请手动执行: 清理团队`
149
+
150
+ ---
151
+
152
+ ### Step 7h: 记录清理日志
153
+
154
+ 记录清理结果到执行报告(成功/失败、尝试次数、使用的方法)。
155
+
156
+ ---
157
+
158
+ ## Error Handling
159
+
160
+ ### 循环依赖
161
+ ```
162
+ ❌ 检测到循环依赖: WP-037 → WP-038 → WP-039 → WP-037
163
+ 请手动解除依赖关系后重试。
164
+ ```
165
+
166
+ ### Teamee 执行失败
167
+ ```
168
+ ⚠️ Task #2 执行失败
169
+ Owner: godot-script-expert-t2
170
+ 状态: in_progress (卡住)
171
+ 处理: Lead 调 markTeameeDestroyed 逻辑销毁该 Teamee(无协议帧)
172
+ 从 teamee_map 移除映射
173
+ 创建新 Teamee 重试 或 人工介入
174
+ ```
175
+
176
+ ### 部分任务超时
177
+ ```
178
+ ⚠️ Task #3 等待依赖超时
179
+ 依赖: Task #2 (状态: in_progress, 超过 30 分钟)
180
+ 处理: 检查 Task #2 的 Teamee 状态
181
+ 必要时发送消息确认进度
182
+ ```
183
+
184
+ ### 清理超时
185
+ ```
186
+ ⚠️ 清理等待超时(30秒)
187
+ 可能原因:
188
+ - Teamee 进程卡死(逻辑销毁已移除映射,但进程未退出)
189
+ - team-cleanup CLI 多次失败(文件系统级删除受阻,如目录被占用)
190
+
191
+ 处理:
192
+ - 强制执行 team-cleanup CLI(不是 rm -rf!)
193
+ - 建议用户检查是否有残留进程
194
+ - 检查 Step 5 是否使用了正确的 subagent_type
195
+ ```
196
+
197
+ ---
198
+
199
+ ## Cleanup Guarantee (清理保障)
200
+
201
+ ```
202
+ ┌─────────────────────────────────────────────────────────────┐
203
+ │ 强制清理检查点 │
204
+ │ │
205
+ │ ✅ 正常完成 → Step 6.5 即时逻辑销毁 → Step 7 历史残留 CLI │
206
+ │ ✅ 部分失败 → Step 6.5 即时逻辑销毁 → Step 7 历史残留 CLI │
207
+ │ ✅ 超时 → Step 6.5 超时逻辑销毁 → Step 7 强制 CLI │
208
+ │ ✅ 异常中断 → 捕获中断 → Step 7 强制逻辑销毁残留 + CLI │
209
+ │ │
210
+ │ ❌ 无任何情况可以跳过 Teamee 逻辑销毁! │
211
+ │ (当前 session implicit team 随 session 自动清理; │
212
+ │ team-cleanup CLI 仅清理历史残留显式/UUID 团队目录) │
213
+ └─────────────────────────────────────────────────────────────┘
214
+ ```
@@ -0,0 +1,249 @@
1
+ # Dispatcher Daemon Helpers Reference (DISP-001/002/003)
2
+
3
+ > 本文件是 skill-agent-dispatcher Step 6.6 的按需参考(渐进式加载,WP-D6)。监控循环主体仍在本体 skill.md;本文件的辅助函数**仅在实现守护进程集成时 Read**。
4
+
5
+ ### Step 6.6: 守护进程辅助函数 (DISP-001/002/003)
6
+
7
+ 以下辅助函数用于守护进程集成,在监控循环中被调用:
8
+
9
+ #### get_process_pid()
10
+ 获取当前进程 PID,用于心跳写入。
11
+
12
+ ```
13
+ def get_process_pid():
14
+ """获取当前进程 PID"""
15
+ # 方法 1: 通过 Bash 工具
16
+ result = Bash(command="echo $$")
17
+ return int(result.strip())
18
+
19
+ # 方法 2: 通过环境变量 (如果可用)
20
+ # return int(os.getenv("PID", "unknown"))
21
+ ```
22
+
23
+ #### now_iso8601()
24
+ 获取当前时间的 ISO 8601 格式字符串。
25
+
26
+ ```
27
+ def now_iso8601():
28
+ """返回当前时间的 ISO 8601 格式字符串"""
29
+ from datetime import datetime, timezone
30
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
31
+ ```
32
+
33
+ #### create_task_file()
34
+ 创建任务状态文件,用于守护进程监控单个任务进度。
35
+
36
+ ```
37
+ def create_task_file(task_id, wp_id, teamee_name, status, complexity_score):
38
+ """创建或初始化任务状态文件"""
39
+ task_data = {
40
+ "task_id": str(task_id),
41
+ "wp_id": wp_id,
42
+ "teamee_name": teamee_name,
43
+ "status": status,
44
+ "complexity_score": complexity_score,
45
+ "progress_markers": [
46
+ {
47
+ "time": now_iso8601(),
48
+ "action": "started",
49
+ "detail": f"Teamee {teamee_name} 开始执行"
50
+ }
51
+ ],
52
+ "retry_count": 0,
53
+ "max_retries": 3,
54
+ "retry_history": [],
55
+ "idle_nudge_sent": False, # idle 催促去重位(WP-183-2-impl F3):本 idle 窗口内是否已催促过,重 spawn 后由 update_task_file(reset_started_at=True) 顺带重置
56
+ "started_at": now_iso8601(),
57
+ "last_update": now_iso8601()
58
+ }
59
+ Write(
60
+ file_path=f".claude-daemon/tasks/task-{task_id}.json",
61
+ content=json_dumps(task_data, indent=2)
62
+ )
63
+ ```
64
+
65
+ #### update_task_file()
66
+ 更新任务状态文件,支持状态更新、追加进度标记、递增重试计数、刷新 idle 计时起点、设置/重置 idle 催促去重位。
67
+
68
+ ```
69
+ def update_task_file(task_id, status=None, increment_retry=False, append_marker=None,
70
+ reset_started_at=False, set_idle_nudge=None):
71
+ """更新任务状态文件
72
+
73
+ 扩展参数(idle 自愈流程,WP-183-2-impl F3/F4 修复):
74
+ - reset_started_at: 重 spawn 后刷新 started_at 为 now_iso8601(),
75
+ 使新 Teamee 获得完整 idle_threshold 执行窗口,避免一出生即满足 idle 阈值(F4)。
76
+ TaskList task 对象不携带时间字段,started_at 是 idle 计时的权威起点(见 F2)。
77
+ - set_idle_nudge: True/False。True=记录本轮已催促(去重位),
78
+ False=重 spawn 后重置为未催促,让新 Teamee 有一次催促机会(F3)。
79
+ """
80
+ task_path = f".claude-daemon/tasks/task-{task_id}.json"
81
+ existing_data = Read(file_path=task_path)
82
+ try:
83
+ task_data = json_loads(existing_data)
84
+ except Exception as e:
85
+ # ── 状态输出(直接文本输出,禁止使用 SendMessage)──
86
+ # 输出: "⚠️ 任务状态文件解析失败,跳过更新: {e}"
87
+ return
88
+
89
+ # 更新状态
90
+ if status:
91
+ task_data["status"] = status
92
+
93
+ # 递增重试计数
94
+ if increment_retry:
95
+ task_data["retry_count"] += 1
96
+ task_data["retry_history"].append({
97
+ "time": now_iso8601(),
98
+ "iteration": loop_iteration
99
+ })
100
+
101
+ # 追加进度标记
102
+ if append_marker:
103
+ task_data["progress_markers"].append({
104
+ "time": now_iso8601(),
105
+ "action": append_marker.get("action", "update"),
106
+ "detail": append_marker.get("detail", "")
107
+ })
108
+
109
+ # 刷新 idle 计时起点(F4):重 spawn 后让新 Teamee 重新获得 idle_threshold 窗口
110
+ if reset_started_at:
111
+ task_data["started_at"] = now_iso8601()
112
+
113
+ # 设置/重置 idle 催促去重位(F3):True=已催促本窗口,False=重 spawn 后清位
114
+ if set_idle_nudge is not None:
115
+ task_data["idle_nudge_sent"] = bool(set_idle_nudge)
116
+
117
+ task_data["last_update"] = now_iso8601()
118
+ Write(file_path=task_path, content=json_dumps(task_data, indent=2))
119
+ ```
120
+
121
+ #### read_task_file()
122
+ 读取任务状态文件并解析为 dict(供 idle 检测读取 `started_at`/`idle_nudge_sent` 等权威字段)。
123
+ TaskList 返回的 task 对象不携带 `assigned_at`/`started_at` 等时间字段,idle 计时起点
124
+ 必须从任务状态文件读取(WP-183-2-impl F2 修复)。
125
+
126
+ ```
127
+ def read_task_file(task_id):
128
+ """读取任务状态文件,返回 dict;文件不存在/解析失败返回 {}"""
129
+ task_path = f".claude-daemon/tasks/task-{task_id}.json"
130
+ if not file_exists(task_path):
131
+ return {}
132
+ try:
133
+ return json_loads(Read(file_path=task_path))
134
+ except Exception:
135
+ return {}
136
+ ```
137
+
138
+ #### expected_product_path()
139
+ 返回 task 的预期产物路径,供 idle 检测的 `Glob(expected_product_path(task))` 判定产物是否已生成。
140
+ **WP-183-2-impl F1 修复**:WP 文档体系当前无"预期产物路径"声明字段,assignment 对象亦无该字段,
141
+ 故此处降级为弱信号——返回 None 时,idle 检测的 `not product_exists` 恒为 True,产物判定退化为
142
+ "task 状态文件 `last_update` 长时间未变 + 无新增 progress_marker"(由 assigned_at 比对 idle_threshold 体现)。
143
+
144
+ TODO(后续 WP):若 WP 文档体系引入产物路径声明(如 assignment.expected_products 或 WP 文档
145
+ `预期产物:` 列表),将本函数改为从该字段返回 Glob 路径,使 idle 检测升级为强信号产物判定。
146
+
147
+ ```
148
+ def expected_product_path(task):
149
+ """返回 task 的预期产物路径;WP 文档体系暂无产物路径声明字段,降级返回 None(弱信号,F1)
150
+
151
+ 降级理由:assignment 对象(role_id/role_prompt/memories/wp_doc_path/complexity_score/
152
+ subagent_type/team_name/prompt)与 WP 文档当前均无产物路径字段,引入新字段需扩大改动范围
153
+ 且与运行时不符。返回 None 时 Glob 调用方应将 product_exists 视为"未知→按停滞判定"。
154
+ """
155
+ # TODO: WP 文档体系引入产物路径声明后,从 assignment.expected_products 或 WP 文档读取
156
+ return None
157
+ ```
158
+
159
+ > **调用方约定(idle 检测段)**:`expected_product_path(task)` 返回 None 时,idle 段不依赖
160
+ > `Glob` 的返回值判定产物存在性,而是退化为时间+进度弱信号(`task_stalled` 中
161
+ > `not product_exists` 对 None 结果恒 True,故停滞判定仅依赖 status 与时间阈值)。
162
+
163
+ #### build_resume_prompt()
164
+ 为复杂任务的 checkpoint_resume 重启策略构建 prompt,注入已完成文件上下文 + 失败项重点修复段(refine 通道,WP-176-6)。
165
+
166
+ `failing_drivers` 来自 Agentic Loop Step 4.2 下发的 `dispatchTarget.failingDrivers`(经 daemon-actions 的 `failing_drivers` 字段传入),每项 `{wpId, category, item, reason}`。仅当列表非空时输出"重点修复"段,让重做 Teamee 针对性修复而非原样重做;为空(dispatch 首次执行)时不输出该段,向后兼容。
167
+
168
+ ```
169
+ def build_resume_prompt(teamee_name, task_id, role_prompt, completed_files, remaining, failing_drivers=None):
170
+ """为 checkpoint_resume 重启策略构建 prompt(含 refine 重点修复段)"""
171
+ # 渲染"重点修复"段:仅当有失败项明细时输出(修复偏差2,WP-176-6)
172
+ if failing_drivers:
173
+ refine_lines = chr(10).join(
174
+ f"- [{d.get('category', '?')}] {d.get('item', '?')} — {d.get('reason', '?')}"
175
+ f"(WP: {d.get('wpId', '?')})"
176
+ for d in failing_drivers
177
+ )
178
+ refine_section = f'''
179
+ ### 🔴 本轮重点修复的失败项(来自上轮 checklist,优先处理)
180
+ 以下是你上轮 checklist 未通过的失败项明细。**请优先、针对性地修复这些项**,而非盲目原样重做:
181
+ {refine_lines}
182
+
183
+ 逐条核对你修复了每一项的失败原因(reason)。这些是 refine 的核心目标——只有它们通过,本轮才算有效改进(而非无效重做)。
184
+ '''
185
+ else:
186
+ refine_section = "" # failing_drivers 为空(dispatch 首次执行)时不输出该段,向后兼容
187
+
188
+ return f'''你是 {teamee_name},是一名 {role_prompt}。
189
+
190
+ ## 任务重启 (Checkpoint Resume)
191
+
192
+ 你正在重新执行任务 #{task_id}。之前的执行已完成部分工作,你将从断点继续。
193
+
194
+ ### 已完成的文件
195
+ {chr(10).join(f"- {f}" for f in completed_files)}
196
+
197
+ ### 待完成的工作
198
+ {chr(10).join(f"- {r}" for r in remaining)}
199
+ {refine_section}
200
+ 请阅读已完成文件的最新状态,然后继续执行剩余工作。
201
+ 不要重复已完成的工作,直接从断点继续。
202
+ '''
203
+ ```
204
+
205
+ #### build_refine_prompt()
206
+ 为 full_restart 重启策略构建 refine prompt:在标准单任务 prompt 基础上注入"重点修复"段(refine 通道,WP-176-6)。
207
+
208
+ retry 时若 WP 无 checkpoint,Think 选 `full_restart` 策略,此时同样需要让承接 Teamee 知道"重点修哪些失败项",而非从头盲目重做。`failing_drivers` 来源与 `build_resume_prompt` 一致(Agentic Loop Step 4.2 的 `dispatchTarget.failingDrivers`,经 daemon-actions `failing_drivers` 字段传入)。为空时不注入 refine 段,退化为标准 `build_single_task_prompt`。
209
+
210
+ ```
211
+ def build_refine_prompt(teamee_name, task_id, role_prompt, memories, wp_doc_path, failing_drivers=None):
212
+ """为 full_restart retry 构建 prompt(在标准单任务 prompt 上叠加 refine 重点修复段)"""
213
+ # 基础 prompt:复用标准单任务构造(角色赋能 + 记忆 + WP 文档路径)
214
+ base_prompt = build_single_task_prompt(
215
+ teamee_name=teamee_name,
216
+ task_id=task_id,
217
+ role_prompt=role_prompt,
218
+ memories=memories,
219
+ wp_doc_path=wp_doc_path
220
+ )
221
+
222
+ # 仅当有失败项明细时追加 refine 段(修复偏差2,WP-176-6)
223
+ if failing_drivers:
224
+ refine_lines = chr(10).join(
225
+ f"- [{d.get('category', '?')}] {d.get('item', '?')} — {d.get('reason', '?')}"
226
+ f"(WP: {d.get('wpId', '?')})"
227
+ for d in failing_drivers
228
+ )
229
+ refine_section = f'''
230
+
231
+ ---
232
+
233
+ ## 🔴 本轮重点修复的失败项(来自上轮 checklist,优先处理)
234
+
235
+ 你是在 retry(full_restart)模式下重新执行任务 #{task_id}。以下是你上轮 checklist 未通过的失败项明细。**请优先、针对性地修复这些项**,而非盲目原样重做:
236
+ {refine_lines}
237
+
238
+ 逐条核对你修复了每一项的失败原因(reason)。这些是 refine 的核心目标——只有它们通过,本轮才算有效改进(而非无效重做)。
239
+ '''
240
+ return base_prompt + refine_section
241
+
242
+ # failing_drivers 为空(dispatch 首次执行 / 无失败项明细)→ 退化为标准单任务 prompt
243
+ return base_prompt
244
+ ```
245
+
246
+ **进度标记追加时机**:
247
+ 1. Teamee 发送消息时 (通过 SendMessage 监听)
248
+ 2. 检测到文件变更时 (通过 Git 状态或文件系统监听)
249
+ 3. 任务状态变更时 (完成/失败/重试)
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "skill-agent-dispatcher",
3
+ "version": "1.3.0",
4
+ "type": "skill",
5
+ "description": "Use when user says \"批量执行\", \"并行执行\", \"调度子代理\", or needs to execute multiple work packages using Agent subagents. Analyzes dependencies and dispatches tasks in parallel or sequential order.",
6
+ "triggers": ["批量执行", "并行执行", "调度子代理", "agent-dispatcher", "batch execute", "parallel execute", "dispatch agents"],
7
+ "dependencies": ["provider:role-registry", "provider:memory-store"],
8
+ "provides": ["skill:agent-dispatcher"],
9
+ "metadata": {
10
+ "gatedByCode": true
11
+ },
12
+ "config": {}
13
+ }