doukui 0.8.0 → 0.9.1

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 (66) hide show
  1. package/README.en.md +85 -18
  2. package/README.md +8 -8
  3. package/bin/commands/help.js +2 -0
  4. package/bin/commands/plan-lint.js +105 -0
  5. package/bin/commands/verify.js +263 -0
  6. package/bin/doukui.js +2 -0
  7. package/package.json +1 -1
  8. package/plugins/core/hook-session-start/index.js +1 -1
  9. package/plugins/core/hook-skill-gate/index.js +154 -19
  10. package/plugins/core/hook-skill-gate/plugin.json +1 -1
  11. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +7 -28
  12. package/plugins/core/skill-agent-dispatcher/monitoring-reference.md +5 -177
  13. package/plugins/core/skill-agent-dispatcher/plugin.json +1 -1
  14. package/plugins/core/skill-agent-dispatcher/recovery-reference.md +99 -58
  15. package/plugins/core/skill-agent-dispatcher/roles-reference.md +9 -22
  16. package/plugins/core/skill-agent-dispatcher/skill.md +112 -524
  17. package/plugins/core/skill-agentic-loop/mirror-rules.md +15 -3
  18. package/plugins/core/skill-agentic-loop/plugin.json +1 -1
  19. package/plugins/core/skill-agentic-loop/skill.md +123 -324
  20. package/plugins/core/skill-batch-task-creator/plugin.json +1 -1
  21. package/plugins/core/skill-batch-task-creator/skill.md +22 -24
  22. package/plugins/core/skill-checklist/skill.md +15 -141
  23. package/plugins/core/skill-completion-report/plugin.json +1 -1
  24. package/plugins/core/skill-doukui-plan/plugin.json +1 -1
  25. package/plugins/core/skill-doukui-plan/skill.md +33 -38
  26. package/plugins/core/skill-experience-logger/plugin.json +1 -1
  27. package/plugins/core/skill-human-checkpoint/skill.md +1 -0
  28. package/plugins/core/skill-split-work-package/plugin.json +1 -1
  29. package/plugins/core/skill-split-work-package/skill.md +20 -18
  30. package/plugins/core/skill-task-creator/plugin.json +1 -1
  31. package/plugins/core/skill-task-creator/skill.md +25 -165
  32. package/plugins/core/skill-workflow-orchestrator/plugin.json +1 -1
  33. package/plugins/plugin-registry.json +0 -36
  34. package/plugins/runtime/claude-md-injector.js +1 -0
  35. package/plugins/runtime/harness-build.js +5 -5
  36. package/plugins/runtime/plan-reader.js +21 -3
  37. package/plugins/runtime/resolve-plugin-path.js +2 -2
  38. package/plugins/runtime/settings-merger.js +5 -0
  39. package/plugins/contracts/capabilities.js +0 -268
  40. package/plugins/core/provider-memory-store/index.js +0 -510
  41. package/plugins/core/provider-memory-store/plugin.json +0 -9
  42. package/plugins/core/provider-state-store/index.js +0 -244
  43. package/plugins/core/provider-state-store/plugin.json +0 -9
  44. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +0 -32
  45. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +0 -676
  46. package/plugins/core/provider-watchdog/assets/watchdog.js +0 -754
  47. package/plugins/core/provider-watchdog/index.js +0 -151
  48. package/plugins/core/provider-watchdog/plugin.json +0 -13
  49. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +0 -249
  50. package/plugins/core/skill-watchdog-manager/plugin.json +0 -10
  51. package/plugins/core/skill-watchdog-manager/skill.md +0 -143
  52. package/plugins/core/validator-doc-sync/index.js +0 -248
  53. package/plugins/core/validator-doc-sync/plugin.json +0 -12
  54. package/plugins/core/validator-work-package/index.js +0 -300
  55. package/plugins/core/validator-work-package/plugin.json +0 -12
  56. package/plugins/runtime/audit-logger.js +0 -311
  57. package/plugins/runtime/build-cli.js +0 -89
  58. package/plugins/runtime/event-bus.js +0 -207
  59. package/plugins/runtime/hook-dispatcher.js +0 -315
  60. package/plugins/runtime/plugin-loader.js +0 -798
  61. package/plugins/runtime/plugin-trust.js +0 -182
  62. package/plugins/runtime/sandbox-context.js +0 -235
  63. package/plugins/runtime/sandbox-manager.js +0 -609
  64. package/plugins/runtime/sandbox-worker.js +0 -215
  65. package/plugins/runtime/text-tokenize.js +0 -24
  66. package/plugins/runtime/validator-pipeline.js +0 -475
@@ -20,6 +20,7 @@
20
20
  'use strict';
21
21
 
22
22
  var fs = require('fs');
23
+ var os = require('os');
23
24
  var path = require('path');
24
25
  var { HookPlugin } = require('../../contracts/plugin-interface');
25
26
  var { StateStore, FileSystemAdapter } = require('../../runtime/state-store');
@@ -176,7 +177,6 @@ class SkillGateHook extends HookPlugin {
176
177
  this.name = 'hook-skill-gate';
177
178
  this.version = '1.0.0';
178
179
  this.description = '统一技能门控 Hook';
179
- this.dependencies = { providers: ['provider:state-store'] };
180
180
  this.trigger = {
181
181
  event: 'PreToolUse',
182
182
  tools: ['Edit', 'Write'],
@@ -225,6 +225,22 @@ class SkillGateHook extends HookPlugin {
225
225
  }
226
226
  }
227
227
 
228
+ // 计划文件放行目录:Plan 模式审批前唯一可写产物(native Plan mode 把
229
+ // 「当前会话自己的计划文件 ~/.claude/plans/」列为受保护路径的显式例外)。
230
+ // 若不放行,「受控 skill 触发即进 Plan 模式」的流程会死锁:waiting 拦掉
231
+ // 计划文件写入 → ExitPlanMode 无计划可提交 → 审批走不到。harness-config
232
+ // 的 hook-skill-gate.planPaths 可扩展(相对路径按项目根解析)。
233
+ var defaultPlanPaths = [
234
+ path.join(os.homedir(), '.claude', 'plans'),
235
+ path.join(this._projectRoot, 'claude-code-plan'),
236
+ path.join(this._projectRoot, 'docs', 'claude-code-plan'),
237
+ ];
238
+ var projectRoot = this._projectRoot;
239
+ var configuredPlanPaths = (this._config.planPaths || []).map(function (p) {
240
+ return path.isAbsolute(p) ? p : path.join(projectRoot, p);
241
+ });
242
+ this._planPaths = defaultPlanPaths.concat(configuredPlanPaths);
243
+
228
244
  // Initial discovery of gated skills
229
245
  this._gatedSkillsCache = discoverGatedSkills(this._packageRoot, this._config);
230
246
  }
@@ -279,6 +295,13 @@ class SkillGateHook extends HookPlugin {
279
295
  return { allowed: true };
280
296
  }
281
297
 
298
+ // Plan 模式的计划文件是审批前唯一可写产物,不受门控拦截(tool_input.file_path
299
+ // 由 harness 保证为绝对路径,Windows 下为反斜杠——比较前归一化)
300
+ var filePath = context.toolInput && context.toolInput.file_path;
301
+ if (filePath && this._isPlanFile(filePath)) {
302
+ return { allowed: true, skipReason: 'plan_file' };
303
+ }
304
+
282
305
  // Read current state from store
283
306
  var currentState = await this._getState();
284
307
  var blockedStates = this._config.blockedStates || ['waiting'];
@@ -288,10 +311,12 @@ class SkillGateHook extends HookPlugin {
288
311
  return {
289
312
  allowed: false,
290
313
  reason:
291
- 'Blocked: current state is "' +
314
+ 'Blocked: 门控状态为 "' +
292
315
  currentState +
293
- '". ' +
294
- 'Edit/Write operations are not allowed while waiting for human confirmation.',
316
+ '"(受控 skill 已触发,等待人工确认)。Edit/Write 已拦截;' +
317
+ '人工确认后复位门控:node ' +
318
+ __filename.replace(/\\/g, '/') +
319
+ ' --reset(Plan 模式的计划文件不受限,可继续写方案)',
295
320
  };
296
321
  }
297
322
  }
@@ -299,6 +324,27 @@ class SkillGateHook extends HookPlugin {
299
324
  return { allowed: true };
300
325
  }
301
326
 
327
+ /**
328
+ * 判断 file_path 是否落在计划文件放行目录内。
329
+ * harness 保证 file_path 为绝对路径;Windows 下归一化分隔符并忽略大小写,
330
+ * path.relative 判定包含关系(.. / 相对路径绕不过)。
331
+ * @param {string} filePath
332
+ * @returns {boolean}
333
+ */
334
+ _isPlanFile(filePath) {
335
+ var norm = function (p) {
336
+ var r = path.resolve(String(p).replace(/\\/g, '/'));
337
+ return process.platform === 'win32' ? r.toLowerCase() : r;
338
+ };
339
+ var file = norm(filePath);
340
+ var dirs = this._planPaths || [];
341
+ for (var i = 0; i < dirs.length; i++) {
342
+ var rel = path.relative(norm(dirs[i]), file);
343
+ if (rel && rel.indexOf('..') !== 0 && !path.isAbsolute(rel)) return true;
344
+ }
345
+ return false;
346
+ }
347
+
302
348
  /**
303
349
  * PostToolUse handler - after a gated skill executes, set state to "waiting".
304
350
  *
@@ -466,21 +512,23 @@ class SkillGateHook extends HookPlugin {
466
512
  *
467
513
  * @returns {boolean} true if this execution should be skipped
468
514
  */
469
- _shouldSkipForDoubleTrigger() {
515
+ _shouldSkipForDoubleTrigger(context) {
516
+ // 防抖目标:global + project 双重注册对**同一事件**的毫秒级重复执行。
517
+ // 只按「同 event + 同 tool」且 1 秒内判重——旧版「任意 hook 5 秒」会吞掉
518
+ // 合法的相邻调用(如 PreToolUse(Edit) 后紧随的 PostToolUse(Skill))。
519
+ var key = ((context && context.event) || '') + ':' + ((context && context.tool) || '');
470
520
  var markerPath = path.join(this._projectRoot, '.claude', '.hook-execution-marker');
471
521
 
472
- // If another hook process is marked as active, skip
522
+ // If another hook process is marked as active for the same key, skip
473
523
  if (fs.existsSync(markerPath)) {
474
524
  try {
475
525
  var marker = fs.readFileSync(markerPath, 'utf-8');
476
526
  var markerData = JSON.parse(marker);
477
527
 
478
- // If marker is recent (< 5 seconds), skip to prevent double execution
479
- var now = Date.now();
480
- if (markerData.timestamp && (now - markerData.timestamp) < 5000) {
528
+ if (markerData.key === key && markerData.timestamp && (Date.now() - markerData.timestamp) < 1000) {
481
529
  return true;
482
530
  }
483
- // Stale marker — clean it up
531
+ // Stale / different-key marker — clean it up
484
532
  try { fs.unlinkSync(markerPath); } catch (e) { /* ignore */ }
485
533
  } catch (e) {
486
534
  // Invalid marker, clean up
@@ -490,9 +538,10 @@ class SkillGateHook extends HookPlugin {
490
538
 
491
539
  // Mark this hook as active
492
540
  try {
541
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
493
542
  fs.writeFileSync(
494
543
  markerPath,
495
- JSON.stringify({ timestamp: Date.now(), pid: process.pid }),
544
+ JSON.stringify({ timestamp: Date.now(), pid: process.pid, key: key }),
496
545
  'utf-8'
497
546
  );
498
547
  } catch (e) {
@@ -583,6 +632,28 @@ function sanitizeObject(obj) {
583
632
  return result;
584
633
  }
585
634
 
635
+ /**
636
+ * Normalize a hook stdin payload across harness schemas.
637
+ *
638
+ * Claude Code passes `{ hook_event_name, tool_name, tool_input: {...} }` on
639
+ * stdin; the legacy/programmatic shape is `{ event, tool, skill }`. The gate
640
+ * previously read only the legacy keys, so in real sessions it never saw the
641
+ * tool/skill and the whole gate was inert. Unknown shapes fail open (empty
642
+ * strings) rather than crash.
643
+ * @param {object} raw - sanitized stdin payload
644
+ * @returns {{event: string, tool: string, skill: string, toolInput: object}}
645
+ */
646
+ function normalizeHookContext(raw) {
647
+ raw = raw || {};
648
+ var toolInput = raw.tool_input || {};
649
+ return {
650
+ event: raw.hook_event_name || raw.event || '',
651
+ tool: raw.tool_name || raw.tool || '',
652
+ skill: toolInput.skill || toolInput.skillName || raw.skill || raw.skillName || '',
653
+ toolInput: toolInput,
654
+ };
655
+ }
656
+
586
657
  /**
587
658
  * Main CLI function.
588
659
  */
@@ -591,21 +662,69 @@ function main() {
591
662
 
592
663
  if (args.length === 0) {
593
664
  console.error(
594
- 'Usage: node index.js --pre-tool | --post-skill\n' +
595
- ' --pre-tool Run PreToolUse check (reads context from stdin)\n' +
596
- ' --post-skill Run PostToolUse handler (reads context from stdin)'
665
+ 'Usage: node index.js --pre-tool | --post-skill | --post-plan-exit | --reset\n' +
666
+ ' --pre-tool Run PreToolUse check (reads context from stdin)\n' +
667
+ ' --post-skill Run PostToolUse handler (reads context from stdin)\n' +
668
+ ' --post-plan-exit Reset gate after ExitPlanMode approval (reads context from stdin)\n' +
669
+ ' --reset Reset harness.state to idle (run after human-checkpoint approval)'
597
670
  );
598
671
  process.exit(1);
599
672
  }
600
673
 
601
674
  var mode = args[0];
602
- if (mode !== '--pre-tool' && mode !== '--post-skill') {
675
+ if (mode !== '--pre-tool' && mode !== '--post-skill' && mode !== '--post-plan-exit' && mode !== '--reset') {
603
676
  console.error('Unknown mode: ' + mode);
604
- console.error('Valid modes: --pre-tool, --post-skill');
677
+ console.error('Valid modes: --pre-tool, --post-skill, --post-plan-exit, --reset');
605
678
  process.exit(1);
606
679
  }
607
680
 
608
- readStdin(function (err, context) {
681
+ if (mode === '--reset') {
682
+ var resetHook = new SkillGateHook();
683
+ resetHook
684
+ .onActivate(null)
685
+ .then(function () {
686
+ return resetHook._setState('idle');
687
+ })
688
+ .then(function () {
689
+ process.stdout.write(JSON.stringify({ ok: true, state: 'idle' }) + '\n');
690
+ process.exit(0);
691
+ })
692
+ .catch(function (error) {
693
+ console.error('Hook execution failed: ' + error.message);
694
+ process.exit(1);
695
+ });
696
+ return;
697
+ }
698
+
699
+ if (mode === '--post-plan-exit') {
700
+ var planExitHook = new SkillGateHook();
701
+ readStdin(function (err) {
702
+ if (err) {
703
+ console.error('Failed to read stdin: ' + err.message);
704
+ process.exit(1);
705
+ }
706
+ planExitHook
707
+ .onActivate(null)
708
+ .then(function () {
709
+ // ExitPlanMode 审批后自动复位门控(waiting → idle),不再依赖模型记得
710
+ // 跑 --reset。拒绝态的 tool_response 形状官方未文档化(拒绝时是否触发
711
+ // PostToolUse 同样未文档化);即便拒绝态误复位,Plan 模式本身仍拦截
712
+ // 代码写入,安全由 Plan 模式兜底。
713
+ return planExitHook._setState('idle');
714
+ })
715
+ .then(function () {
716
+ process.stdout.write(JSON.stringify({ ok: true, state: 'idle' }) + '\n');
717
+ process.exit(0);
718
+ })
719
+ .catch(function (error) {
720
+ console.error('Hook execution failed: ' + error.message);
721
+ process.exit(1);
722
+ });
723
+ });
724
+ return;
725
+ }
726
+
727
+ readStdin(function (err, payload) {
609
728
  if (err) {
610
729
  console.error('Failed to read stdin: ' + err.message);
611
730
  process.exit(1);
@@ -617,8 +736,13 @@ function main() {
617
736
  hook
618
737
  .onActivate(null)
619
738
  .then(function () {
620
- // Check for double-triggering prevention
621
- if (hook._shouldSkipForDoubleTrigger()) {
739
+ var context = normalizeHookContext(payload);
740
+
741
+ // Check for double-triggering prevention (same event + tool, 1s window).
742
+ // Only for state-changing --post-skill: --pre-tool is a pure read-only
743
+ // check and must NEVER be deduped (parallel Edit calls fire within 1s;
744
+ // skipping them would fail the waiting-block open).
745
+ if (mode === '--post-skill' && hook._shouldSkipForDoubleTrigger(context)) {
622
746
  // Skip execution to prevent double-triggering
623
747
  process.stdout.write(JSON.stringify({ allowed: true, skipped: true, reason: 'Double-trigger prevention' }) + '\n');
624
748
  process.exit(0);
@@ -638,6 +762,16 @@ function main() {
638
762
  return hook.handle(context);
639
763
  })
640
764
  .then(function (result) {
765
+ // PreToolUse 拦截:exit 2 时 harness 只把 stderr 回给模型——原因必须走
766
+ // stderr。旧版把 {allowed, reason} 写 stdout(不在 hook 输出 schema 内,
767
+ // 校验失败回退到空 stderr),模型只看到 "No stderr output",不知被门控
768
+ // 拦截也不知道如何复位(magpie-plugins 2026-11-30 死锁报告缺陷 3)。
769
+ if (mode === '--pre-tool' && result.allowed === false && result.reason) {
770
+ process.stderr.write(result.reason + '\n');
771
+ process.exit(2);
772
+ return;
773
+ }
774
+
641
775
  // Output the result as JSON
642
776
  process.stdout.write(JSON.stringify(result, null, 2) + '\n');
643
777
 
@@ -660,3 +794,4 @@ if (require.main === module) {
660
794
  }
661
795
 
662
796
  module.exports = SkillGateHook;
797
+ module.exports.normalizeHookContext = normalizeHookContext;
@@ -3,7 +3,7 @@
3
3
  "version": "1.0.0",
4
4
  "type": "hook",
5
5
  "description": "统一技能门控 Hook - 合并 check-state + post-skill + skill-gate 三合一,动态查询 gated skills",
6
- "dependencies": ["provider:state-store"],
6
+ "dependencies": [],
7
7
  "provides": ["hook:skill-gate"],
8
8
  "config": {
9
9
  "gatedSkills": [],
@@ -6,11 +6,7 @@
6
6
 
7
7
  ## ⚠️ 权限要求
8
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 ...)` 一条。
9
+ Step 7 清理需要 Bash 权限执行 `test -d` 验证与 `node bin/doukui.js team-cleanup <team> --force`(该 CLI 是 Node 进程,内部走 fs.rmSync 文件系统级删除,不调用 TeamDelete——工具已移除;**无需**在 settings.json 添加 `Bash(rm -rf ...)` 条目,只需 `Bash(node bin/doukui.js team-cleanup ...)` 一条)。
14
10
 
15
11
  > ⚠️ **implicit session team 模式下的清理范围**: 当前 session 的 implicit team 随 session 自动清理,**本流程主要针对历史残留的显式/UUID 团队目录**(如旧的 `cybershop-wp101`、UUID 命名团队)。若 `team_name` 是当前 session 的批次标签(非真实 harness 团队目录),目录可能不存在,Step 7a 条件 2 会返回 `NOT_FOUND` 并正常跳过。
16
12
 
@@ -69,17 +65,10 @@ Teamee 逻辑销毁必须完成 + 残留目录清理必须验证结果!
69
65
  ```
70
66
  # 无协议帧;in-process Teamee 随 session 自然终止
71
67
  teamee_map.clear()
72
- # ── 状态输出(直接文本输出,禁止使用 SendMessage)──
73
- # 输出: "映射表已清空(残留 Teamee 随 session 终止)"
68
+ # 输出: "映射表已清空(残留 Teamee 随 session 终止)" ← 直接文本输出,禁止用 SendMessage
74
69
  ```
75
70
 
76
- > 不再读取团队配置发 orphan shutdown——映射表不一致的孤儿成员会在后续 team-cleanup CLI 的目录级清理中被一并删除。
77
-
78
- ---
79
-
80
- ### Step 7c: (已删除) 无需等待 shutdown 响应
81
-
82
- 逻辑销毁(Step 7b `teamee_map.clear()`)无协议帧,无需等待响应,直接进入残留目录清理(Step 7d)。
71
+ > 映射表不一致的孤儿成员会在后续 team-cleanup CLI 的目录级清理中被一并删除。
83
72
 
84
73
  ---
85
74
 
@@ -198,17 +187,7 @@ Owner: godot-script-expert-t2
198
187
 
199
188
  ## Cleanup Guarantee (清理保障)
200
189
 
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
- ```
190
+ - ✅ 正常完成 / 部分失败 → Step 6.5 即时逻辑销毁 → Step 7 历史残留 CLI
191
+ - ✅ 超时 → Step 6.5 超时逻辑销毁 → Step 7 强制 CLI
192
+ - ✅ 异常中断 → 捕获中断 → Step 7 强制逻辑销毁残留 + CLI
193
+ - ❌ **无任何情况可以跳过 Teamee 逻辑销毁**(当前 session implicit team 随 session 自动清理;team-cleanup CLI 仅清理历史残留显式/UUID 团队目录)
@@ -1,179 +1,6 @@
1
1
  # Dispatcher Monitoring Reference(监控循环运行时细则)
2
2
 
3
- > 本文件是 skill-agent-dispatcher 的按需参考(渐进式加载约定,P2a 二轮瘦身外移)。
4
- > 规则本体与触发条件仍在 SKILL.md 主干;以下章节仅在遇到对应运行时场景时按 📖指针 Read,无需预载。
5
- > 来源章节:SKILL.md Step 6.5 监控循环(Phase 0.1 / Phase D.1 / Phase D.3)与后置辅助函数、拆分工作包执行支持、共享上下文机制。
6
-
7
- ## Phase 0.1 多窗口阶段信号检查
8
-
9
- 位于监控循环 Phase 0 之后、Phase A 之前(缩进为循环体内原样保留):
10
-
11
- ```
12
- # ---- Phase 0.1: 多窗口阶段信号检查 ----
13
- # 读取 multi-window-session.json,检查当前窗口的阶段是否就绪
14
- if is_multi_window:
15
- session_file = ".claude-daemon/multi-window-session.json"
16
- try:
17
- session_data = json_loads(Read(file_path=session_file))
18
- except Exception:
19
- session_data = None
20
-
21
- if session_data:
22
- my_stage = None
23
- for s in session_data.get("stages", []):
24
- if window_id in s.get("windows", []):
25
- my_stage = s
26
- break
27
-
28
- if my_stage:
29
- if my_stage.get("status") == "pending":
30
- # 当前阶段未就绪,跳过本轮 Teamee 创建
31
- # 输出: "⏸ 窗口 {window_id} 阶段 {my_stage['stage_id']} 尚未就绪,等待阶段信号"
32
- pass # 跳过后续 Phase C 创建逻辑(通过标志控制)
33
- elif my_stage.get("status") == "completed":
34
- # 当前阶段已完成,检查是否有下一阶段
35
- next_stage = None
36
- for s in session_data.get("stages", []):
37
- if s.get("stage_id") == my_stage.get("stage_id") + 1:
38
- next_stage = s
39
- break
40
- if next_stage and next_stage.get("status") == "active":
41
- # 切换到下一阶段的任务
42
- assigned_wps = next_stage.get("work_packages", assigned_wps)
43
- current_stage = next_stage.get("stage_id", current_stage)
44
- # 输出: "🔄 窗口 {window_id} 切换到阶段 {next_stage['stage_id']}: {next_stage.get('name', '')}"
45
- ```
46
-
47
- ## Phase D.1 守护进程指令处理(DISP-003)
48
-
49
- 位于监控循环 Phase C.5 写回之后、Phase D 退出判定之前(缩进原样保留):
50
-
51
- ```
52
- # ---- Phase D.1: 读取守护进程指令 (DISP-003) ----
53
- # 在判断退出条件前,读取守护进程下发的指令
54
- daemon_actions_path = ".claude-daemon/daemon-actions.json"
55
- if file_exists(daemon_actions_path):
56
- actions_data = Read(file_path=daemon_actions_path)
57
- try:
58
- actions = json_loads(actions_data).get("actions", [])
59
- except Exception as e:
60
- # 输出: "⚠️ 守护进程指令文件解析失败,跳过本轮指令: {e}"
61
- actions = []
62
-
63
- for action in actions:
64
- # 检查指令是否已被处理
65
- if action.get("id") in processed_action_ids:
66
- continue
67
-
68
- target_task_id = action.get("target_task")
69
- action_type = action.get("action")
70
- strategy = action.get("strategy", "full_restart")
71
- reason = action.get("reason", "")
72
- # 读取 Agentic Loop 下发的失败项明细(refine 通道,WP-176-6):
73
- # 来源 skill-agentic-loop Step 4.2 的 dispatchTarget.failingDrivers,
74
- # 每项 {wpId, category, item, reason};仅 retry/resplit 有值,dispatch 首次执行为空。
75
- failing_drivers = action.get("failing_drivers", [])
76
-
77
- if action_type == "restart":
78
- # 重启指令: 逻辑销毁旧 Teamee → 创建新 Teamee
79
- if target_task_id in teamee_map:
80
- old_teamee = teamee_map[target_task_id]
81
-
82
- # D1a. 逻辑销毁旧 Teamee(无协议帧)
83
- markTeameeDestroyed(teamee_map, target_task_id)
84
-
85
- # D1b. 根据策略创建新 Teamee
86
- # 🔴 两种策略都注入 failing_drivers(refine 通道,WP-176-6):
87
- # 让承接重做的 Teamee 知道"重点修哪些失败项",而非盲目原样重做。
88
- assignment = wp_assignments[target_task_id]
89
- new_teamee_name = f"{assignment.role_id}-t{target_task_id}-retry"
90
-
91
- if strategy == "checkpoint_resume":
92
- # 复杂任务: 注入已完成文件上下文 + 失败项重点修复段
93
- context = action.get("context", {})
94
- prompt = build_resume_prompt(
95
- teamee_name=new_teamee_name,
96
- task_id=target_task_id,
97
- role_prompt=assignment.role_prompt,
98
- completed_files=context.get("completed_files", []),
99
- remaining=context.get("remaining", []),
100
- failing_drivers=failing_drivers
101
- )
102
- else: # full_restart
103
- # 简单任务: 从头执行(仍注入失败项重点修复段,区分 retry 与首次 dispatch)
104
- prompt = build_refine_prompt(
105
- teamee_name=new_teamee_name,
106
- task_id=target_task_id,
107
- role_prompt=assignment.role_prompt,
108
- memories=assignment.memories,
109
- wp_doc_path=assignment.wp_doc_path,
110
- failing_drivers=failing_drivers
111
- )
112
-
113
- # D1c. 创建新 Teamee(自动加入 implicit session team,无需 team_name 参数)
114
- Agent(
115
- name=new_teamee_name,
116
- subagent_type=resolve_subagent_type(assignment.role_id), # 双分支路由(见 Step 6 规则)
117
- prompt=prompt
118
- )
119
- teamee_map[target_task_id] = new_teamee_name
120
-
121
- # D1d. 更新重试计数
122
- update_task_file(target_task_id, increment_retry=True)
123
-
124
- # 标记指令已处理
125
- processed_action_ids.append(action.get("id"))
126
-
127
- elif action_type == "abort":
128
- # 中止单个任务
129
- if target_task_id in teamee_map:
130
- teamee_name = teamee_map[target_task_id]
131
- # 逻辑销毁(无协议帧)
132
- markTeameeDestroyed(teamee_map, target_task_id)
133
- update_task_file(target_task_id, status="failed")
134
- processed_action_ids.append(action.get("id"))
135
-
136
- elif action_type == "pause":
137
- # 暂停创建新 Teamee(已有 Teamee 继续运行)
138
- global_pause_flag = True
139
- processed_action_ids.append(action.get("id"))
140
-
141
- elif action_type == "abort_all":
142
- # 全局中止: 逻辑销毁所有 Teamee,终止监控循环(无协议帧)
143
- for task_id in list(teamee_map.keys()):
144
- markTeameeDestroyed(teamee_map, task_id)
145
- teamee_map.clear()
146
- # 输出: "收到 abort_all 指令,终止监控循环"
147
- processed_action_ids.append(action.get("id"))
148
- break # 跳出监控循环
149
-
150
- # D1e. 回写已处理的 iteration
151
- if actions:
152
- Write(file_path=daemon_actions_path, content=json_dumps({
153
- "actions": [a for a in actions if a.get("id") not in processed_action_ids],
154
- "last_processed_iteration": loop_iteration
155
- }))
156
- ```
157
-
158
- ## Phase D.3 批次自动加载
159
-
160
- 位于监控循环每轮末尾、sleep(loop_interval) 之前(缩进原样保留):
161
-
162
- ```
163
- # Phase D3: 批次自动加载 — 当前批次全部完成后从 pending_batches 加载下一批
164
- if current_batch and len(teamee_map) == 0:
165
- batch_completed = all(
166
- find_by_id(tasks, tid).status == "completed" for tid in current_batch
167
- if find_by_id(tasks, tid)
168
- )
169
- if batch_completed and pending_batches:
170
- next_batch_size = min(max_batch_size, len(pending_batches))
171
- current_batch = pending_batches[:next_batch_size]
172
- pending_batches = pending_batches[next_batch_size:]
173
- # 输出: "当前批次完成,自动加载下一批: {len(current_batch)} 个任务, 剩余 {len(pending_batches)} 个"
174
- # 写回状态文件保存批次进度
175
- write_state("monitoring")
176
- ```
3
+ > 本文件是 skill-agent-dispatcher 的按需参考(渐进式加载约定)。规则本体与触发条件仍在 SKILL.md 主干(Step 6 / Step 6.5 监控循环 Phase C、拆分工作包执行支持、共享上下文机制);以下章节仅在遇到对应运行时场景时按 📖指针 Read,无需预载。
177
4
 
178
5
  ## 辅助函数(is_unblocked / 并发控制)
179
6
 
@@ -215,6 +42,8 @@ def is_time_in_range(current, start, end):
215
42
  return current >= start or current < end
216
43
  ```
217
44
 
45
+ 配置来源:`agent_dispatcher.concurrency`(plugin.json / harness-config.yaml,字段 `default_max` + `schedules[{name, time_range:{start,end}, max_concurrent}]`)。Phase C 每轮用 `get_max_concurrent(config, now())` 取当前时段上限,活跃 Teamee 数(`len(teamee_map)`)达上限即跳过创建、任务保持 pending。
46
+
218
47
  ## 拆分工作包执行支持
219
48
 
220
49
  当工作包有子工作包时,agent-dispatcher 会自动识别并按依赖调度。
@@ -252,10 +81,9 @@ def is_time_in_range(current, start, end):
252
81
 
253
82
  ### 主动共享 (通过 SendMessage)
254
83
 
255
- > 注:Teamee 一经 spawn **自动加入 implicit session team**,无需 Lead 显式分配团队——SendMessage 与共享 Task List 的协作能力由 implicit session team 提供,未受 harness 团队机制变更影响。
84
+ > Teamee 一经 spawn **自动加入 implicit session team**——SendMessage 与共享 Task List 的协作能力由 implicit session team 提供。
256
85
 
257
86
  | 消息类型 | 格式 | 用途 |
258
87
  |----------|------|------|
259
- | `shutdown_request` | (deprecated) | Lead 不再发 shutdown_request;harness 拦截含 protocol frame 的 SendMessage message |
260
- | `shutdown_response` | (deprecated) | 同上;Teamee 状态同步改为 TaskUpdate(completed) → Lead 检测 → markTeameeDestroyed → 批末 team-cleanup CLI |
88
+ | `shutdown_request` / `shutdown_response` | (deprecated) | 不再使用;harness 拦截含 protocol frame 的 SendMessage message。Teamee 状态同步改为 TaskUpdate(completed) → Lead 检测 → markTeameeDestroyed |
261
89
  | 纯文本状态 | string + summary | Teamee 间/向 Lead 的进度沟通(唯一允许的 SendMessage 用途) |
@@ -4,7 +4,7 @@
4
4
  "type": "skill",
5
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
6
  "triggers": ["批量执行", "并行执行", "调度子代理", "agent-dispatcher", "batch execute", "parallel execute", "dispatch agents"],
7
- "dependencies": ["provider:role-registry", "provider:memory-store"],
7
+ "dependencies": ["provider:role-registry"],
8
8
  "provides": ["skill:agent-dispatcher"],
9
9
  "metadata": {
10
10
  "gatedByCode": true