doukui 0.3.0 → 0.4.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.
@@ -91,29 +91,20 @@ description: "任务创建 Skill - 创建工作包定义(仅定义不实现)
91
91
  | 包含"只写文档"、"不要执行"、"不具体执行"、"不要直接执行" | **快速模式** | 只定义任务,不分析代码 |
92
92
  | 无上述关键词 | **深度模式** | 可自由分析代码、评估复杂度 |
93
93
 
94
- ### 快速模式(用户明确说"不要执行"时)
94
+ ### 快速模式(用户明确说"不要执行"时)——红线,触发即适用
95
95
 
96
- 在 Plan 模式中,你只能:
97
- - ✅ 确定工作包编号
98
- - ✅ 写任务标题和目标(1-2句话)
99
- - ✅ 写子任务列表(可选)
100
- - ✅ 写验收标准(可选)
96
+ Plan 模式中你**禁止**:读取代码文件分析实现 / 检查代码是否存在 / 运行任何代码审计 /
97
+ 做任何"执行阶段"才该做的工作。只确定编号、写标题目标(1-2 句)、可选子任务与验收标准。
98
+ **只定义"做什么",不分析"怎么做"或"是否已做"。**
101
99
 
102
- 在 Plan 模式中,你**禁止**:
103
- - ❌ 读取代码文件分析实现
104
- - ❌ 检查代码是否存在
105
- - ❌ 运行任何代码审计
106
- - ❌ 做任何"执行阶段"才该做的工作
100
+ ### 深度模式细则(📖 共享参考,按需 Read)
107
101
 
108
- **规则**: 快速模式下,Plan 阶段只定义"做什么",不分析"怎么做"或"是否已做"
102
+ 深度模式下的自由度清单与上下文预算纪律(预读估算/分块读取/语义边界/上下文缺口表格),
103
+ 三 skill 共用同一份规范:
109
104
 
110
- ### 深度模式(默认)
111
-
112
- Plan 阶段可以自由进行:
113
- - ✅ 读取代码分析依赖
114
- - ✅ 评估任务复杂度
115
- - ✅ 检查现有实现
116
- - ✅ 设计拆分方案
105
+ ```
106
+ Read("plugins/core/skill-task-creator/context-budget-reference.md")
107
+ ```
117
108
 
118
109
  ### 多窗口规划模式
119
110
 
@@ -323,53 +314,13 @@ WP-XXX: [原任务] (父工作包)
323
314
 
324
315
  ---
325
316
 
326
- ## 上下文窗口管理
327
-
328
- 仅在深度模式下生效。快速模式不读取文件,无需分块。
329
-
330
- ### 预读估算协议
331
-
332
- 1. 查看文件顶部的 `<!-- CONTEXT-CONFIG -->` 获取限制参数
333
- 2. 先用 Glob 发现文件,用 Bash `wc -l` 估算行数
334
- 3. 估算公式: 每行代码 ≈ 10 tokens,每行文本 ≈ 5 tokens
335
- 4. 可用预算 = max_tokens - safety_margin
336
-
337
- ### 读取策略决策树
338
-
339
- | 文件估算行数 | 策略 |
340
- |-------------|------|
341
- | ≤ thresholds.small (200行) | 直接用 Read 工具读取整个文件 |
342
- | thresholds.small ~ thresholds.medium (200-800行) | 分块读取: Read(offset, limit=chunk_lines) |
343
- | > thresholds.medium (800行) | Grep 扫描关键模式 → 定位行范围 → Read 目标段 |
344
- | 多文件合计超预算 | 排序优先级 → 读高优 → 低优用 Grep |
345
-
346
- ### 分块读取协议
347
-
348
- 1. **首块**(1 ~ chunk_lines): 建立"结构地图"(类/函数/节标题位置)
349
- 2. **后续块**: 根据结构地图判断是否包含相关内容
350
- 3. **提前终止**: 已获得足够信息时停止读取,不读完整文件
351
- 4. **跨块引用**: 记录依赖但不回读
352
-
353
- ### 语义边界规则(优先级从高到低)
354
-
355
- 1. 函数/方法边界 - 不在函数体中间断开
356
- 2. 类边界 - 不在类定义中间断开
357
- 3. Markdown 节标题 - 在 `##`/`###` 处断开
358
- 4. 代码块边界 - 在 `{ }` 之间断开
359
- 5. 行边界 - 最后手段
360
-
361
- ### 部分分析的合并
317
+ ## 上下文窗口管理(📖 共享参考,按需 Read)
362
318
 
363
- 置信度标注:
364
- - **[HIGH]** 基于完整直接读取
365
- - **[MEDIUM]** 基于部分读取 + 结构推断
366
- - **[LOW]** 仅基于 Grep 结果
319
+ 深度模式下的预读估算 / 读取策略决策树 / 分块读取 / 语义边界 / 部分分析合并 / 上下文缺口表格,
320
+ 三 skill(task-creator / batch-task-creator / split-work-package)共用同一份规范:
367
321
 
368
- 在 Plan 中包含"上下文缺口"子节:
369
322
  ```
370
- ## 上下文缺口
371
- | 文件 | 未读部分 | 影响 | 建议 |
372
- |------|----------|------|------|
323
+ Read("plugins/core/skill-task-creator/context-budget-reference.md")
373
324
  ```
374
325
 
375
326
  ### 任务创建专属规则
@@ -1,20 +1,19 @@
1
1
  /**
2
- * Executor (claude) — Agentic Loop Act 层 provider 执行单元的 Claude Code 实现(WP-185 / WP-187)
2
+ * Claude executor 共享 internals(WP-185 / WP-187 / v0.3.10 去死代码)
3
3
  *
4
4
  * @module executor-claude
5
5
  *
6
- * 职责:实现 driver 期望的 `run(pendingAction) -> CheckResult` 契约的真实实现——
7
- * spawn Claude Code CLI(`claude -p --output-format json --allowedTools ...`)逐轮写代码,
8
- * 从其 stdout JSON 提取 text,再从 text 里的 `json:machine-readable` fenced block
9
- * 解析出 CheckResult(skill-checklist 机器可读契约,design.md §5.4.2)。
6
+ * 定位:本模块原是完整的 claude executor;v0.3.10 起 `--executor=claude` 经
7
+ * loop-executor 别名重定向到 executor-default(真实 Anthropic 与智谱/mimo 等统一
8
+ * 走 default),执行器实现已并入 executor-default.js。本模块降级为**共享工具库**:
9
+ * prompt 构造(buildPrompt / WP 文档读取 / retry 精读裁剪)、checklist 解析
10
+ * (`json:machine-readable` 契约)、进展检测(工作树脏度)、stdout 元数据提取,
11
+ * 供 executor-default 与 executor-sdk 经 `claudeInternals._*` 复用。
10
12
  *
11
- * 设计约束(docs/plan/agentic-loop-node-driver.md 硬约束 #3):
12
- * - provider 解耦点是 `executor.run()`:driver 不直接 spawn claude,
13
- * 本模块与 executor-local.js 实现同一份接口契约,可互换(--executor=local|claude)。
14
- * - 新增 executor-glm.js 接智谱 Coding Plan 时,driver 与 engine 零改动。
13
+ * ⚠️ 本模块不再导出 createExecutor——新增 executor 走 loop-executor.js REGISTRY。
15
14
  *
16
- * 接口契约(与 executor-local.js 一致,createExecutor 返回 { name, run, config }):
17
- * run(pendingAction: {wpId, mode, strategy, failingDrivers?, ...}) -> Promise<CheckResult>
15
+ * CheckResult 契约(reflection-evaluator.proximityFromChecklist /
16
+ * failingDriversFromChecklist 消费,见 test-checklist-json-contract.js):
18
17
  *
19
18
  * CheckResult 契约(reflection-evaluator.proximityFromChecklist /
20
19
  * failingDriversFromChecklist 消费,见 test-checklist-json-contract.js):
@@ -582,233 +581,10 @@ function buildClaudeArgs(allowedTools, settingsPath) {
582
581
  }
583
582
 
584
583
  // ---------------------------------------------------------------------------
585
- // 公开 API
584
+ // 共享 internals 导出(executor-default / executor-sdk 复用;不再导出 createExecutor)
586
585
  // ---------------------------------------------------------------------------
587
586
 
588
- /**
589
- * 创建一个 claude executor 实例。
590
- *
591
- * @param {object} [opts]
592
- * @param {Function} [opts.spawnFn] 注入 spawn(测试用);默认 child_process.spawn
593
- * @param {string} [opts.binary] claude 可执行名
594
- * @param {number} [opts.timeoutMs] 单次超时(ms)
595
- * @param {number} [opts.rateLimitPerHour] 调用上限/h
596
- * @param {string} [opts.model] 模型名占位(provider 零分支统一通道;claude 不显式 --model)
597
- * @param {string[]} [opts.allowedTools] 工具白名单
598
- * @param {string} [opts.projectRoot] 项目根覆盖(默认自动探测)
599
- * @param {string} [opts.settingsPath] claude settings 文件路径(透传 --settings;切换 provider/套餐)
600
- * @returns {{ name:string, run:Function, config:object }}
601
- */
602
-
603
- /**
604
- * 把 executor 打点 trace 附到 CheckResult 上(WP-196-1-impl,纯观测)。
605
- * 下划线前缀 `_executorTrace` 表示内部观测字段,reflection-evaluator 不消费;
606
- * driver 读取后聚合到 round record。全程 try/catch 降级。
607
- * @param {object} checkResult
608
- * @param {object} trace { spawnMs, exitCode, timedOut, rateLimited, tokenUsage, endpointMs }
609
- * @returns {object} 原 checkResult(附 _executorTrace)
610
- */
611
- function withExecutorTrace(checkResult, trace) {
612
- try {
613
- if (checkResult && typeof checkResult === 'object') {
614
- checkResult._executorTrace = trace || null;
615
- }
616
- } catch (_e) { /* 降级:观测失败绝不阻断 */ }
617
- return checkResult;
618
- }
619
-
620
- function createExecutor(opts) {
621
- opts = opts || {};
622
- var config = {
623
- binary: opts.binary || DEFAULTS.binary,
624
- timeoutMs: typeof opts.timeoutMs === 'number' ? opts.timeoutMs : DEFAULTS.timeoutMs,
625
- rateLimitPerHour: typeof opts.rateLimitPerHour === 'number'
626
- ? opts.rateLimitPerHour : DEFAULTS.rateLimitPerHour,
627
- model: opts.model || DEFAULTS.model,
628
- allowedTools: (opts.allowedTools && opts.allowedTools.length)
629
- ? opts.allowedTools.slice() : DEFAULTS.allowedTools.slice(),
630
- projectRoot: opts.projectRoot || resolveProjectRoot(),
631
- settingsPath: opts.settingsPath || null,
632
- // 上下文窗口预算 tokens(Phase B-2 分档;null=未知不注入 prompt)
633
- contextWindow: typeof opts.contextWindow === 'number' && opts.contextWindow > 0
634
- ? opts.contextWindow : null,
635
- };
636
- var spawnFn = opts.spawnFn || spawn;
637
- // 进展检测 git status 执行函数(DI 注入,测试用;默认走 readWorktreeDirty 内 execFileSync)
638
- var gitStatusFn = typeof opts.gitStatusFn === 'function' ? opts.gitStatusFn : null;
639
-
640
- // 限流状态
641
- var callTimestamps = [];
642
- var HOUR_MS = 60 * 60 * 1000;
643
-
644
- /**
645
- * 执行 pendingAction:spawn claude → 收集 stdout → 解析 json:machine-readable block。
646
- * @param {object} pendingAction
647
- * @returns {Promise<object>} CheckResult
648
- */
649
- async function run(pendingAction) {
650
- pendingAction = pendingAction || {};
651
- var wpId = pendingAction.wpId || 'unknown';
652
-
653
- // concurrent-dispatch Step 2(per-WP worktree 隔离):
654
- // per-call projectRoot override。批内 N 个并发 run 各自走独立 worktree(loop.js
655
- // 传入 pendingAction.projectRoot = wtPath),使 readWorktreeDirty 的 dirtyBefore/
656
- // dirtyAfter per-WP 准确、互不串扰(修复 v0.4.0 noProgress 批级串扰)。
657
- // 不传 → 走 config.projectRoot(零回归 = v0.4.0 行为)。
658
- var runCwd = (typeof pendingAction.projectRoot === 'string' && pendingAction.projectRoot)
659
- ? pendingAction.projectRoot : config.projectRoot;
660
- // noProgressForceZero(--no-progress-detect escape hatch,文档 §5.5):批模式强制
661
- // 脏度降级(dirtyBefore/dirtyAfter=null → applyProgressDetection 走降级 noProgress=false),
662
- // 牺牲发散检测精度换稳定性,~0 行内联(仅置 null,无需 worktree 基建)。
663
- var forceZeroProgress = pendingAction.noProgressForceZero === true;
664
-
665
- // WP-196-1-impl / token-usage:executor.run 打点(仅观测,不引入 provider 分支)。
666
- // 采集 {spawnMs, exitCode, timedOut, rateLimited, tokenUsage, endpointMs} 附在 checkResult._executorTrace。
667
- // tokenUsage/endpointMs 在 close 回调由 extractMetaFromClaudeStdout 填充;限流/失败路径保持 null。
668
- var trace = { spawnMs: null, exitCode: null, timedOut: false, rateLimited: false, tokenUsage: null, endpointMs: null };
669
- var spawnStartMs = Date.now();
670
-
671
- // 限流
672
- var now = Date.now();
673
- callTimestamps = callTimestamps.filter(function (ts) { return now - ts < HOUR_MS; });
674
- if (callTimestamps.length >= config.rateLimitPerHour) {
675
- trace.rateLimited = true;
676
- trace.spawnMs = Date.now() - spawnStartMs;
677
- return withExecutorTrace(buildFailedChecklist(wpId, 'rate_limited'), trace);
678
- }
679
- callTimestamps.push(now);
680
-
681
- // 进展检测基线(WP-191-2-impl):执行前工作树脏度(porcelain)
682
- // forceZeroProgress → 跳过采样(置 null),applyProgressDetection 走降级 noProgress=false
683
- var dirtyBefore = forceZeroProgress ? null : readWorktreeDirty(runCwd, gitStatusFn);
684
-
685
- // 构造 prompt + args
686
- // bug-003 fix:readWpDoc 用 config.projectRoot(主工作树 docs/wp/),非 runCwd(worktree,
687
- // git worktree add 不含 gitignored docs/wp/)。spawn cwd 仍用 runCwd。无 override 等价。
688
- var prompt = buildPrompt(pendingAction, config.projectRoot, config.contextWindow);
689
- var args = buildClaudeArgs(config.allowedTools, config.settingsPath);
690
-
691
- // spawn + 超时控制
692
- var stdoutBuf = '';
693
- var stderrBuf = '';
694
- var timedOut = false;
695
- var child;
696
- try {
697
- child = spawnFn(config.binary, args, {
698
- cwd: runCwd,
699
- encoding: 'utf8',
700
- stdio: ['pipe', 'pipe', 'pipe'],
701
- // WP-D1 dogfood 发现:Windows 下 claude 是 npm shim(claude.cmd),
702
- // 无 shell 的 spawn 直接 ENOENT——win32 必须走 shell 解析 .cmd。
703
- // args 均为无空格 token(--allowedTools 逗号串 / --settings 路径由
704
- // Node shell:true 的引用处理覆盖常规空格路径)。
705
- shell: process.platform === 'win32',
706
- });
707
- } catch (e) {
708
- // spawn 立即失败(如 binary 不存在,ENOENT)
709
- trace.spawnMs = Date.now() - spawnStartMs;
710
- return withExecutorTrace(buildFailedChecklist(wpId, 'spawn_failed: ' + ((e && e.code) || (e && e.message) || String(e))), trace);
711
- }
712
-
713
- // prompt 走 stdin(S1):claude -p 从 stdin 读取,规避 argv 长度/泄漏问题。
714
- // 子进程若早退或拒读 stdin,write 会触发 EPIPE——挂 error handler 吞掉,
715
- // 由 child 'close'/'error' 统一收尾,避免 unhandled 异常。
716
- if (child.stdin) {
717
- child.stdin.on('error', function (_e) {});
718
- try {
719
- child.stdin.write(prompt);
720
- child.stdin.end();
721
- } catch (_writeErr) {
722
- // 同步写失败(如 stdin 已关闭):忽略,等 close 事件裁决
723
- }
724
- }
725
-
726
- return new Promise(function (resolve) {
727
- // 超时计时器:到点 kill 子进程
728
- var timer = setTimeout(function () {
729
- timedOut = true;
730
- try {
731
- if (process.platform === 'win32' && child.pid) {
732
- // WP-D1 dogfood 发现:win32 shell:true 时 SIGTERM 杀的是 cmd 包装层,
733
- // claude 孙进程残留 → close 永不到达 → 挂满超时。用 taskkill 进程树击杀。
734
- spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
735
- } else {
736
- child.kill('SIGTERM');
737
- // 宽限 2s 后 SIGKILL
738
- setTimeout(function () {
739
- try { child.kill('SIGKILL'); } catch (_e2) {}
740
- }, 2000);
741
- }
742
- } catch (_e) {}
743
- }, config.timeoutMs);
744
-
745
- if (child.stdout) {
746
- child.stdout.on('data', function (chunk) {
747
- if (chunk) stdoutBuf += chunk.toString();
748
- });
749
- }
750
- if (child.stderr) {
751
- child.stderr.on('data', function (chunk) {
752
- if (chunk) stderrBuf += chunk.toString();
753
- });
754
- }
755
-
756
- child.on('error', function (err) {
757
- clearTimeout(timer);
758
- trace.spawnMs = Date.now() - spawnStartMs;
759
- trace.exitCode = null;
760
- resolve(withExecutorTrace(buildFailedChecklist(wpId, 'spawn_error: ' + (err && err.message ? err.message : String(err))), trace));
761
- });
762
-
763
- child.on('close', function (code) {
764
- clearTimeout(timer);
765
- trace.spawnMs = Date.now() - spawnStartMs;
766
- trace.exitCode = (typeof code === 'number') ? code : null;
767
- trace.timedOut = timedOut === true;
768
- if (timedOut) {
769
- resolve(withExecutorTrace(buildFailedChecklist(wpId, 'timeout'), trace));
770
- return;
771
- }
772
- // 提取 text → 解析 checklist block
773
- var text = extractTextFromClaudeStdout(stdoutBuf);
774
- // token-usage:提取端点元数据(usage/ttft/duration),失败降级 null(不阻断解析)
775
- try {
776
- var meta = extractMetaFromClaudeStdout(stdoutBuf);
777
- trace.tokenUsage = meta.usage;
778
- // 仅当提取到至少一个端点时序时才设 endpointMs,否则保持 null(语义:无端点数据)
779
- if (meta.ttftMs !== null || meta.durationMs !== null) {
780
- trace.endpointMs = { ttft: meta.ttftMs, duration: meta.durationMs };
781
- }
782
- } catch (_me) { /* 元数据提取降级:保持 null */ }
783
- // Phase D 收尾链:schema 校验(谎报硬改判)→ normalize → 客观交叉验证
784
- var raw = parseCheckResult(text);
785
- var chk = finalizeCheckResult(raw, wpId, { cwd: runCwd });
786
-
787
- // 进展检测(WP-191-2-impl):执行后工作树脏度 → 标注 noProgress
788
- // 语义见 applyProgressDetection:工作树有改动=有进展;干净+passed=false=无进展
789
- // forceZeroProgress → 置 null 走降级(与 dirtyBefore 对称)
790
- var dirtyAfter = forceZeroProgress ? null : readWorktreeDirty(runCwd, gitStatusFn);
791
- applyProgressDetection(chk, dirtyBefore, dirtyAfter);
792
- // 非 0 退出码但解析出结果:仍用解析结果(claude 可能正常输出后非 0 退出)
793
- // 非 0 退出码且无解析结果:视为失败
794
- if (code !== 0 && !raw) {
795
- resolve(withExecutorTrace(buildFailedChecklist(wpId, 'claude_exit_' + code + ': ' + stderrBuf.slice(0, 200)), trace));
796
- return;
797
- }
798
- resolve(withExecutorTrace(chk, trace));
799
- });
800
- });
801
- }
802
-
803
- return {
804
- name: 'claude',
805
- run: run,
806
- config: config,
807
- };
808
- }
809
-
810
587
  module.exports = {
811
- createExecutor: createExecutor,
812
588
  // 暴露内部工具便于单元测试
813
589
  _buildPrompt: buildPrompt,
814
590
  _buildClaudeArgs: buildClaudeArgs,
@@ -23,7 +23,7 @@
23
23
  * 文件决定,不追加 --model。settingsPath 为空但探测到 model:追加 `--model <model>`(环境变量场景)。
24
24
  *
25
25
  * SECURITY:
26
- * - S1:prompt 走 stdin,不进 argv(与 executor-claude 一致)。
26
+ * - S1:prompt 走 stdin,不进 argv(对齐 executor-claude internals)。
27
27
  * - 不再注入 ANTHROPIC_BASE_URL/AUTH_TOKEN 环境变量(端点+认证由 settings 文件携带,
28
28
  * executor 注入会与 settings 冲突且有泄漏风险)。智谱旧路径 buildAnthropicEnv 已删除。
29
29
  *
@@ -59,7 +59,7 @@ var applyProgressDetection = claudeInternals._applyProgressDetection;
59
59
  var DEFAULTS = {
60
60
  binary: 'claude', // Claude Code CLI 可执行名
61
61
  timeoutMs: 15 * 60 * 1000, // 单次执行超时 15min(对齐 executor-claude/local)
62
- rateLimitPerHour: 100, // 单实例每小时调用上限(与 executor-claude 一致)
62
+ rateLimitPerHour: 100, // 单实例每小时调用上限(对齐 executor-claude internals)
63
63
  allowedTools: [
64
64
  // 白名单:允许 Claude 读写代码与跑测试,禁止改动 .claude/ 内部状态(防自篡改)
65
65
  'Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash',
@@ -250,7 +250,7 @@ function createExecutor(opts) {
250
250
  ? createQuotaTracker(config.quotaConfig, nowFn)
251
251
  : null;
252
252
 
253
- // 限流状态(与 executor-claude 一致)
253
+ // 限流状态(对齐 executor-claude internals)
254
254
  var callTimestamps = [];
255
255
  var HOUR_MS = 60 * 60 * 1000;
256
256
 
@@ -269,7 +269,7 @@ function createExecutor(opts) {
269
269
  var wpId = pendingAction.wpId || 'unknown';
270
270
 
271
271
  // concurrent-dispatch Step 2(per-WP worktree 隔离):
272
- // per-call projectRoot override(与 executor-claude 一致)。批内 N 个并发 run 各走独立
272
+ // per-call projectRoot override(对齐 executor-claude internals)。批内 N 个并发 run 各走独立
273
273
  // worktree,readWorktreeDirty per-WP 准确、互不串扰(修复 v0.4.0 noProgress 批级串扰)。
274
274
  // 不传 → 走 config.projectRoot(零回归 = v0.4.0)。
275
275
  var runCwd = (typeof pendingAction.projectRoot === 'string' && pendingAction.projectRoot)
@@ -283,7 +283,7 @@ function createExecutor(opts) {
283
283
  var trace = { spawnMs: null, exitCode: null, timedOut: false, rateLimited: false, tokenUsage: null, endpointMs: null };
284
284
  var spawnStartMs = Date.now();
285
285
 
286
- // 限流(与 executor-claude 一致,所有 provider 共用)
286
+ // 限流(对齐 executor-claude internals,所有 provider 共用)
287
287
  var now = Date.now();
288
288
  callTimestamps = callTimestamps.filter(function (ts) { return now - ts < HOUR_MS; });
289
289
  if (callTimestamps.length >= config.rateLimitPerHour) {
@@ -296,7 +296,7 @@ function createExecutor(opts) {
296
296
  // WP-198① 后续(用户「去 glm 限速」第二层):额度降速门控已移除——不再因 5h 窗口接近
297
297
  // 上限返回 quota_exhausted。quota 记账(spawn 后 quota.record)+ 只读视图(quota.windowRatio)
298
298
  // 保留供 observability;softThreshold 字段保留但不再触发停止。loop 永远 spawn(仅受上方
299
- // rateLimitPerHour 通用限流约束,与 executor-claude 一致、所有 provider 共用)。
299
+ // rateLimitPerHour 通用限流约束,对齐 executor-claude internals、所有 provider 共用)。
300
300
 
301
301
  // 进展检测基线(WP-191-2-impl,复用 executor-claude 的工作树脏度判定)
302
302
  // forceZeroProgress → 跳过采样(置 null),applyProgressDetection 走降级 noProgress=false
@@ -333,7 +333,7 @@ function createExecutor(opts) {
333
333
  return _withTrace(buildFailedChecklist(wpId, 'spawn_failed: ' + ((e && e.code) || (e && e.message) || String(e))), trace);
334
334
  }
335
335
 
336
- // prompt 走 stdin(S1,与 executor-claude 一致)
336
+ // prompt 走 stdin(S1,对齐 executor-claude internals)
337
337
  if (child.stdin) {
338
338
  child.stdin.on('error', function (_e) {});
339
339
  try {
@@ -220,6 +220,9 @@ function createExecutor(opts) {
220
220
  allowedTools: (opts.allowedTools && opts.allowedTools.length)
221
221
  ? opts.allowedTools.slice() : DEFAULTS.allowedTools.slice(),
222
222
  resumeSessionId: opts.resumeSessionId || null,
223
+ // v0.3.1 T2:系统提示模式('default' 缺省 / 'lean' 实验性精简——实测校准后
224
+ // 默认保守回退 default;lean 需用户显式配置并在自己端点验证)
225
+ systemPromptMode: opts.systemPromptMode || 'default',
223
226
  };
224
227
 
225
228
  var sdk = opts.sdk !== undefined ? opts.sdk : loadSdk();
@@ -291,6 +294,21 @@ function createExecutor(opts) {
291
294
  abortController: abortController,
292
295
  env: {},
293
296
  };
297
+ // v0.3.1 深审 T2:系统提示瘦身。默认系统提示(~10-30K)+ 动态 env 段是每轮
298
+ // input 的结构性大头。两模式(实测校准 2026-11-08):
299
+ // 'lean':完全自定义精简系统提示(纯字符串,兼容性已实测——请求被智谱端点
300
+ // 正常接受)。**不传 settingSources**——实测发现 `[]` 会把承载第三方端点
301
+ // 配置(GLM env 段)的 user settings 一并隔离 → "Not logged in"。
302
+ // 削减主体 = 系统提示本身(行为规范段),CLAUDE.md/skills 注入保留。
303
+ // 'default'(默认):SDK 缺省全量注入——v0.3.0 行为。preset 结构
304
+ // ({type:'preset',excludeDynamicSections})实测在智谱兼容端点不返回内容
305
+ // (模型空回复),已弃用。
306
+ if (config.systemPromptMode === 'lean') {
307
+ queryOpts.systemPrompt =
308
+ '你是 doukui agentic loop 的执行单元。按用户消息中的 WP 文档用允许的工具完成任务;' +
309
+ '遵循最小改动原则;完成后必须在最终回复产出 ```json:machine-readable 判定块' +
310
+ '(字段:wpId/passed/summary{total,passed,failed}/categories[]/failedItems[])。';
311
+ }
294
312
  if (config.model) queryOpts.model = config.model;
295
313
  if (config.settingsPath) {
296
314
  queryOpts.extraArgs = { settings: config.settingsPath };
@@ -337,8 +355,15 @@ function createExecutor(opts) {
337
355
  applyProgressDetection(chk, dirtyBefore, dirtyAfter);
338
356
 
339
357
  trace.exitCode = consumed.aborted ? -1 : 0;
358
+ // v0.3.1 T5:tokenUsage 归一化为 CLI 口径 {input, cacheRead, output}——
359
+ // 智谱/Anthropic usage 的 cache_read_input_tokens 即隐式缓存命中量,
360
+ // trace 聚合后可算真实命中率(S2 系列优化的度量基础)
340
361
  if (consumed.usage) {
341
- trace.tokenUsage = consumed.usage;
362
+ trace.tokenUsage = {
363
+ input: typeof consumed.usage.input_tokens === 'number' ? consumed.usage.input_tokens : null,
364
+ cacheRead: typeof consumed.usage.cache_read_input_tokens === 'number' ? consumed.usage.cache_read_input_tokens : null,
365
+ output: typeof consumed.usage.output_tokens === 'number' ? consumed.usage.output_tokens : null,
366
+ };
342
367
  }
343
368
  if (consumed.durationMs !== null || consumed.ttftMs !== null) {
344
369
  trace.endpointMs = { ttft: consumed.ttftMs, duration: consumed.durationMs };
@@ -261,6 +261,74 @@ module.exports = {
261
261
  * summary, markdown, lastProximity, failedCount, generatedAt
262
262
  * }
263
263
  */
264
+ /**
265
+ * 生成降级交付报告(v0.4.0 A1——北极星 1 终态语义:自救梯穷尽后不是「停下等人」,
266
+ * 已完成 WP 照常交付 + 未完成项交接明细,人拿到的是「部分成果 + 接手清单」)。
267
+ *
268
+ * 内部复用 generateTerminalReport(趋势/失败项明细同源),追加交付清单段。
269
+ * 纯函数,无副作用。
270
+ *
271
+ * @param {object} state LoopState(同 generateTerminalReport)
272
+ * @param {object} [opts]
273
+ * @param {string[]} [opts.completedWps] 已完成 WP 列表(driver 从 PROGRESS.md 读)
274
+ * @param {string[]} [opts.goalWps] 全量目标 WP(缺省时 pending = goal - completed - failed 推导不出,仅展示两清单)
275
+ * @returns {object} 报告对象(含 terminal 基础字段 + delivered/pendingWps/markdown)
276
+ */
277
+ generateDegradedDeliveryReport: function (state, opts) {
278
+ opts = opts || {};
279
+ var base = module.exports.generateTerminalReport(state, opts);
280
+ var completedWps = Array.isArray(opts.completedWps) ? opts.completedWps : [];
281
+ var goalWps = Array.isArray(opts.goalWps) ? opts.goalWps : [];
282
+
283
+ // 未完成 WP = goal 范围内非 completed 的(failedItems 的 wpId 并集优先展示失败原因)
284
+ var pendingWps = [];
285
+ for (var i = 0; i < goalWps.length; i++) {
286
+ if (completedWps.indexOf(goalWps[i]) === -1) pendingWps.push(goalWps[i]);
287
+ }
288
+
289
+ var lines = [];
290
+ lines.push('## Agentic Loop 降级交付报告');
291
+ lines.push('');
292
+ lines.push('**Loop ID**: `' + base.loopId + '` · **终止原因**: ' + base.verdict +
293
+ ' · **自救链已穷尽**(切换/重置均试过,未达成)');
294
+ lines.push('');
295
+ lines.push('### ✅ 已交付(' + completedWps.length + ' 个 WP,成果已生效)');
296
+ lines.push('');
297
+ if (completedWps.length) {
298
+ for (var c = 0; c < completedWps.length; c++) lines.push('- ' + completedWps[c]);
299
+ } else {
300
+ lines.push('(无已通过 checklist 的 WP)');
301
+ }
302
+ lines.push('');
303
+ lines.push('### ⏳ 未完成(' + pendingWps.length + ' 个 WP,需人接手或重启 loop)');
304
+ lines.push('');
305
+ if (pendingWps.length) {
306
+ for (var p = 0; p < pendingWps.length; p++) lines.push('- ' + pendingWps[p]);
307
+ } else {
308
+ lines.push('(无)');
309
+ }
310
+ lines.push('');
311
+ lines.push('### 失败项明细(接手修复的切入点)');
312
+ lines.push('');
313
+ lines.push(renderFailedItemsTable(base.failedItems));
314
+ lines.push('');
315
+ lines.push('### Proximity 趋势(最近 ' + DEFAULTS.trendTableLimit + ' 轮)');
316
+ lines.push('');
317
+ lines.push(renderTrendTable(base.proximityTrend, DEFAULTS.trendTableLimit));
318
+ lines.push('');
319
+ lines.push('### 建议下一步');
320
+ lines.push('');
321
+ lines.push('- 优先按失败项明细修复未完成 WP(上文 ⏳ 清单),再对剩余 WP 重跑 `doukui loop`(PROGRESS.md 已记完成项,不会重做)');
322
+ lines.push('- ' + (VERDICT_SUMMARIES[base.verdict] || VERDICT_SUMMARIES.timeout));
323
+ lines.push('');
324
+
325
+ base.delivered = completedWps;
326
+ base.pendingWps = pendingWps;
327
+ base.markdown = lines.join('\n');
328
+ base.degradedDelivery = true;
329
+ return base;
330
+ },
331
+
264
332
  generateTerminalReport: function (state, opts) {
265
333
  // 容错:state 完全缺失 → 降级最小报告,不抛异常
266
334
  state = state || {};
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Plan Lint(v0.3.1 T4——plan 质量前置闸)
5
+ // ---------------------------------------------------------------------------
6
+ // 北极星:① 失败前置暴露(verify 命令拼错要等 dispatch 后 15min 超时才炸,
7
+ // 人得盯着第一轮翻车)② 废轮清零(一轮全额 input 白付)。
8
+ //
9
+ // parsePlanToGoal 之后、loop 启动之前跑三道检查:
10
+ // ERROR(拒启):
11
+ // - WP checklist 为空(isExecutableSection 靠动词放行的 section——
12
+ // executor 自报判定无依据,proximity 语义失效)
13
+ // WARNING(放行但告警):
14
+ // - [verify: cmd] 命令的首 token 在本机 PATH 上不可见(拼错如 npm tset
15
+ // 提前暴露;只探测可执行名存在性,不实跑命令)
16
+ // - 整份 plan 零 verify 覆盖(S5 客观验证缺位,全靠 LLM 自报)
17
+ // ---------------------------------------------------------------------------
18
+
19
+ var spawnSync = require('child_process').spawnSync;
20
+
21
+ /**
22
+ * 探测命令首 token 在本机是否可见(where/which,3s 超时;探测失败视为可见——
23
+ * 探测机制本身不可靠时不误杀)。
24
+ * @param {string} command
25
+ * @returns {boolean|null} true=可见 false=不可见 null=无法判定
26
+ */
27
+ function commandResolvable(command) {
28
+ var first = String(command || '').trim().split(/\s+|&&|\|\||;/)[0].replace(/^["']|["']$/g, '');
29
+ if (!first || !/^[\w.\-/]+$/.test(first)) return null; // 复合/特殊命令无法静态判定
30
+ try {
31
+ var res = process.platform === 'win32'
32
+ ? spawnSync('where', [first], { timeout: 3000, stdio: ['ignore', 'pipe', 'pipe'] })
33
+ : spawnSync('which', [first], { timeout: 3000, stdio: ['ignore', 'pipe', 'pipe'] });
34
+ if (res.status === 0) return true;
35
+ if (res.status === 1) return false;
36
+ return null; // where/which 自身异常 → 不判定
37
+ } catch (_e) {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * lint 一份解析后的 plan。
44
+ * @param {object} parsed parsePlanToGoal 产物(含 workPackages/goal)
45
+ * @param {object} [opts] { skipCommandProbe } 测试/CI 可关探测
46
+ * @returns {{ errors: string[], warnings: string[], verifyTotal: number, verifyWithCommand: number }}
47
+ */
48
+ function lintPlan(parsed, opts) {
49
+ opts = opts || {};
50
+ var errors = [];
51
+ var warnings = [];
52
+ var wps = (parsed && parsed.workPackages) || [];
53
+ var verifyTotal = 0;
54
+ var verifyWithCommand = 0;
55
+
56
+ for (var i = 0; i < wps.length; i++) {
57
+ var wp = wps[i];
58
+ var checklist = wp.checklist || [];
59
+ if (checklist.length === 0) {
60
+ // 语义章节(成功标准/验收标准/背景/目标)被历史 WP 编号行为编入 workPackages
61
+ // 属契约模糊而非 plan 缺陷——降级 warning 不拒启(实测 todo-cli-smoke fixture
62
+ // 的「## 成功标准」即此形态)。执行型章节空 checklist 才是 ERROR。
63
+ var semantic = /^(成功标准|验收标准|背景|目标|success|acceptance|background|goal)/i.test(wp.title || '');
64
+ var msg = 'WP ' + wp.wpId + '(' + (wp.title || '') + ')checklist 为空';
65
+ if (semantic) {
66
+ warnings.push(msg + '(语义章节,非执行单元)');
67
+ } else {
68
+ errors.push(msg + '——executor 无判定依据,proximity 语义失效。' +
69
+ '请在 plan 中为该章节补验收任务项(- [ ] ...),或将其改名/并入成功标准章节');
70
+ }
71
+ continue;
72
+ }
73
+ for (var j = 0; j < checklist.length; j++) {
74
+ var item = checklist[j];
75
+ if (!item.verify || !item.verify.command) continue;
76
+ verifyTotal++;
77
+ if (opts.skipCommandProbe) {
78
+ verifyWithCommand++;
79
+ continue;
80
+ }
81
+ // v0.4.0 CI flaky 修复:probeFn 注入点(DI-over-mocking 纪律,先例 spawnFn/gitStatusFn)。
82
+ // 根因:真实 where/which 探测在 Windows CI 高负载下偶发超 3s → status null →
83
+ // 不告警 → 测试断言挂(第一轮过第二轮挂的竞态)。测试注入 probeFn 确定性返回,
84
+ // 不再赌系统命令速度;生产路径不变(null = 探测失败保守不告警,宁漏报不误报)。
85
+ var resolvable = (typeof opts.probeFn === 'function')
86
+ ? opts.probeFn(item.verify.command)
87
+ : commandResolvable(item.verify.command);
88
+ if (resolvable === false) {
89
+ warnings.push('WP ' + wp.wpId + ' 验收项「' + item.item + '」的 verify 命令首个可执行名在本机 PATH 不可见: "' +
90
+ item.verify.command + '"——请确认命令拼写或该依赖已安装(否则该验收项将在实跑时失败)');
91
+ verifyWithCommand++;
92
+ } else {
93
+ verifyWithCommand++;
94
+ }
95
+ }
96
+ }
97
+
98
+ if (wps.length > 0 && verifyTotal === 0) {
99
+ warnings.push('整份 plan 零 [verify: command] 验收项——S5 客观验证缺位,判定完全依赖 LLM 自报' +
100
+ '(可靠性低且费 token)。建议为可命令化的验收项补 verify 标记');
101
+ }
102
+
103
+ return { errors: errors, warnings: warnings, verifyTotal: verifyTotal, verifyWithCommand: verifyWithCommand };
104
+ }
105
+
106
+ module.exports = { lintPlan: lintPlan, commandResolvable: commandResolvable };