doukui 0.3.0 → 0.3.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.
@@ -54,6 +54,9 @@ var ConfigManager = require('../../plugins/runtime/config-manager');
54
54
  var providerResolver = require('../../plugins/runtime/provider-resolver');
55
55
  var contextWindowHelper = require('../../plugins/runtime/context-window');
56
56
  var providerFailover = require('../../plugins/runtime/provider-failover');
57
+ // v0.3.1 T4:plan 质量前置闸(空 checklist 拒启 / verify 命令拼错前置暴露)
58
+ var planLint = require('../../plugins/runtime/plan-lint');
59
+ var selfRescueLadder = require('../../plugins/runtime/self-rescue-ladder');
57
60
  // concurrent-dispatch Step 1(next-dev-plan Batch 2):readyWave 批并发调度。
58
61
  // driver 主循环单 WP dispatch → readyWave 批并发(Promise.allsettled 语义)+ 串行回填。
59
62
  // WP-198①:默认 maxConcurrency=2(并发开箱即用,去默认限速);N=1 串行可经 --concurrency=1
@@ -581,6 +584,22 @@ module.exports = {
581
584
  // WP-S3:plan 风险分级落 state(hook-skill-gate 的 low-risk 豁免依据)
582
585
  // driverStore 初始化在后面——此处用延迟写(init 后补写)。先记标志。
583
586
  var planRiskLow = parsed.riskLow === true;
587
+ // v0.3.1 T4:plan lint 前置闸——空 checklist 拒启;verify 命令拼错/零覆盖前置暴露。
588
+ // 失败前置暴露(否则 verify 拼错要等 dispatch 后 15min 超时才炸,废轮全额 input)
589
+ try {
590
+ var _lint = planLint.lintPlan(parsed);
591
+ for (var _le = 0; _le < _lint.errors.length; _le++) {
592
+ log(ctx.colorize('✗ plan lint ERROR: ' + _lint.errors[_le], 'red'));
593
+ }
594
+ for (var _lw = 0; _lw < _lint.warnings.length; _lw++) {
595
+ log(ctx.colorize('⚠ plan lint: ' + _lint.warnings[_lw], 'yellow'));
596
+ }
597
+ if (_lint.errors.length > 0) {
598
+ log(ctx.colorize('plan lint 未通过(' + _lint.errors.length + ' 个 ERROR),拒绝启动 loop。请修复 plan 后重试', 'red'));
599
+ ctx.exit(2);
600
+ return;
601
+ }
602
+ } catch (_lintErr) { /* lint 自身异常不阻断(降级放行) */ }
584
603
 
585
604
  // WP-202(gap ⑤):缓存 planPath mtime 作 round 边界 mtime-gate 重解析基线。
586
605
  // 稳态每轮仅一次 statSync(近乎免费);mtime 变更 → round 边界重解析 dependencyGraph + wpIds
@@ -710,10 +729,41 @@ module.exports = {
710
729
  }
711
730
 
712
731
  var executor;
732
+ // WP-S1 自救链配置 + v0.3.1 T2 系统提示模式(须在 executor 创建前就绪——
733
+ // createExecutor opts 需要 systemPromptMode;原声明在 completedSet 附近,
734
+ // var 提升导致创建点读到 undefined 抛 TypeError)
735
+ var selfRescueCfg = {
736
+ enabled: true,
737
+ maxSwitches: 2,
738
+ modelFallback: null,
739
+ extraIterations: 3,
740
+ extraWallMs: 30 * 60 * 1000,
741
+ systemPromptMode: 'default',
742
+ };
743
+ try {
744
+ var _cfgAll4 = new ConfigManager().getAll();
745
+ var _srCfg = _cfgAll4 && _cfgAll4.loop && _cfgAll4.loop.self_rescue;
746
+ if (_srCfg && typeof _srCfg === 'object') {
747
+ if (_srCfg.enabled === false) selfRescueCfg.enabled = false;
748
+ if (typeof _srCfg.max_switches === 'number' && _srCfg.max_switches >= 0) {
749
+ selfRescueCfg.maxSwitches = Math.floor(_srCfg.max_switches);
750
+ }
751
+ if (typeof _srCfg.model_fallback === 'string' && _srCfg.model_fallback) {
752
+ selfRescueCfg.modelFallback = _srCfg.model_fallback;
753
+ }
754
+ if (typeof _srCfg.extra_iterations === 'number' && _srCfg.extra_iterations > 0) {
755
+ selfRescueCfg.extraIterations = Math.floor(_srCfg.extra_iterations);
756
+ }
757
+ if (typeof _srCfg.system_prompt_mode === 'string' &&
758
+ ['lean', 'default'].indexOf(_srCfg.system_prompt_mode) !== -1) {
759
+ selfRescueCfg.systemPromptMode = _srCfg.system_prompt_mode;
760
+ }
761
+ }
762
+ } catch (_cfgErr4) { /* 用默认 */ }
713
763
  try {
714
764
  // local executor 只需 projectRoot(mock);default 额外接收 resolver 产物
715
765
  if (args.executor === 'local') {
716
- executor = loopExecutor.createExecutor('local', { projectRoot: projectRoot });
766
+ executor = loopExecutor.createExecutor('local', { projectRoot: projectRoot });
717
767
  } else {
718
768
  executor = loopExecutor.createExecutor(args.executor, {
719
769
  projectRoot: projectRoot,
@@ -722,6 +772,8 @@ module.exports = {
722
772
  provider: resolvedProvider ? resolvedProvider.provider : 'unknown',
723
773
  quotaConfig: resolvedProvider ? resolvedProvider.quotaConfig : null,
724
774
  contextWindow: resolvedProvider ? contextWindowResolved.tokens : null,
775
+ // v0.3.1 T2:系统提示模式(sdk executor 消费;default executor 忽略)
776
+ systemPromptMode: selfRescueCfg.systemPromptMode,
725
777
  });
726
778
  // WP-D3:fallback 配置预解析(profile.fallback_settings → 文件预检)
727
779
  failoverCfg = providerFailover.resolveFallbackConfig({
@@ -860,46 +912,19 @@ module.exports = {
860
912
  // 梯子 = [switch_provider(需 fallback_settings,复用 D3)→ switch_model(需
861
913
  // loop.self_rescue.model_fallback)→ 停(degrade:已完成 WP 保留在 PROGRESS)]。
862
914
  // 每级至多一次、每 loop 至多 maxSwitches 次;SDK session 随 executor 重建作废。
863
- var selfRescueCfg = {
864
- enabled: true,
865
- maxSwitches: 2,
866
- modelFallback: null,
867
- extraIterations: 3,
868
- extraWallMs: 30 * 60 * 1000,
869
- };
870
- try {
871
- var _cfgAll4 = new ConfigManager().getAll();
872
- var _srCfg = _cfgAll4 && _cfgAll4.loop && _cfgAll4.loop.self_rescue;
873
- if (_srCfg && typeof _srCfg === 'object') {
874
- if (_srCfg.enabled === false) selfRescueCfg.enabled = false;
875
- if (typeof _srCfg.max_switches === 'number' && _srCfg.max_switches >= 0) {
876
- selfRescueCfg.maxSwitches = Math.floor(_srCfg.max_switches);
877
- }
878
- if (typeof _srCfg.model_fallback === 'string' && _srCfg.model_fallback) {
879
- selfRescueCfg.modelFallback = _srCfg.model_fallback;
880
- }
881
- if (typeof _srCfg.extra_iterations === 'number' && _srCfg.extra_iterations > 0) {
882
- selfRescueCfg.extraIterations = Math.floor(_srCfg.extra_iterations);
883
- }
884
- }
885
- } catch (_cfgErr4) { /* 用默认 */ }
915
+ // selfRescueCfg 已上移至 executor 创建前(v0.3.1 T2:systemPromptMode 在创建时即需读取)
886
916
  var usedRescues = []; // 本 loop 已用自救级别(顺序即尝试序)
917
+ // v0.3.1 T5:loop 级 token 累计(input/cacheRead/output)——终态汇总真实命中率,
918
+ // 让 S2/lean 等优化有度量依据(cacheRead 来自端点隐式缓存命中)
919
+ var tokenTotals = { input: 0, cacheRead: 0, output: 0, rounds: 0 };
887
920
  /**
888
- * WP-S1:找下一级可用的自救动作(未用过 + 前置条件满足)。
921
+ * WP-S1:找下一级可用的自救动作(v0.3.1 T7 抽为纯函数 self-rescue-ladder.js,
922
+ * 梯子优先级语义由单测锁定;此处仅做闭包状态绑定)
889
923
  * @param {string} verdict 'diverged'|'timeout'
890
924
  * @returns {{type:string}|null} null = 梯子穷尽/自救停用
891
925
  */
892
926
  function planSelfRescue(verdict) {
893
- if (!selfRescueCfg.enabled) return null;
894
- if (usedRescues.length >= selfRescueCfg.maxSwitches) return null;
895
- if (usedRescues.indexOf('switch_provider') === -1 &&
896
- failoverCfg.fallbackSettings && failoverCfg.fallbackFileExists) {
897
- return { type: 'switch_provider' };
898
- }
899
- if (usedRescues.indexOf('switch_model') === -1 && selfRescueCfg.modelFallback) {
900
- return { type: 'switch_model' };
901
- }
902
- return null;
927
+ return selfRescueLadder.planSelfRescue(verdict, selfRescueCfg, usedRescues, failoverCfg);
903
928
  }
904
929
  // WP-D7:per-WP 上轮 SDK session id(retry 续轮)。loop 内闭包累积;
905
930
  // 开关 loop.sdkResumeOnRetry(默认 true);worktree 模式禁用(session cwd 已清理)。
@@ -1067,6 +1092,9 @@ module.exports = {
1067
1092
  }
1068
1093
  if (_rescueOk) {
1069
1094
  usedRescues.push(_rescueAction.type);
1095
+ // v0.3.1 深审修复:自救重建 executor 后必须清空 session 映射——
1096
+ // 旧 provider/model 的 sessionId 注入新 executor 的 resume 是未定义行为
1097
+ sdkSessionIds = {};
1070
1098
  try {
1071
1099
  if (result.verdict === 'diverged') {
1072
1100
  await api.prepareSelfRescue(loopId, {
@@ -1098,6 +1126,14 @@ module.exports = {
1098
1126
  log(ctx.colorize('ℹ WP-S1 自救链已尝试 ' + usedRescues.length + ' 级 [' +
1099
1127
  usedRescues.join(' → ') + '],穷尽后终止。未完成 WP 建议 resplit 或人审', 'yellow'));
1100
1128
  }
1129
+ // v0.3.1 T5:token 汇总(命中率 = cacheRead / (cacheRead + input))
1130
+ if (tokenTotals.rounds > 0) {
1131
+ var _tot = tokenTotals.cacheRead + tokenTotals.input;
1132
+ var _hit = _tot > 0 ? Math.round(tokenTotals.cacheRead / _tot * 100) : 0;
1133
+ log(ctx.colorize('ℹ token 汇总(' + tokenTotals.rounds + ' 轮 dispatch): input=' +
1134
+ tokenTotals.input + ' cacheRead=' + tokenTotals.cacheRead +
1135
+ '(命中率 ' + _hit + '%) output=' + tokenTotals.output, 'gray'));
1136
+ }
1101
1137
  break;
1102
1138
  }
1103
1139
 
@@ -1216,6 +1252,7 @@ module.exports = {
1216
1252
  fallbackSettings: failoverCfg.fallbackSettings,
1217
1253
  });
1218
1254
  switchedToFallback = true;
1255
+ sdkSessionIds = {}; // v0.3.1 深审修复:session 映射随 provider 切换作废(与 D7 注释一致)
1219
1256
  log(ctx.colorize('⚠ provider 窗口占用 ' + (_fbRatio * 100).toFixed(0) +
1220
1257
  '% ≥ 阈值,已切换到 fallback settings(' + failoverCfg.fallbackSettings +
1221
1258
  ');SDK session 作废(WP-D3)', 'yellow'));
@@ -1339,6 +1376,14 @@ module.exports = {
1339
1376
  if (executor.name === 'sdk' && cr && cr._sdkMeta && cr._sdkMeta.sessionId) {
1340
1377
  sdkSessionIds[r.wpId] = cr._sdkMeta.sessionId;
1341
1378
  }
1379
+ // v0.3.1 T5:token 累计(两载体口径已统一 {input,cacheRead,output})
1380
+ var _tu = cr && cr._executorTrace && cr._executorTrace.tokenUsage;
1381
+ if (_tu) {
1382
+ if (typeof _tu.input === 'number') tokenTotals.input += _tu.input;
1383
+ if (typeof _tu.cacheRead === 'number') tokenTotals.cacheRead += _tu.cacheRead;
1384
+ if (typeof _tu.output === 'number') tokenTotals.output += _tu.output;
1385
+ tokenTotals.rounds++;
1386
+ }
1342
1387
  // WP-196-1-impl:每 WP 一条 round record(engine 阶段 + executor trace)
1343
1388
  emitRoundTrace(ctx, log, loopId, result, cr, r.wpId);
1344
1389
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doukui",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Doukui (斗魁) - multi-provider AI agent orchestration harness for Claude Code: goal-driven agentic loop, dependency-graph dispatch, per-WP worktree isolation, for GLM/DeepSeek/MiMo and Claude",
5
5
  "bin": {
6
6
  "doukui": "bin/doukui.js"
@@ -891,11 +891,19 @@ class LoopEngineProvider extends ProviderPlugin {
891
891
  var state = await loadState(loopId);
892
892
  if (!state) return false;
893
893
  state.divergenceStreak = 0;
894
+ // WP-S1 边界修复(v0.3.1 深审):清 history 会丢失末轮 failedCount,
895
+ // 自救后首轮的「部分改进宽容」(computeRefineProgress 读上轮 failedCount)
896
+ // 退化为不可宽容。快照到 selfRescue.prevFailedCount,evaluator 降级读它。
897
+ var lastEntry = (state.history && state.history.length)
898
+ ? state.history[state.history.length - 1] : null;
899
+ var prevFailed = (lastEntry && lastEntry.eval && typeof lastEntry.eval.failedCount === 'number')
900
+ ? lastEntry.eval.failedCount : null;
894
901
  state.history = [];
895
902
  state.selfRescue = {
896
903
  level: (meta && meta.level) || 'unknown',
897
904
  reason: (meta && meta.reason) || '',
898
905
  at: nowIso(),
906
+ prevFailedCount: prevFailed,
899
907
  };
900
908
  await saveState(state);
901
909
  return true;
@@ -922,6 +930,12 @@ class LoopEngineProvider extends ProviderPlugin {
922
930
  ? opts.extraWallMs : 30 * 60 * 1000;
923
931
  self._config.max_iterations += extraIter;
924
932
  self._config.max_wall_time_ms += extraWall;
933
+ // WP-S1 边界修复(v0.3.1 深审):timeout 自救若不清发散计数,streak 已满时
934
+ // 续跑第一轮不改进会被 _decide 立即判 diverged(发散判定优先于上限)——
935
+ // 一次自救级别被白白烧掉。extendBudget 语义 = 「换了手段重新评估」,
936
+ // 与 prepareSelfRescue 同样需要清 streak + history。
937
+ state.divergenceStreak = 0;
938
+ state.history = [];
925
939
  var prevBonus = (state.selfRescue && state.selfRescue.budgetBonus) || { iterations: 0, wallMs: 0 };
926
940
  state.selfRescue = {
927
941
  level: (meta && meta.level) || 'extend_budget',
@@ -238,7 +238,23 @@ loop 是半自主的,**入口必须经 P1 人确认**。调用 `skill-human-ch
238
238
 
239
239
  > design 把状态放在 `state-store` key `loop.{loopId}`(engine 测试用)。运行时由 Claude 通过 PROGRESS.md 维护等效信息(progress-tracker),防上下文压缩。
240
240
 
241
- ### Step 3: 主循环(Claude 按规则迭代,按 verdict 分流)
241
+ ### Step 2.5: 路径选择(v0.3.1 T6——driver 子进程优先,镜像降级)🔴
242
+
243
+ **探测 `doukui --version`(或 `node <doukui包根>/bin/doukui.js --version`)**:
244
+
245
+ - **✅ CLI 可用 → 必须走 driver 子进程路径(主路径)**:
246
+ 1. 用 Bash 后台启动:`doukui loop <plan 路径> --executor=default --loop-id=<本 loopId> [--settings=<provider 配置>] &`
247
+ —— 决策由 **JS engine 真跑**(Observe→Think→Reflect→Decide 全在 driver 进程内),本会话只做监控,**不复现任何判定规则**
248
+ 2. 监控协议(每 30~60s 轮询一次,用 Bash `tail`):
249
+ - `.doukui/loop-{loopId}/trace.jsonl` 尾部 1 行 = 最新轮次的五段计时 + verdict + token
250
+ - `PROGRESS.md` = WP 完成标记
251
+ - 终态:driver 退出(`wait` 或检查进程)后读 stdout 尾部的「Agentic Loop 终止报告」呈现给用户;含 `♻ WP-S1 自救` 行则说明自救链已自动介入
252
+ 3. 会话在 loop 运行期间**只读不写**仓库文件(driver 子进程持有执行权,并行写会冲突)
253
+ - **⚠️ CLI 不可用(未安装/无 provider settings)→ 走下方 Step 3 镜像路径(降级)**:
254
+ Step 3 的规则框是 engine 决策的**行为镜像**,仅在无 driver 可启动时按其自轮询。
255
+ 镜像与 engine 的一致性由 `test-agentic-loop-skill-mirror.js` CI 锁定。
256
+
257
+ ### Step 3: 主循环(Claude 按规则迭代,按 verdict 分流)【降级路径——CLI 可用时走 Step 2.5 driver 路径】
242
258
 
243
259
  这是 loop 的核心。**Claude 循环执行 Observe→Think→Act→Reflect→Decide 一轮,按 verdict 分流**。判定规则严格复现 `provider-loop-engine` 的 `_think` / `_decide` / evaluator 语义(见下方各步规则框)。
244
260
 
@@ -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 };
@@ -0,0 +1,100 @@
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
+ var resolvable = commandResolvable(item.verify.command);
82
+ if (resolvable === false) {
83
+ warnings.push('WP ' + wp.wpId + ' 验收项「' + item.item + '」的 verify 命令首个可执行名在本机 PATH 不可见: "' +
84
+ item.verify.command + '"——请确认命令拼写或该依赖已安装(否则该验收项将在实跑时失败)');
85
+ verifyWithCommand++;
86
+ } else {
87
+ verifyWithCommand++;
88
+ }
89
+ }
90
+ }
91
+
92
+ if (wps.length > 0 && verifyTotal === 0) {
93
+ warnings.push('整份 plan 零 [verify: command] 验收项——S5 客观验证缺位,判定完全依赖 LLM 自报' +
94
+ '(可靠性低且费 token)。建议为可命令化的验收项补 verify 标记');
95
+ }
96
+
97
+ return { errors: errors, warnings: warnings, verifyTotal: verifyTotal, verifyWithCommand: verifyWithCommand };
98
+ }
99
+
100
+ module.exports = { lintPlan: lintPlan, commandResolvable: commandResolvable };
@@ -144,6 +144,11 @@ function _clampFailed(n) {
144
144
  * @returns {number|null} 上轮失败项数;无 history 或末轮无 failedCount 时 null
145
145
  */
146
146
  function prevFailedCountFromHistory(state) {
147
+ if (state && state.selfRescue && typeof state.selfRescue.prevFailedCount === 'number') {
148
+ // WP-S1 边界修复(v0.3.1):自救清空 history 后,发散宽容的上轮 failedCount
149
+ // 从自救快照降级读取——保证自救后首轮的「部分改进仍被宽容」
150
+ return state.selfRescue.prevFailedCount;
151
+ }
147
152
  if (!state || !state.history || !state.history.length) return null;
148
153
  var last = state.history[state.history.length - 1];
149
154
  if (last && last.eval && typeof last.eval.failedCount === 'number') {
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Self-Rescue Ladder(v0.3.1 T7——从 loop.js 闭包抽取的纯函数)
5
+ // ---------------------------------------------------------------------------
6
+ // 深审维度 1:梯子优先级逻辑(provider 优先于 model、每级一次、穷尽返回 null)
7
+ // 原内嵌在 driver execute 闭包内无法直测。抽出纯函数 + 单测锁定语义。
8
+ // ---------------------------------------------------------------------------
9
+
10
+ /**
11
+ * 找下一级可用的自救动作。
12
+ * @param {string} verdict 'diverged'|'timeout'(其它 verdict 不自救)
13
+ * @param {object} cfg { enabled, maxSwitches, modelFallback }
14
+ * @param {string[]} used 已用级别(顺序即尝试序)
15
+ * @param {object} failoverCfg { fallbackSettings, fallbackFileExists }(WP-D3 预解析产物)
16
+ * @returns {{ type: string }|null} null = 梯子穷尽/自救停用
17
+ */
18
+ function planSelfRescue(verdict, cfg, used, failoverCfg) {
19
+ if (verdict !== 'diverged' && verdict !== 'timeout') return null;
20
+ cfg = cfg || {};
21
+ if (cfg.enabled === false) return null;
22
+ used = Array.isArray(used) ? used : [];
23
+ if (used.length >= (cfg.maxSwitches || 0)) return null;
24
+ failoverCfg = failoverCfg || {};
25
+
26
+ // 优先级 ①:换 provider(需 fallback settings 可读——复用 WP-D3 预解析)
27
+ if (used.indexOf('switch_provider') === -1 &&
28
+ failoverCfg.fallbackSettings && failoverCfg.fallbackFileExists) {
29
+ return { type: 'switch_provider' };
30
+ }
31
+ // 优先级 ②:换模型(需显式配置备用模型档)
32
+ if (used.indexOf('switch_model') === -1 && cfg.modelFallback) {
33
+ return { type: 'switch_model' };
34
+ }
35
+ return null;
36
+ }
37
+
38
+ module.exports = { planSelfRescue: planSelfRescue };
@@ -255,6 +255,12 @@ loop:
255
255
  extra_iterations: 3 # timeout 自救每次追加的迭代预算
256
256
  # extra_wall_ms: 1800000 # timeout 自救每次追加的墙钟(默认 30min)
257
257
 
258
+ # v0.3.1 T2 系统提示瘦身(仅 --executor=sdk 生效):
259
+ # lean = 自定义精简系统提示替换 SDK 默认大提示(实测每轮 input 结构性大头),
260
+ # 保留 CLAUDE.md/skills 注入与端点配置——省 token 显著但需自行验证任务质量;
261
+ # default = SDK 全量注入(v0.3.0 行为,安全默认)。
262
+ # system_prompt_mode: lean
263
+
258
264
  # concurrent-dispatch Step 1:readyWave 并发批调度度。
259
265
  # WP-198①:默认并发 2(去默认限速,所有 provider 一视同仁——不再因 GLM 降速)。
260
266
  # 优先级:--concurrency flag > 此值 > 2(默认)。N=1 显式串行回退。