dsh-workplan 3.0.2 → 3.0.6

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.
@@ -45,7 +45,7 @@ import { diceSimilarity } from './v3-contract.js'
45
45
  /** 三阶段顺序不可颠倒;这里也是结果块里 `phases` 的键名。 */
46
46
  export const THREE_PHASE_IDS = Object.freeze(['planning', 'execution', 'verification'] as const)
47
47
  /** [2.5.1] 契约版本 2:规划阶段升级为两轮深度思考协议(新增必填 approachBasis)。 */
48
- export const THREE_PHASE_VERSION = 2
48
+ export const THREE_PHASE_VERSION = 3
49
49
 
50
50
  /**
51
51
  * 「全面、全盘、深入」无法由代码度量,但可以给一个不可忽略的下限:
@@ -55,6 +55,10 @@ export const THREE_PHASE_VERSION = 2
55
55
  export const MIN_PLANNING_PROBLEM_CHARS = 40
56
56
  export const MIN_PLANNING_APPROACH_CHARS = 40
57
57
  export const MIN_PLANNING_BASIS_CHARS = 20
58
+ /** [3.1.0] 第二步资源与工具、第三步准备与就绪证据的下限(合计字符数)。 */
59
+ export const MIN_RESOURCE_CHARS = 20
60
+ export const MIN_TOOL_CHARS = 10
61
+ export const MIN_PREPARATION_CHARS = 20
58
62
  export const MAX_PHASE_LIST_ITEMS = 20
59
63
  export const MAX_PHASE_ITEM_CHARS = 800
60
64
  export const MAX_PHASE_TOTAL_CHARS = 6000
@@ -70,6 +74,10 @@ export type PlanningPhase = {
70
74
  problemAnalysis: string[]
71
75
  constraints: string[]
72
76
  unknowns: string[]
77
+ /** [3.1.0] 第二步 · 资源研究:完成本任务需要哪些资源(数据、文件、权限、人、知识、时间)。 */
78
+ resources: string[]
79
+ /** [3.1.0] 第二步 · 工具研究:完成本任务需要哪些工具,以及每个工具用来做什么。 */
80
+ tools: string[]
73
81
  /** [2.5.1] 第二轮 · 基于第一轮全部结果理清的方法、流程、步骤(一步步执行的路径)。 */
74
82
  approach: string[]
75
83
  /**
@@ -80,6 +88,17 @@ export type PlanningPhase = {
80
88
  approachBasis: string[]
81
89
  }
82
90
 
91
+ /**
92
+ * [3.1.0] 第三步 · 准备工作:把第二步研究出的资源与工具真正备齐(不是「打算用」,
93
+ * 而是「已就绪」)。每条都要有可复核的就绪证据,缺证据的资源不得进入执行。
94
+ */
95
+ export type PreparationPhase = {
96
+ /** 已准备好的资源/工具清单:每一项写清准备了什么、在哪里、是否可用。 */
97
+ prepared: string[]
98
+ /** 就绪证据:命令输出、文件路径、配置项、版本号或引用;与 prepared 一一对应。 */
99
+ evidence: string[]
100
+ }
101
+
83
102
  export type ExecutionPhase = {
84
103
  steps: string[]
85
104
  deviations: string[]
@@ -102,6 +121,7 @@ export type VerificationPhase = {
102
121
  export type ThreePhases = {
103
122
  version: number
104
123
  planning: PlanningPhase
124
+ preparation: PreparationPhase
105
125
  execution: ExecutionPhase
106
126
  verification: VerificationPhase
107
127
  }
@@ -111,7 +131,7 @@ export type PhaseValidation = {
111
131
  phases: ThreePhases | null
112
132
  errors: string[]
113
133
  /** 错误落在哪个阶段:'planning' | 'execution' | 'verification' | 'shape' */
114
- failedPhase: 'planning' | 'execution' | 'verification' | 'shape' | null
134
+ failedPhase: 'planning' | 'preparation' | 'execution' | 'verification' | 'shape' | null
115
135
  }
116
136
 
117
137
  function isRecord(value: any): value is Record<string, any> {
@@ -150,8 +170,8 @@ function totalChars(items: string[]) {
150
170
  }
151
171
 
152
172
  /**
153
- * Same matching rules as `src/plan.ts#acceptanceCoverage` (Q6 / U-16 +
154
- * [2.0.4] 同义改写两条宽松规则,逐字对齐 plan.ts:3177-3202):
173
+ * Same matching rules as `src/plan.ts#acceptanceCoverage`([4th batch] 归一化逐字
174
+ * 对齐 plan.ts:3300-3309:全角折叠、完成态前缀剥离、去标点、去祈使前缀):
155
175
  * stable A1…An numbering, exact full text, a longer text containing the
156
176
  * full criterion, a near-full copy (≥85% of the criterion length), or a
157
177
  * paraphrase with Dice ≥ 0.70 and matching negation polarity. A partial
@@ -163,7 +183,11 @@ function totalChars(items: string[]) {
163
183
  */
164
184
  function normaliseCriterion(value: any) {
165
185
  return String(value ?? '')
186
+ .trim()
187
+ .replace(/[!-~]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 0xFEE0))
188
+ .replace(/ /g, ' ')
166
189
  .toLowerCase()
190
+ .replace(/^(?:已完成|完成|已|done|yes)(?=[\s::,,。.!!??;;、\-—–]|$)|^(?:已完成|完成|已)/i, '')
167
191
  .replace(/[\s,。;、,.;::!!??"'“”‘’()()\[\]【】《》<>]/g, '')
168
192
  .replace(/^(必须|需要|应当|应该|请|务必)/, '')
169
193
  }
@@ -213,12 +237,14 @@ export function validatePhaseEvidence(value: any, expectedAcceptance: any = []):
213
237
  return {
214
238
  ok: false,
215
239
  phases: null,
216
- errors: ['phases 缺失:必须提交 planning / execution / verification 三阶段证据'],
240
+ errors: ['phases 缺失:必须提交 planning(第一、二步)/ preparation(第三步)/ execution(第四步)/ verification(第四步验证)四组证据,第五步用 report / departmentSummary 交付'],
217
241
  failedPhase: 'shape',
218
242
  }
219
243
  }
220
244
  const planningRaw = isRecord(value.planning) ? value.planning : null
221
- if (!planningRaw) fail('planning', 'phases.planning 缺失(阶段一 · 两轮深度思考:先全面、全盘、深入梳理、研究、思考自己的任务,再基于其全部结果理清方法、流程、步骤)')
245
+ if (!planningRaw) fail('planning', 'phases.planning 缺失(第一步 · 任务梳理 + 第二步 · 资源/工具/实施方案研究:先全面、全盘、深入梳理研究自己的任务,再基于其结果研究需要哪些资源、哪些工具、具体实施方案)')
246
+ const preparationRaw = isRecord(value.preparation) ? value.preparation : null
247
+ if (!preparationRaw) fail('preparation', 'phases.preparation 缺失(第三步 · 准备:把第二步研究出的资源、工具、实施方案真正备齐,并给出就绪证据)')
222
248
  const executionRaw = isRecord(value.execution) ? value.execution : null
223
249
  if (!executionRaw) fail('execution', 'phases.execution 缺失(阶段二:基于第二轮理清的方法、流程、步骤执行)')
224
250
  const verificationRaw = isRecord(value.verification) ? value.verification : null
@@ -239,6 +265,14 @@ export function validatePhaseEvidence(value: any, expectedAcceptance: any = []):
239
265
  required: !!planningRaw,
240
266
  minItems: 1,
241
267
  }),
268
+ resources: readTextList(planningRaw?.resources, 'phases.planning.resources', errors, {
269
+ required: !!planningRaw,
270
+ minItems: 1,
271
+ }),
272
+ tools: readTextList(planningRaw?.tools, 'phases.planning.tools', errors, {
273
+ required: !!planningRaw,
274
+ minItems: 1,
275
+ }),
242
276
  }
243
277
  if (errors.some((item) => item.startsWith('phases.planning.problemAnalysis'))) failedPhase ||= 'planning'
244
278
  if (errors.some((item) => item.startsWith('phases.planning.approach'))) failedPhase ||= 'planning'
@@ -252,6 +286,31 @@ export function validatePhaseEvidence(value: any, expectedAcceptance: any = []):
252
286
  fail('planning', `phases.planning.approachBasis 太薄(合计 ${totalChars(planning.approachBasis)} 字,至少 ${MIN_PLANNING_BASIS_CHARS} 字):要写清第二轮的方法、流程、步骤如何基于第一轮梳理、研究、思考完成好的所有结果`)
253
287
  }
254
288
 
289
+ if (planning.resources.length > 0 && totalChars(planning.resources) < MIN_RESOURCE_CHARS) {
290
+ fail('planning', `phases.planning.resources 太薄(合计 ${totalChars(planning.resources)} 字,至少 ${MIN_RESOURCE_CHARS} 字):第二步要逐项写清完成本任务需要哪些资源(数据/文件/权限/人/知识/时间),缺一项就会在执行中卡住`)
291
+ }
292
+ if (planning.tools.length > 0 && totalChars(planning.tools) < MIN_TOOL_CHARS) {
293
+ fail('planning', `phases.planning.tools 太薄(合计 ${totalChars(planning.tools)} 字,至少 ${MIN_TOOL_CHARS} 字):第二步要逐项写清需要哪些工具、每个工具用来做什么、为什么选它`)
294
+ }
295
+
296
+ const preparation: PreparationPhase = {
297
+ prepared: readTextList(preparationRaw?.prepared, 'phases.preparation.prepared', errors, {
298
+ required: !!preparationRaw,
299
+ minItems: 1,
300
+ }),
301
+ evidence: readTextList(preparationRaw?.evidence, 'phases.preparation.evidence', errors, {
302
+ required: !!preparationRaw,
303
+ minItems: 1,
304
+ }),
305
+ }
306
+ if (errors.some((item) => item.startsWith('phases.preparation'))) failedPhase ||= 'preparation'
307
+ if (preparation.prepared.length > 0 && totalChars(preparation.prepared) < MIN_PREPARATION_CHARS) {
308
+ fail('preparation', `phases.preparation.prepared 太薄(合计 ${totalChars(preparation.prepared)} 字,至少 ${MIN_PREPARATION_CHARS} 字):第三步要把第二步研究出的资源与工具真正备齐,逐项写清准备了什么、在哪里、是否可用`)
309
+ }
310
+ if (preparation.evidence.length > 0 && totalChars(preparation.evidence) < MIN_PREPARATION_CHARS) {
311
+ fail('preparation', `phases.preparation.evidence 太薄(合计 ${totalChars(preparation.evidence)} 字,至少 ${MIN_PREPARATION_CHARS} 字):每一项就绪状态都要有可复核的证据(命令输出/文件路径/配置项/版本号/引用)`)
312
+ }
313
+
255
314
  const execution: ExecutionPhase = {
256
315
  steps: readTextList(executionRaw?.steps, 'phases.execution.steps', errors, {
257
316
  required: !!executionRaw,
@@ -318,6 +377,7 @@ export function validatePhaseEvidence(value: any, expectedAcceptance: any = []):
318
377
  const phases: ThreePhases = {
319
378
  version: THREE_PHASE_VERSION,
320
379
  planning,
380
+ preparation,
321
381
  execution,
322
382
  verification,
323
383
  }
@@ -327,6 +387,10 @@ export function validatePhaseEvidence(value: any, expectedAcceptance: any = []):
327
387
  ...planning.unknowns,
328
388
  ...planning.approach,
329
389
  ...planning.approachBasis,
390
+ ...planning.resources,
391
+ ...planning.tools,
392
+ ...preparation.prepared,
393
+ ...preparation.evidence,
330
394
  ...execution.steps,
331
395
  ...execution.deviations,
332
396
  verification.requirementCheck,
@@ -343,9 +407,9 @@ export function validatePhaseEvidence(value: any, expectedAcceptance: any = []):
343
407
  * Used by `dsh_workplan_verify`: planning/execution gaps mean the caller is
344
408
  * still in phase 1 or 2, where the plugin is disabled by the user's rule.
345
409
  */
346
- export function phaseGateFromErrors(errors: string[]): 'phase-1-2' | 'verification' {
347
- return errors.some((item) => /^phases(\.| 缺失)/.test(item) && /planning|execution/.test(item))
348
- ? 'phase-1-2'
410
+ export function phaseGateFromErrors(errors: string[]): 'phase-1-3' | 'verification' {
411
+ return errors.some((item) => /^phases(\.| 缺失)/.test(item) && /planning|preparation|execution/.test(item))
412
+ ? 'phase-1-3'
349
413
  : 'verification'
350
414
  }
351
415
 
@@ -353,12 +417,14 @@ export function phaseGateFromErrors(errors: string[]): 'phase-1-2' | 'verificati
353
417
  export function phaseSummaryLine(phases: ThreePhases): string {
354
418
  const deviations = phases.execution.deviations.length
355
419
  return [
356
- `阶段一 规划 · 两轮深度思考(第一轮任务深研 ${phases.planning.problemAnalysis.length} 条 / 第二轮方法流程步骤 ${phases.planning.approach.length} 步 / 第二轮依据 ${phases.planning.approachBasis.length} 条)`,
357
- `阶段二 执行(${phases.execution.steps.length} 步${deviations ? ` / 偏离 ${deviations} 处` : ''})`,
358
- `阶段三 验证(${phases.verification.checks.length} 项${phases.verification.allPassed ? ',全部通过' : ',未全部通过'};`
420
+ `第一步 任务梳理(${phases.planning.problemAnalysis.length} 条)`,
421
+ `第二步 资源/工具/方案研究(资源 ${phases.planning.resources.length} 项 / 工具 ${phases.planning.tools.length} 项 / 方法 ${phases.planning.approach.length} 步 / 依据 ${phases.planning.approachBasis.length} 条)`,
422
+ `第三步 准备(已备 ${phases.preparation.prepared.length} 项 / 就绪证据 ${phases.preparation.evidence.length} 条)`,
423
+ `第四步 执行与验证(执行 ${phases.execution.steps.length} 步${deviations ? ` / 偏离 ${deviations} 处` : ''};验证 ${phases.verification.checks.length} 项${phases.verification.allPassed ? ',全部通过' : ',未全部通过'};`
359
424
  + `复盘 ${phases.verification.retrospective.problems.length} 个问题 / `
360
425
  + `${phases.verification.retrospective.detours.length} 条弯路 / `
361
426
  + `${phases.verification.retrospective.prevention.length} 条防再犯规则)`,
427
+ '第五步 JSON 交付(report / departmentSummary,只含关键信息)',
362
428
  ].join(';')
363
429
  }
364
430
 
@@ -371,26 +437,29 @@ export function phaseSummaryLine(phases: ThreePhases): string {
371
437
  */
372
438
  export function threePhasePromptLines(): string[] {
373
439
  return [
374
- '三阶段工作法(用户强制要求;顺序不可颠倒,阶段一的两轮深度思考没有完成之前禁止动手执行):',
375
- '【阶段一 · 规划阶段 = 两轮深度思考(部门负责人、全球顶尖专家执行自己的任务时同一口径,顺序与依赖不可颠倒)】',
376
- ' 第一轮 · 任务深研:先全面、全盘、深入梳理、研究、思考自己的任务——逐条写清任务目标与验收标准、现状与已知事实、约束条件、未知/待确认项、主要矛盾、工作边界与依赖,结果写入 phases.planning.problemAnalysis;',
377
- ' 第二轮 · 理清方法流程步骤:基于刚才第一轮完成好的所有结果,再全面、全盘、深入地开展梳理、研究和思考,理清自己的思路,理清自己该具体如何一步步以最高效率执行、确保完美完成自己任务的方法、流程和步骤——每一步做什么、产出什么、依赖什么、风险与对策、如何证明做对了,并写清全程如何少走弯路(先查历史教训记忆、先验证再动手、不重复同样的试错),结果写入 phases.planning.approach;同时把第二轮如何基于第一轮全部结果写入 phases.planning.approachBasis(逐条对应:第一轮的哪些事实/约束/矛盾决定了第二轮的哪些方法/流程/步骤);',
378
- ' 自检:任何一条验收标准或用户原要求没有落在第二轮的方法、流程、步骤上,就回到第一轮重做;两轮深度思考没有完成并写全(problemAnalysis + approach + approachBasis)之前,不得进入阶段二。',
379
- '【阶段二 · 执行阶段】',
380
- ' 最后,基于刚才第二轮理清楚的所有方法、流程、步骤,开始具体的执行工作:严格按 phases.planning.approach 执行。出现新事实需要偏离时,必须记录偏离原因、证据与调整后的做法,不得静默改道。',
381
- '【阶段三 · 验证阶段】',
382
- ' 执行完成后逐条验证验收标准与用户原要求:每条都要有可复核的证据(命令输出/文件/引用);验证未通过不得报 done,无法确认写 unverified。',
383
- '【阶段三收尾 · 自我学习复盘(强制)】',
440
+ '五步工作法(用户 2026-11-17 强制要求,取代旧的三阶段口径;五个步骤必须按顺序执行,前一步没有完成并写好证据之前,禁止进入下一步):',
441
+ '【第一步 · 任务梳理(部门负责人、相关领域全球顶尖专家执行自己的任务时同一口径)】',
442
+ ' 先全面、全盘、深入梳理、研究、思考自己的任务:逐条写清任务目标与验收标准、现状与已知事实、约束条件、未知/待确认项、主要矛盾、工作边界与依赖,结果写入 phases.planning.problemAnalysis(约束写 constraints,未知写 unknowns)。',
443
+ '【第二步 · 资源、工具与实施方案研究】',
444
+ ' 基于第一步完成好的所有结果,再全面、全盘、深入地梳理、研究、思考:完成本任务需要哪些资源(数据/文件/权限/人/知识/时间)写入 phases.planning.resources;需要哪些工具、每个工具用来做什么写入 phases.planning.tools;具体实施方案写成自己该具体如何一步步以最高效率执行、确保完美完成自己任务的方法、流程和步骤(每一步做什么、产出什么、依赖什么、风险与对策、如何证明做对了,以及全程如何少走弯路:先查历史教训、先验证再动手、不重复试错)写入 phases.planning.approach;同时把第二步如何基于第一步全部结果逐条对应写入 phases.planning.approachBasis。',
445
+ ' 自检:任何一条验收标准或用户原要求没有落在第二步的资源、工具与实施方案上,就回到第一步重做。',
446
+ '【第三步 · 准备】',
447
+ ' 基于第二步的全部结果,把需要的资源、工具、实施方案真正准备到位,而不是「打算用」:逐项写清准备了什么、在哪里、是否可用,写入 phases.preparation.prepared;每一项就绪状态都必须给出可复核的证据(命令输出/文件路径/配置项/版本号/引用),写入 phases.preparation.evidence。缺资源、缺工具、缺证据时,先补齐或如实上报受阻,不得带着缺口进入第四步。',
448
+ '【第四步 · 执行与验证】',
449
+ ' 基于第三步备齐的成果和既定实施方案,开始具体执行,严格按 phases.planning.approach 落地;出现新事实需要偏离时,必须记录偏离原因、证据与调整后的做法,不得静默改道,执行步骤写入 phases.execution.steps。',
450
+ ' 执行完成后逐条验证验收标准与用户原要求:每条都要有可复核的证据(命令输出/文件/引用);验证未通过不得报 done,无法确认写 unverified;结果写入 phases.verification。',
451
+ '【第四步收尾 · 自我学习复盘(强制)】',
384
452
  ' 报 done 之前必须把 phases.verification.retrospective 写全,四项缺一不可:',
385
453
  ' 1) problems:本次全过程遇到的所有问题(现象 + 根因),至少 1 条;',
386
454
  ' 2) detours:走过的弯路、返工与无效尝试(确实没有就写空数组 [],不要编造);',
387
455
  ' 3) resolutions:最终是如何解决上述问题的,至少 1 条,可与 problems 一一对应;',
388
456
  ' 4) prevention:以后如何预防再犯,至少 1 条,必须写成「遇到…先…」的可执行硬规则。',
389
- ' 插件会在完成判定时复核这四项,并在通过后把复盘写入永久记忆文件;下次派发同类任务时,历史教训会自动出现在提示词里。',
390
- '插件使用说明(三阶段证据门禁):',
391
- ' - 阶段一、二:先把两轮深度思考产物(第一轮任务深研 problemAnalysis、第二轮方法流程步骤 approach、第二轮依据 approachBasis)与执行记录写全;此时不要调用 dsh_workplan_verify,它会因缺少前两阶段证据返回 PHASE_GATE 与待补项(这是证据门禁,不是禁用插件)。',
392
- ' - 阶段三:可以调用 dsh_workplan_verify 让插件做最终核验:提交 planning / execution / verification 三阶段证据,插件返回 passed 或仍需补齐的 gaps;未通过先修复再回报。遇阻时可用 dsh_workplan_escalate 上报,它是安全通道,不属于三阶段产物。',
393
- ' - 结果块里的 phases 是必填项:缺任一阶段、内容为空、或验证未全部通过,插件都会判为未完成,不能用 done 收尾。',
457
+ '【第五步 · JSON mode 结构化交付给本部门负责人】',
458
+ ' 执行完美完成后,必须把成果以 JSON mode 结构化交回本部门负责人:专家写入 report 对象(只允许 keyResults / keyInfo / importantInfo / leadRequirements 四个字符串数组字段,只写关键信息、关键成果、重要信息和负责人要求的东西,禁止过程流水账与重复表述);部门负责人写入 departmentSummary 对象(keyResults / keyInfo / importantInfo / sources,汇总本部门全部专家汇报,sources 必须覆盖全部已派发专家)。成果块必须放在 <!-- WORKPLAN_EVIDENCE:START --> 与 <!-- WORKPLAN_EVIDENCE:END --> 之间,且是合法 JSON,不得用散文代替。',
459
+ '插件使用说明(五步证据门禁):',
460
+ ' - 第一、二、三步:先把问题梳理、资源/工具/实施方案、准备与就绪证据写全;此时不要调用 dsh_workplan_verify,它会因缺少前几步证据返回 PHASE_GATE 与待补项(这是证据门禁,不是禁用插件)。',
461
+ ' - 第四步:可以调用 dsh_workplan_verify 让插件做最终核验:提交 planning / preparation / execution / verification 证据,插件返回 passed 或仍需补齐的 gaps;未通过先修复再回报。遇阻时可用 dsh_workplan_escalate 上报,它是安全通道,不属于五步产物。',
462
+ ' - 结果块里的 phases 是必填项:缺 planning / preparation / execution / verification 任一组、内容为空、或验证未全部通过,插件都会判为未完成,不能用 done 收尾;第五步缺 report / departmentSummary 同样判为未完成。',
394
463
  ]
395
464
  }
396
465
 
@@ -25,10 +25,16 @@
25
25
  * 3. check — compare the plan (and the model's own restatement) against the
26
26
  * read-only anchor, and report every dropped hard element.
27
27
  *
28
- * Everything here is pure: no model call, no network, no clock, no filesystem.
29
- * The same inputs always produce the same audit, which makes the result
30
- * reproducible and unit-testable. A model-based reviewer would be *another*
31
- * opinion, not evidence — so it is deliberately not part of this path.
28
+ * Almost everything here is pure: no model call, no network, no filesystem.
29
+ * The audit functions always produce the same result for the same inputs,
30
+ * which makes them reproducible and unit-testable. A model-based reviewer
31
+ * would be *another* opinion, not evidence — so it is deliberately not part
32
+ * of this path.
33
+ *
34
+ * The one deliberate exception is the clarify gate (auditClarifyNeed): it
35
+ * keeps a small in-memory round counter per session with a wall-clock TTL so
36
+ * the gate cannot ask the user the same class of question forever (see
37
+ * CLARIFY_GATE_MAX_ROUNDS below). The audit stages themselves stay pure.
32
38
  *
33
39
  * Failure policy (why not everything blocks)
34
40
  * ------------------------------------------
@@ -216,6 +222,11 @@ export interface PlanAuditContext {
216
222
  sourceMessageIds?: string[]
217
223
  /** `false` downgrades every blocking error to a warning (rollback switch). */
218
224
  strict?: boolean
225
+ /**
226
+ * [3.0.2] 澄清闸轮次计数按会话隔离:调用方传 sessionId 时,
227
+ * 上限/自愈均按该会话独立计算;缺省回落到共享默认键。
228
+ */
229
+ sessionId?: string
219
230
  }
220
231
 
221
232
  export interface PlanContextValidation {
@@ -731,7 +742,7 @@ export function resolvePronounAntecedentInline(token: string, taskText: string):
731
742
  * C4 missing UI object — a display change (折叠/展开/按钮…) that names no surface
732
743
  * (左侧栏/截图/插件…), so any implementation would be a guess.
733
744
  */
734
- export function auditClarifyNeed(
745
+ function auditClarifyNeedRules(
735
746
  taskText: unknown,
736
747
  conversationContext = '',
737
748
  ): { needed: boolean; rule: string; reason: string; question: string } {
@@ -792,6 +803,89 @@ export function auditClarifyNeed(
792
803
  return { needed: false, rule: '', reason: '', question: '' }
793
804
  }
794
805
 
806
+ /* ------------------------------------------------------------------------ */
807
+ /* [3.0.2] 澄清闸轮次上限:同一会话连问 CLARIFY_GATE_MAX_ROUNDS 轮后放行 */
808
+ /* ------------------------------------------------------------------------ */
809
+
810
+ /**
811
+ * [3.0.2] 同一会话最多向用户发起 CLARIFY_GATE_MAX_ROUNDS 轮澄清提问。
812
+ *
813
+ * 背景:澄清闸(runtime 规划前拦截 + validatePlanContext 的 CLARIFY 错误)
814
+ * 对判定永远成立的任务会无限「问一句→用户补一点→还是缺→再问一句」,
815
+ * 计划永远进不来。达到上限后,该会话后续 auditClarifyNeed 一律放行
816
+ * (needed:false),把任务交还规划路径,由规划器按 assumption 显式标注
817
+ * 推进,而不是把会话钉死在提问环里。
818
+ */
819
+ export const CLARIFY_GATE_MAX_ROUNDS = 2
820
+ /** 保守自愈:距上次触发超过 30 分钟视为新一轮会话目标,计数自动归零。 */
821
+ const CLARIFY_ROUNDS_TTL_MS = 30 * 60 * 1000
822
+ /** 调用方未提供 sessionId 时的共享计数键。 */
823
+ const DEFAULT_CLARIFY_SESSION = '__default__'
824
+
825
+ type ClarifyRoundEntry = { count: number; lastAt: number }
826
+ const clarifyRounds = new Map<string, ClarifyRoundEntry>()
827
+
828
+ /*
829
+ * 时钟可注入(测试用)。生产固定为 Date.now()。
830
+ * 说明:宿主 runtime 目前不传 sessionId(runtime.ts 归并行维护),因此
831
+ * 生产上所有会话共享默认键 + 30 分钟 TTL 自愈;若宿主侧能 hook 「会话
832
+ * 开始新规划」的时机,应调用 resetClarifyRounds(sessionId) 立即清零,
833
+ * 而不是等 30 分钟 TTL。
834
+ */
835
+ let clarifyGateClock: () => number = () => Date.now()
836
+
837
+ /** 测试专用:注入/恢复澄清闸时钟(不传参数则恢复真实时钟)。 */
838
+ export function __setClarifyGateClockForTests(clock?: () => number): void {
839
+ clarifyGateClock = clock ?? (() => Date.now())
840
+ }
841
+
842
+ /**
843
+ * 清空指定会话的澄清轮次计数。
844
+ *
845
+ * 意图调用时机:「会话开始新规划」的可感知点(新任务锚点落进规划器)。
846
+ * 当前宿主尚未 hook 该点(runtime.ts 不在本文件维护范围内),所以生产上
847
+ * 依赖 30 分钟 TTL 自愈;宿主一旦能感知规划起点,应调用本函数立即清零。
848
+ */
849
+ export function resetClarifyRounds(sessionId: string): void {
850
+ clarifyRounds.delete(String(sessionId ?? '').trim() || DEFAULT_CLARIFY_SESSION)
851
+ }
852
+
853
+ /**
854
+ * [3.0.2] 澄清判定对外唯一入口:规则判定 + 轮次上限。
855
+ *
856
+ * - 规则未命中(含空文本):纯透传,不计数;
857
+ * - 规则命中且轮次未达上限:计数 +1 并原样返回 needed:true;
858
+ * - 同一会话 30 分钟内已触发 CLARIFY_GATE_MAX_ROUNDS 轮:返回
859
+ * needed:false(放行进入规划),不再计数、不刷新时间戳——「被上限挡住」
860
+ * 不算一次触发,TTL 自上次真实提问起算。
861
+ */
862
+ export function auditClarifyNeed(
863
+ taskText: unknown,
864
+ conversationContext = '',
865
+ sessionId = '',
866
+ ): { needed: boolean; rule: string; reason: string; question: string } {
867
+ const verdict = auditClarifyNeedRules(taskText, conversationContext)
868
+ if (!verdict.needed) return verdict
869
+ const key = String(sessionId ?? '').trim() || DEFAULT_CLARIFY_SESSION
870
+ const now = clarifyGateClock()
871
+ let entry = clarifyRounds.get(key)
872
+ if (entry && now - entry.lastAt > CLARIFY_ROUNDS_TTL_MS) {
873
+ clarifyRounds.delete(key)
874
+ entry = undefined
875
+ }
876
+ if (entry && entry.count >= CLARIFY_GATE_MAX_ROUNDS) {
877
+ return { needed: false, rule: '', reason: '', question: '' }
878
+ }
879
+ clarifyRounds.set(key, { count: (entry?.count ?? 0) + 1, lastAt: now })
880
+ // 顺手清扫其他会话的过期条目,避免长进程里 Map 只增不减。
881
+ if (clarifyRounds.size > 16) {
882
+ for (const [otherKey, other] of clarifyRounds) {
883
+ if (now - other.lastAt > CLARIFY_ROUNDS_TTL_MS) clarifyRounds.delete(otherKey)
884
+ }
885
+ }
886
+ return verdict
887
+ }
888
+
795
889
  /**
796
890
  * Split one clause into candidate noun phrases.
797
891
  *
@@ -1381,7 +1475,7 @@ export function validatePlanContext(plan: any, context: PlanAuditContext = {}):
1381
1475
  * [P0-2c] Missing inputs must stop the plan before any department agent runs:
1382
1476
  * MS2 T05-04/09/13/20 were all planned and dispatched with the key input absent.
1383
1477
  */
1384
- const clarify = auditClarifyNeed(context.taskText ?? audit.anchor?.text ?? '', context.conversationContext ?? '')
1478
+ const clarify = auditClarifyNeed(context.taskText ?? audit.anchor?.text ?? '', context.conversationContext ?? '', context.sessionId ?? '')
1385
1479
  if (clarify.needed) {
1386
1480
  errors.push('CLARIFY: ' + clarify.reason + '(规则 ' + clarify.rule + ')')
1387
1481
  }
@@ -142,13 +142,30 @@ export const MIN_ATOMIC_TASK_CHARS = 8
142
142
  * 并列/多目标的强信号词。命中 1 个以上即视为「一个任务里塞了多件事」。
143
143
  * 只收强信号(明显的并列连词与小标题分隔),不收「和」这类高频虚词,
144
144
  * 避免把正常表述误判成多任务。
145
+ *
146
+ * [3.0.2] 补齐「并/然后/接着」:子 Agent 的任务书常写「改 A 并改 B」「先备份
147
+ * 然后上传」这类口语并列,旧词表全漏(英文盲区事故:英文句点 + 英文 then
148
+ * 都不在判据里,复合任务被当单句放行)。「并且」已含「并」,报错文案按
149
+ * 长词优先去重。
145
150
  */
146
151
  const MULTI_GOAL_MARKERS: readonly string[] = Object.freeze([
147
- '并且', '同时', '另外', '还要', '以及', '分别', '顺便',
152
+ '并且', '同时', '另外', '还要', '以及', '分别', '顺便', '并', '然后', '接着',
148
153
  ])
149
154
 
150
- /** 句末终止符:原子任务必须是单句。 */
151
- const SENTENCE_TERMINATORS: readonly RegExp[] = [new RegExp('[。!?!?]', 'g')]
155
+ /**
156
+ * [3.0.2] 「再」只在两个动作之间当连词时才算并列信号(「先备份再修改」)。
157
+ * 不再/再次/再三/再现/再也不/要再 等副词用法不算——「不要再等待」不会被误伤。
158
+ * 若后续实测「再」的误判率仍偏高,按用户裁决可仅保留 并/然后/接着 并删除
159
+ * 本规则。
160
+ */
161
+ const ZAI_CONJUNCTION_RE = /(?<![不未莫无勿别一要])再(?![次三现也])/
162
+
163
+ /**
164
+ * 句末终止符:原子任务必须是单句。
165
+ * [3.0.2] 英文句点 `.` 计入,但只认「后跟空白或文本结尾」的句读——文件名
166
+ * (a.ts)、版本号(1.12.0)、省略号(...)里的点不算句子分隔。
167
+ */
168
+ const SENTENCE_TERMINATORS: readonly RegExp[] = [new RegExp('[。!?!?]|\\.(?:\\s|$)', 'g')]
152
169
 
153
170
  export interface AtomicTaskCheck {
154
171
  ok: boolean
@@ -162,13 +179,15 @@ export interface AtomicTaskCheck {
162
179
  *
163
180
  * 判据全部可机械复算,不看语义:
164
181
  * 1) 非空且长度在 8–300 字符之间;
165
- * 2) 只有一句话(不出现第二个句末标点,不含分号分句);
166
- * 3) 不含并列强信号词(并且/同时/另外/还要/以及/分别/顺便);
182
+ * 2) 只有一句话(不出现第二个句末标点——含英文句点 `.`,不含分号分句);
183
+ * 3) 不含并列强信号词(并且/并/同时/另外/还要/以及/分别/顺便/然后/接着,
184
+ * 以及两动作之间的连词「再」);
167
185
  * 4) 必须带非空的质量要求(用户要求 6:交代清楚成果必须达到的要求和质量)。
168
186
  *
169
187
  * 返回的 hint 是可直接照做的拆小指令,不是一句「不合格」。
170
188
  */
171
189
  export function checkAtomicAssignment(task: string, qualityRequirements?: unknown): AtomicTaskCheck {
190
+ const rawLength = String(task ?? '').trim().length
172
191
  const text = String(task ?? '').replace(/\s+/g, ' ').trim()
173
192
  if (text.length < MIN_ATOMIC_TASK_CHARS) {
174
193
  return {
@@ -182,7 +201,9 @@ export function checkAtomicAssignment(task: string, qualityRequirements?: unknow
182
201
  return {
183
202
  ok: false,
184
203
  code: 'DELEGATE_TASK_NOT_ATOMIC',
185
- error: `分到的任务太长(${text.length} 字符 > ${MAX_ATOMIC_TASK_CHARS}),不是 1+1=2 的单项任务。`,
204
+ // [3.0.2] 如实报告截断后实际长度:调用方(llm-rules truncate(1500))先截断
205
+ // 再送检,这里的数字是被判定文本的真实长度,不是原始输入的长度。
206
+ error: `分到的任务太长(截断后实际 ${rawLength} 字符 > ${MAX_ATOMIC_TASK_CHARS}),不是 1+1=2 的单项任务。`,
186
207
  hint: '按「一个目标 / 一个主产物 / 一项可独立验收」拆成多条;每条只保留一个动作,其余另起一条。',
187
208
  }
188
209
  }
@@ -207,11 +228,14 @@ export function checkAtomicAssignment(task: string, qualityRequirements?: unknow
207
228
  }
208
229
  }
209
230
  const hit = MULTI_GOAL_MARKERS.filter((marker) => text.includes(marker))
210
- if (hit.length > 0) {
231
+ // 「并且」与「并」同命中时只报长词,报错文案不重复列同一个信号。
232
+ const markers = hit.filter((marker) => !hit.some((other) => other !== marker && other.includes(marker)))
233
+ if (ZAI_CONJUNCTION_RE.test(text)) markers.push('再')
234
+ if (markers.length > 0) {
211
235
  return {
212
236
  ok: false,
213
237
  code: 'DELEGATE_TASK_NOT_ATOMIC',
214
- error: `分到的任务含并列词「${hit.join('、')}」,说明一个任务里有多件事。`,
238
+ error: `分到的任务含并列词「${markers.join('、')}」,说明一个任务里有多件事。`,
215
239
  hint: '把并列词前后的内容各拆成一条独立任务,每条只做一个动作。',
216
240
  }
217
241
  }
@@ -232,6 +256,14 @@ export function checkAtomicAssignment(task: string, qualityRequirements?: unknow
232
256
 
233
257
  /** 单个汇报数组的条数上限:精简的量化口径。 */
234
258
  export const MAX_REPORT_ITEMS = 6
259
+ /**
260
+ * [3.0.6][第 3 批③] sources(部门汇总「覆盖的专家汇报」)专用上限。
261
+ * 死锁修复:复杂任务按用户裁决 D1/D2 强制 ≥8 名专家(上限 12),而 sources
262
+ * 必须覆盖全部已派发专家——若与其他数组共用 6 条上限,7–12 人的部门永远
263
+ * 交不出合法汇总(覆盖诚实要求 vs 精简上限互相矛盾)。覆盖是硬要求,
264
+ * 故 sources 单独放宽到 16(≥ 复杂任务 12 人上限 + 余量),其余数组仍 6 条。
265
+ */
266
+ export const MAX_SOURCES_ITEMS = 16
235
267
  /** 单条汇报文本的字符上限。 */
236
268
  export const MAX_REPORT_ITEM_CHARS = 200
237
269
 
@@ -328,7 +360,7 @@ function checkListField(
328
360
  container: Record<string, unknown>,
329
361
  name: string,
330
362
  violations: string[],
331
- options: { minItems: number; dedupeAcross?: readonly string[] },
363
+ options: { minItems: number; maxItems?: number; dedupeAcross?: readonly string[] },
332
364
  ): string[] {
333
365
  const raw = container[name]
334
366
  if (!Array.isArray(raw)) {
@@ -339,8 +371,9 @@ function checkListField(
339
371
  if (lines.length < options.minItems) {
340
372
  violations.push(`${name} 至少 ${options.minItems} 条非空内容,当前 ${lines.length} 条`)
341
373
  }
342
- if (lines.length > MAX_REPORT_ITEMS) {
343
- violations.push(`${name} 最多 ${MAX_REPORT_ITEMS} 条(精简要求),当前 ${lines.length} 条,请合并去重`)
374
+ const maxItems = options.maxItems ?? MAX_REPORT_ITEMS
375
+ if (lines.length > maxItems) {
376
+ violations.push(`${name} 最多 ${maxItems} 条(精简要求),当前 ${lines.length} 条,请合并去重`)
344
377
  }
345
378
  for (const line of lines) {
346
379
  if (line.length > MAX_REPORT_ITEM_CHARS) {
@@ -413,7 +446,7 @@ export function checkDepartmentSummary(summary: unknown, expectedExperts: readon
413
446
  checkListField(container, 'keyResults', violations, { minItems: 1, dedupeAcross: ['keyInfo', 'importantInfo'] })
414
447
  checkListField(container, 'keyInfo', violations, { minItems: 0, dedupeAcross: ['keyResults', 'importantInfo'] })
415
448
  checkListField(container, 'importantInfo', violations, { minItems: 0, dedupeAcross: ['keyResults', 'keyInfo'] })
416
- const covered = checkListField(container, 'sources', violations, { minItems: 0 })
449
+ const covered = checkListField(container, 'sources', violations, { minItems: 0, maxItems: MAX_SOURCES_ITEMS })
417
450
  if (expectedExperts.length > 0) {
418
451
  const joined = covered.join('\n').toLowerCase()
419
452
  const missing = expectedExperts.filter((member) => member.trim() !== '' && !joined.includes(member.trim().toLowerCase()))
@@ -458,7 +491,7 @@ export function renderDepartmentSummarySpec(): string {
458
491
  ' "sources": ["专家名:一句关键成果"]',
459
492
  ' }',
460
493
  ...DEPARTMENT_SUMMARY_FIELDS.map((field) => `- ${field.name}(${field.label}):${field.description}`),
461
- `- 每个数组最多 ${MAX_REPORT_ITEMS} 条、每条最多 ${MAX_REPORT_ITEM_CHARS} 字符;sources 必须覆盖本部门全部已派发专家,同一信息只能出现一次。`,
494
+ `- keyResults/keyInfo/importantInfo 每个数组最多 ${MAX_REPORT_ITEMS} 条、每条最多 ${MAX_REPORT_ITEM_CHARS} 字符;sources 最多 ${MAX_SOURCES_ITEMS} 条(不受 6 条精简上限约束——必须逐人覆盖本部门全部已派发专家,覆盖是诚实硬要求),同一信息只能出现一次。`,
462
495
  '- 门禁:缺 departmentSummary、字段缺失、未覆盖全部专家、或出现重复项,结果一律退回重交(DEPARTMENT_SUMMARY_INVALID / DEPARTMENT_SUMMARY_NOT_CONCISE)。',
463
496
  ].join('\n')
464
497
  }