dsh-workplan 2.0.4 → 2.1.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.
@@ -0,0 +1,215 @@
1
+ /**
2
+ * [2.1.0] 统一沟通交流格式规范与合规检查(用户 2026-11-06 的强制要求)。
3
+ *
4
+ * 机制闭环:
5
+ * 1. 主 Agent 派发子任务时,在提示词里附带本模块渲染的《沟通交流格式规范》
6
+ * (renderCommFormatSpec),作为双方认可的唯一结果格式契约;
7
+ * 2. 部门人员提交结果前,必须逐条对照规范自查(提示词中有强制自查指令);
8
+ * 3. 主 Agent 收到结果后,由 adjudicateResult 用 checkCommFormatCompliance
9
+ * 按同一份规范逐条核验;不合规即判定 blocked/comm-format,把
10
+ * renderCommFormatRejection 生成的退回通知随下一次激活发回,
11
+ * 通知部门人员重新检查格式后重交。
12
+ *
13
+ * 设计约束:
14
+ * - 本模块只做「格式/结构」核验,不做语义真伪判断(F9 为提示词级诚信约束,
15
+ * 由三阶段门禁与人工复核兜底,这里不自动判);
16
+ * - 规范是纯数据,可序列化进提示词,也可独立校验,版本号随内容变更递增;
17
+ * - 与既有门禁正交:解析失败、验收缺口、三阶段缺失仍由原门禁先拦,
18
+ * 本门禁只负责把「其它门禁都过了、但格式仍不合规」的 done 退回。
19
+ */
20
+
21
+ /** 格式规范版本,随规范内容变更递增。 */
22
+ export const COMM_FORMAT_VERSION = 1
23
+
24
+ /** 单条不合规项。 */
25
+ export interface CommFormatViolation {
26
+ /** 规范条目编号(F1-F9)。 */
27
+ ruleId: string
28
+ /** 不合规的具体描述(写清缺什么、怎么补)。 */
29
+ message: string
30
+ /** 条目分类(structure/phases/acceptance/artifacts/retrospective/blocked/integrity)。 */
31
+ category: string
32
+ }
33
+
34
+ /** 格式合规检查结果。 */
35
+ export interface CommFormatCheckResult {
36
+ /** 是否全部合规。 */
37
+ compliant: boolean
38
+ /** 不合规项列表(合规时为空)。 */
39
+ violations: CommFormatViolation[]
40
+ /** 核验所用的规范版本。 */
41
+ version: number
42
+ }
43
+
44
+ /**
45
+ * 统一沟通交流格式规范定义(F1-F9,冻结不可变)。
46
+ */
47
+ export const COMM_FORMAT_SPEC = Object.freeze({
48
+ version: COMM_FORMAT_VERSION,
49
+ name: 'dsh-workplan 沟通交流格式规范',
50
+ requirements: Object.freeze([
51
+ Object.freeze({ id: 'F1', category: 'structure',
52
+ description: '结果必须包含结构化证据块:以 <!-- WORKPLAN_EVIDENCE:START --> 开头、<!-- WORKPLAN_EVIDENCE:END --> 结尾,且两块标记成对出现',
53
+ rationale: '没有标记块,主 Agent 无法定位与解析结果,交付门禁无从启动' }),
54
+ Object.freeze({ id: 'F2', category: 'structure',
55
+ description: '证据块必须是合法 JSON 对象,顶层必须含 status 字段,取值只能是 done / blocked / partial',
56
+ rationale: 'status 是交付门禁的入口条件,缺失或非法则无法判定完成与否' }),
57
+ Object.freeze({ id: 'F3', category: 'phases',
58
+ description: '必须包含三阶段证据:phases.planning(问题分析与可执行思路)、phases.execution(实际执行步骤)、phases.verification(逐项验证)',
59
+ rationale: '三阶段是质量闭环的基础,缺任一阶段等于跳过对应质控环节' }),
60
+ Object.freeze({ id: 'F4', category: 'acceptance',
61
+ description: '验收结果必须逐条回应计划的验收标准(A1、A2…),且每条 result=pass 必须附带具体证据(命令输出/文件路径/引用),禁止空证据 pass',
62
+ rationale: '空证据 pass 是自述而非验证,交付门禁只认可证据' }),
63
+ Object.freeze({ id: 'F5', category: 'acceptance',
64
+ description: '验收回应的条数不得少于计划定义的验收标准条数',
65
+ rationale: '少回应一条等于该条验收未做,交付门禁会判为未完成' }),
66
+ Object.freeze({ id: 'F6', category: 'artifacts',
67
+ description: 'artifacts 声明清单中每一项都必须是合法条目:kind 只能取 file / url / note,且 ref 非空;不允许空条目或占位条目',
68
+ rationale: '主 Agent 按 ref 核验交付物;非法条目让核验无从执行。是否必须交付文件由计划验收标准决定,不由本条决定' }),
69
+ Object.freeze({ id: 'F7', category: 'retrospective',
70
+ description: 'phases.verification.retrospective 复盘必须完整:problems、resolutions、prevention 均至少 1 条(detours 没有可写空数组)',
71
+ rationale: '复盘是自我学习闭环的入口,缺失则教训无法写入永久记忆' }),
72
+ Object.freeze({ id: 'F8', category: 'blocked',
73
+ description: '若 status 为 blocked,必须附非空 question 字段写清受阻原因(卡在哪一步、已尝试什么、需要谁决定什么)',
74
+ rationale: '受阻无原因等于主 Agent 不知道卡在哪里,无法给出指示或转派' }),
75
+ Object.freeze({ id: 'F9', category: 'integrity',
76
+ description: '不得编造、虚构或伪造任何证据、文件路径、命令输出或验收结果;无法确认的项目必须写 unverified',
77
+ rationale: '虚假证据一旦通过交付门禁,用户拿到的就是不可信的成品' }),
78
+ ]),
79
+ })
80
+
81
+ /**
82
+ * 对子 Agent 的证据块执行沟通交流格式合规检查(F1-F8 自动核验;F9 为诚信约束不自动判)。
83
+ *
84
+ * @param parsed - 已解析的证据块 payload(parseEvidenceBlock 的 payload,可为 null)
85
+ * @param rawOutput - 子 Agent 原始输出全文
86
+ * @param expectedAcceptanceCount - 计划定义的验收标准条数
87
+ */
88
+ export function checkCommFormatCompliance(
89
+ parsed: any,
90
+ rawOutput: string,
91
+ expectedAcceptanceCount: number,
92
+ ): CommFormatCheckResult {
93
+ const violations: CommFormatViolation[] = []
94
+ const text = typeof rawOutput === 'string' ? rawOutput : ''
95
+
96
+ // F1: 证据块标记必须成对出现(rescueEvidence 捞到的豁免——主 Agent 已能解析)
97
+ if (!text.includes('WORKPLAN_EVIDENCE:START') || !text.includes('WORKPLAN_EVIDENCE:END')) {
98
+ if (!parsed) {
99
+ violations.push({ ruleId: 'F1', category: 'structure',
100
+ message: '缺少 WORKPLAN_EVIDENCE:START/END 标记块,主 Agent 无法定位与解析结果' })
101
+ }
102
+ }
103
+
104
+ if (!parsed || typeof parsed !== 'object') {
105
+ if (violations.length === 0) {
106
+ violations.push({ ruleId: 'F2', category: 'structure', message: '证据块无法解析为 JSON 对象' })
107
+ }
108
+ return { compliant: false, violations, version: COMM_FORMAT_VERSION }
109
+ }
110
+
111
+ // F2: status 必填且取值合法
112
+ if (!['done', 'blocked', 'partial'].includes(String(parsed.status ?? ''))) {
113
+ violations.push({ ruleId: 'F2', category: 'structure',
114
+ message: `status 字段缺失或取值非法("${String(parsed.status ?? '')}"),只能是 done / blocked / partial` })
115
+ }
116
+
117
+ // F3: 三阶段证据齐全
118
+ const phases = parsed.phases
119
+ if (!phases || typeof phases !== 'object') {
120
+ violations.push({ ruleId: 'F3', category: 'phases',
121
+ message: '缺少 phases 对象:planning / execution / verification 三阶段证据全部缺失' })
122
+ } else {
123
+ const missing: string[] = []
124
+ if (!phases.planning || typeof phases.planning !== 'object') missing.push('planning(问题分析与思路)')
125
+ if (!phases.execution || typeof phases.execution !== 'object') missing.push('execution(实际执行步骤)')
126
+ if (!phases.verification || typeof phases.verification !== 'object') missing.push('verification(逐项验证与复盘)')
127
+ if (missing.length > 0) {
128
+ violations.push({ ruleId: 'F3', category: 'phases', message: `三阶段证据缺失:${missing.join('、')}` })
129
+ }
130
+ }
131
+
132
+ // F4: pass 必须带证据
133
+ const acceptance = Array.isArray(parsed.acceptance) ? parsed.acceptance : []
134
+ const emptyPass: string[] = []
135
+ for (const item of acceptance) {
136
+ if (item && item.result === 'pass' && !String(item.evidence ?? '').trim()) {
137
+ emptyPass.push(String(item.criterion ?? '(未命名验收项)'))
138
+ }
139
+ }
140
+ if (emptyPass.length > 0) {
141
+ violations.push({ ruleId: 'F4', category: 'acceptance',
142
+ message: `以下验收项 result=pass 但未附证据:${emptyPass.slice(0, 5).join('、')};pass 必须附命令输出/文件路径/引用` })
143
+ }
144
+
145
+ // F5: 验收条数不得少于计划定义
146
+ if (expectedAcceptanceCount > 0 && acceptance.length < expectedAcceptanceCount) {
147
+ violations.push({ ruleId: 'F5', category: 'acceptance',
148
+ message: `验收回应仅 ${acceptance.length} 条,少于计划定义的 ${expectedAcceptanceCount} 条;须逐条回应 A1、A2…` })
149
+ }
150
+
151
+ // F6: 产物声明必须逐条合法(kind 枚举 + ref 非空);是否必须交付文件由计划验收决定,不在此拦
152
+ const artifacts = Array.isArray(parsed.artifacts) ? parsed.artifacts : []
153
+ const badArtifacts = artifacts.filter((item: any) =>
154
+ !item || typeof item !== 'object'
155
+ || !['file', 'url', 'note'].includes(String(item.kind ?? ''))
156
+ || String(item.ref ?? '').trim() === '')
157
+ if (badArtifacts.length > 0) {
158
+ violations.push({ ruleId: 'F6', category: 'artifacts',
159
+ message: `artifacts 有 ${badArtifacts.length} 条非法声明:每条必须 kind 取 file/url/note 且 ref 非空,不允许空条目` })
160
+ }
161
+
162
+ // F7: 复盘完整(problems/resolutions/prevention 均至少 1 条)
163
+ const retro = phases?.verification?.retrospective
164
+ if (!retro || typeof retro !== 'object') {
165
+ violations.push({ ruleId: 'F7', category: 'retrospective',
166
+ message: '缺少 phases.verification.retrospective 复盘(problems / detours / resolutions / prevention)' })
167
+ } else {
168
+ const missingRetro: string[] = []
169
+ if (!Array.isArray(retro.problems) || retro.problems.length === 0) missingRetro.push( 'problems(遇到的问题,现象+根因)')
170
+ if (!Array.isArray(retro.resolutions) || retro.resolutions.length === 0) missingRetro.push( 'resolutions(最终如何解决)')
171
+ if (!Array.isArray(retro.prevention) || retro.prevention.length === 0) missingRetro.push( 'prevention(防再犯规则)')
172
+ if (missingRetro.length > 0) {
173
+ violations.push({ ruleId: 'F7', category: 'retrospective',
174
+ message: `复盘不完整,缺少:${missingRetro.join('、')},均至少 1 条` })
175
+ }
176
+ }
177
+
178
+ // F8: blocked 必须附非空 question
179
+ if (parsed.status === 'blocked' && !String(parsed.question ?? '').trim()) {
180
+ violations.push({ ruleId: 'F8', category: 'blocked',
181
+ message: 'status 为 blocked 但 question 为空:须写清卡在哪一步、已尝试什么、需要谁做什么决定' })
182
+ }
183
+
184
+ return { compliant: violations.length === 0, violations, version: COMM_FORMAT_VERSION }
185
+ }
186
+
187
+ /**
188
+ * 把格式规范渲染为嵌入子 Agent 提示词的文本。
189
+ * 这是「派发工作时附带统一沟通交流格式要求」的具体实现。
190
+ */
191
+ export function renderCommFormatSpec(): string {
192
+ const lines: string[] = [
193
+ '沟通交流格式规范(v' + String(COMM_FORMAT_VERSION) + ',主 Agent 与部门人员双方认可的结果格式契约):',
194
+ ]
195
+ for (const req of COMM_FORMAT_SPEC.requirements) {
196
+ lines.push(`- 【${req.id}】${req.description}`)
197
+ }
198
+ lines.push('不合规的后果:主 Agent 收到结果后按本规范逐条核验;任一不合规,结果立刻退回,你将收到列明不合规条目的退回通知,须全部修正后重新提交完整结果。')
199
+ return lines.join('\n')
200
+ }
201
+
202
+ /**
203
+ * 把合规检查结果渲染为退回通知文本(随下一次激活发回部门人员)。
204
+ */
205
+ export function renderCommFormatRejection(result: CommFormatCheckResult): string {
206
+ if (result.compliant) return ''
207
+ const lines: string[] = [
208
+ '结果退回:沟通交流格式不合规(规范 v' + String(result.version) + ')。',
209
+ '你的结果未通过以下条目,请逐条修正、重新自查全部 F1-F9 后再提交完整结果(不要只修一条就重交):',
210
+ ]
211
+ for (const v of result.violations) {
212
+ lines.push(`- ${v.ruleId}:${v.message}`)
213
+ }
214
+ return lines.join('\n')
215
+ }
package/src/host.ts CHANGED
@@ -1490,7 +1490,7 @@ export function apply(ctx: any, config: WorkplanConfig = {}) {
1490
1490
 
1491
1491
  export const meta = {
1492
1492
  name,
1493
- version: '2.0.4',
1493
+ version: '2.1.1',
1494
1494
  promptOrder: PROMPT_ORDER,
1495
1495
  routes: ['/dsh-workplan/plans', '/dsh-workplan/vendor/chart.umd.js'],
1496
1496
  }
package/src/plan.ts CHANGED
@@ -13,6 +13,11 @@ import { DEPARTMENT_CAPABILITIES, departmentCapability } from './departments.js'
13
13
  import { MAX_TASK_ANCHOR_CHARS } from './understanding.js'
14
14
  import { isMappingDigest, verifyMappingDigest } from './supersede-digest.js'
15
15
  import { phaseSummaryLine, threePhasePromptLines, validatePhaseEvidence } from './three-phase.js'
16
+ import {
17
+ checkCommFormatCompliance,
18
+ renderCommFormatRejection,
19
+ renderCommFormatSpec,
20
+ } from './comm-format.js'
16
21
 
17
22
  export const PLAN_VERSION = 1
18
23
 
@@ -137,7 +142,7 @@ export const CLOSURES = Object.freeze([
137
142
  'replanned',
138
143
  ])
139
144
  /** Why a `blocked` / `escalated` row stopped. Read by the dashboard and result message. */
140
- export const BLOCKED_KINDS = Object.freeze(['failed', 'timeout', 'no-ack', 'escalated'])
145
+ export const BLOCKED_KINDS = Object.freeze(['failed', 'timeout', 'no-ack', 'escalated', 'comm-format'])
141
146
  /**
142
147
  * [1.11.0] 合法闭环迁移(T4 §4 的 19 条,M1)。
143
148
  *
@@ -913,6 +918,119 @@ export function flattenSubtasks(plan: any): Array<{ stage: any; subtask: any }>
913
918
  return out
914
919
  }
915
920
 
921
+ /**
922
+ * [2.1.0] 只补结构、不补内容。
923
+ *
924
+ * 规划器返回的 JSON 常见三类损伤:少一个 `}`、多一个尾逗号、字符串里有裸换行。
925
+ * 旧实现直接 JSON.parse,一个字符之差就抛 INVALID_JSON,整个计划降级。
926
+ * 这里做的是纯结构修复:配对括号、去掉尾逗号、把字符串里的裸控制符转义。
927
+ * 绝不猜测、绝不编造任何字段或值——修不好就照旧抛错。
928
+ */
929
+ export function repairJsonStructure(input: string): string {
930
+ const stack: string[] = []
931
+ let inString = false
932
+ let escaped = false
933
+ let out = ''
934
+ for (let i = 0; i < input.length; i += 1) {
935
+ const ch = input[i] as string
936
+ if (inString) {
937
+ if (escaped) {
938
+ out += ch
939
+ escaped = false
940
+ continue
941
+ }
942
+ if (ch === '\\') {
943
+ out += ch
944
+ escaped = true
945
+ continue
946
+ }
947
+ if (ch === '"') {
948
+ inString = false
949
+ out += ch
950
+ continue
951
+ }
952
+ if (ch === '\n') {
953
+ out += '\\n'
954
+ continue
955
+ }
956
+ if (ch === '\r') {
957
+ out += '\\r'
958
+ continue
959
+ }
960
+ if (ch === '\t') {
961
+ out += '\\t'
962
+ continue
963
+ }
964
+ if (ch < ' ') {
965
+ out += `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`
966
+ continue
967
+ }
968
+ out += ch
969
+ continue
970
+ }
971
+ if (ch === '"') {
972
+ inString = true
973
+ out += ch
974
+ continue
975
+ }
976
+ if (ch === '{' || ch === '[') {
977
+ stack.push(ch)
978
+ out += ch
979
+ continue
980
+ }
981
+ if (ch === '}' || ch === ']') {
982
+ const want = ch === '}' ? '{' : '['
983
+ while (stack.length > 0 && stack[stack.length - 1] !== want) {
984
+ out += stack.pop() === '{' ? '}' : ']'
985
+ }
986
+ if (stack.length > 0) stack.pop()
987
+ out += ch
988
+ continue
989
+ }
990
+ out += ch
991
+ }
992
+ if (inString) out += '"'
993
+ while (stack.length > 0) out += stack.pop() === '{' ? '}' : ']'
994
+ return stripTrailingCommas(out)
995
+ }
996
+
997
+ function stripTrailingCommas(input: string): string {
998
+ return input.replace(/,(\s*[}\]])/g, '$1')
999
+ }
1000
+
1001
+ /** 找到最后一个「成员边界」逗号(在任何嵌套深度上、且不在字符串内)。 */
1002
+ function lastMemberComma(input: string): number {
1003
+ let inString = false
1004
+ let escaped = false
1005
+ let index = -1
1006
+ for (let i = 0; i < input.length; i += 1) {
1007
+ const ch = input[i] as string
1008
+ if (inString) {
1009
+ if (escaped) escaped = false
1010
+ else if (ch === '\\') escaped = true
1011
+ else if (ch === '"') inString = false
1012
+ continue
1013
+ }
1014
+ if (ch === '"') inString = true
1015
+ else if (ch === ',') index = i
1016
+ }
1017
+ return index
1018
+ }
1019
+
1020
+ /**
1021
+ * 截断修复:规划器被 max tokens 截断时,最后一个成员通常是半截的。
1022
+ * 从尾部逐个丢弃不完整成员,再补齐括号——丢掉的都是「本来就残缺、不能用」的内容。
1023
+ */
1024
+ function* truncatedCandidates(input: string, rounds = 24): Generator<string> {
1025
+ let working = input
1026
+ for (let round = 0; round < rounds; round += 1) {
1027
+ const cut = lastMemberComma(working)
1028
+ if (cut <= 0) return
1029
+ working = working.slice(0, cut)
1030
+ yield repairJsonStructure(working)
1031
+ }
1032
+ }
1033
+
916
1034
  export function extractJson(text: any) {
917
1035
  if (typeof text !== 'string' || text.trim() === '') {
918
1036
  throw new PlanError('规划器没有返回内容', 'EMPTY_OUTPUT')
@@ -921,14 +1039,32 @@ export function extractJson(text: any) {
921
1039
  const fenced = value.match(/```(?:json)?\s*([\s\S]*?)```/i)
922
1040
  if (fenced) value = fenced[1].trim()
923
1041
  const first = value.indexOf('{')
924
- const last = value.lastIndexOf('}')
925
- if (first < 0 || last <= first) {
1042
+ if (first < 0) {
926
1043
  throw new PlanError('规划器返回内容中没有 JSON 对象', 'NO_JSON')
927
1044
  }
928
- const candidate = value.slice(first, last + 1)
1045
+ const last = value.lastIndexOf('}')
1046
+ // [2.1.0] 输出被截断时没有结尾 `}`,旧实现这里直接判 NO_JSON —— 改成仍以 `{` 起头做修复。
1047
+ const candidate = last > first ? value.slice(first, last + 1) : value.slice(first)
1048
+
929
1049
  try {
930
1050
  return JSON.parse(candidate)
931
1051
  } catch (error) {
1052
+ const repaired = repairJsonStructure(candidate)
1053
+ try {
1054
+ const value2 = JSON.parse(repaired)
1055
+ console.warn('[dsh-workplan] 规划器 JSON 结构已修复(只补括号/逗号,未改内容)')
1056
+ return value2
1057
+ } catch {
1058
+ for (const attempt of truncatedCandidates(repaired)) {
1059
+ try {
1060
+ const value3 = JSON.parse(attempt)
1061
+ console.warn('[dsh-workplan] 规划器 JSON 被截断,已丢弃末尾残缺成员后解析成功')
1062
+ return value3
1063
+ } catch {
1064
+ continue
1065
+ }
1066
+ }
1067
+ }
932
1068
  throw new PlanError(`规划器返回的 JSON 无法解析:${error instanceof Error ? error.message : String(error)}`, 'INVALID_JSON')
933
1069
  }
934
1070
  }
@@ -1982,6 +2118,46 @@ function readEvidenceOptions(value: any) {
1982
2118
  .filter(Boolean)
1983
2119
  }
1984
2120
 
2121
+ /**
2122
+ * [2.1.0] 顶层证据字段被误写进 `phases` 时,把它们提回顶层(用户 2026-11-05)。
2123
+ *
2124
+ * 事故(子会话 13b45af6 原文复核):子 Agent 的回执像这样——
2125
+ * {"status":"done","phases":{"planning":{…},"execution":{…},"verification":{…},
2126
+ * "acceptance":[…4 条…],"artifacts":[…]}}
2127
+ * 少了一个 `}`,于是 acceptance/artifacts 全部落进 `phases`。`closeOpenJson`
2128
+ * 在末尾补一个 `}` 后 JSON 合法,`readEvidenceAcceptance(payload.acceptance)`
2129
+ * 读到空数组,最终判成「验收项未被逐条回应(0/4)」——证据一条不缺,却被
2130
+ * 说成「没做验收」,且把责任推回子 Agent。这不是证据问题,是层级错位。
2131
+ *
2132
+ * 这里只做**位置归位**:字段名与值原样搬回顶层,不改内容、不补内容;顶层
2133
+ * 已有非空值时不覆盖(避免把真值盖掉)。归位后仍走完整门禁。
2134
+ */
2135
+ const HOISTABLE_EVIDENCE_KEYS = ['acceptance', 'artifacts', 'needs', 'question', 'options'] as const
2136
+
2137
+ export function hoistEvidenceFields(payload: any) {
2138
+ if (!isRecord(payload) || !isRecord(payload.phases)) return { payload, hoisted: [] as string[] }
2139
+ const phases: any = payload.phases
2140
+ const next: any = { ...payload, phases: { ...phases } }
2141
+ const hoisted: string[] = []
2142
+ for (const key of HOISTABLE_EVIDENCE_KEYS) {
2143
+ const top = next[key]
2144
+ const topEmpty = top === undefined || top === null
2145
+ || (Array.isArray(top) && top.length === 0)
2146
+ || (typeof top === 'string' && top.trim() === '')
2147
+ if (!topEmpty) continue
2148
+ if (!(key in phases)) continue
2149
+ const value = phases[key]
2150
+ const hasValue = Array.isArray(value)
2151
+ ? value.length > 0
2152
+ : typeof value === 'string' ? value.trim() !== '' : false
2153
+ if (!hasValue) continue
2154
+ next[key] = value
2155
+ delete (next.phases as any)[key]
2156
+ hoisted.push(key)
2157
+ }
2158
+ return hoisted.length > 0 ? { payload: next, hoisted } : { payload, hoisted }
2159
+ }
2160
+
1985
2161
  /**
1986
2162
  * Parse the child's structured evidence block.
1987
2163
  *
@@ -2080,7 +2256,7 @@ export function repairEvidenceJson(text: string): any {
2080
2256
  * 这里做的是**有界认领**:只认带 `status` 且至少还有一个证据字段的 JSON
2081
2257
  * 对象,绝不把任意 JSON(比如计划载荷、配置片段)当成回执。
2082
2258
  */
2083
- export function rescueEvidenceFromFence(output: any): any {
2259
+ function rescueEvidence(output: any): { payload: any; raw: string; repaired: boolean } | null {
2084
2260
  const text = typeof output === 'string' ? output : ''
2085
2261
  if (!text.includes('{')) return null
2086
2262
  const candidates: string[] = []
@@ -2091,29 +2267,45 @@ export function rescueEvidenceFromFence(output: any): any {
2091
2267
  const last = text.lastIndexOf('}')
2092
2268
  if (first >= 0 && last > first) candidates.push(text.slice(first, last + 1))
2093
2269
  for (const candidate of candidates) {
2270
+ const body = String(candidate).trim()
2094
2271
  let value: any = null
2272
+ let repaired = false
2095
2273
  try {
2096
- value = JSON.parse(String(candidate).trim())
2274
+ value = JSON.parse(body)
2097
2275
  } catch {
2098
- value = repairEvidenceJson(String(candidate).trim())
2276
+ value = repairEvidenceJson(body)
2277
+ repaired = value !== null
2099
2278
  }
2100
2279
  if (!isRecord(value)) continue
2101
2280
  if (!EVIDENCE_STATUSES.includes(value.status)) continue
2102
2281
  const hasEvidence = Array.isArray(value.acceptance) || Array.isArray(value.artifacts)
2103
2282
  || Array.isArray(value.needs) || isRecord(value.phases) || typeof value.summary === 'string'
2104
2283
  if (!hasEvidence) continue
2105
- return value
2284
+ return { payload: value, raw: body, repaired }
2106
2285
  }
2107
2286
  return null
2108
2287
  }
2109
2288
 
2289
+ export function rescueEvidenceFromFence(output: any): any {
2290
+ const rescued = rescueEvidence(output)
2291
+ return rescued ? rescued.payload : null
2292
+ }
2293
+
2110
2294
  export function parseEvidenceBlock(output: any) {
2111
2295
  const text = typeof output === 'string' ? output : ''
2112
2296
  const begin = text.lastIndexOf(EVIDENCE_MARKER_BEGIN)
2113
2297
  if (begin < 0) {
2114
- const rescued = rescueEvidenceFromFence(text)
2298
+ const rescued = rescueEvidence(text)
2115
2299
  if (rescued) {
2116
- return { found: true, malformed: false, truncated: false, repaired: false, rescued: true, payload: rescued, raw: '' }
2300
+ return {
2301
+ found: true,
2302
+ malformed: false,
2303
+ truncated: false,
2304
+ repaired: rescued.repaired,
2305
+ rescued: true,
2306
+ payload: rescued.payload,
2307
+ raw: rescued.raw,
2308
+ }
2117
2309
  }
2118
2310
  return { found: false, malformed: false, truncated: false, repaired: false, rescued: false, payload: null, raw: '' }
2119
2311
  }
@@ -2218,7 +2410,8 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2218
2410
  error: '子 Agent 未提供结构化证据块(完成必回报):结果块缺失,无法确认验收项是否真的通过',
2219
2411
  }
2220
2412
  }
2221
- const payload: any = parsed.payload
2413
+ const hoistedEvidence = hoistEvidenceFields(parsed.payload)
2414
+ const payload: any = hoistedEvidence.payload
2222
2415
  const acceptance = readEvidenceAcceptance(payload.acceptance)
2223
2416
  const artifacts = readEvidenceArtifacts(payload.artifacts)
2224
2417
  const needs = readEvidenceNeeds(payload.needs)
@@ -2293,6 +2486,19 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2293
2486
  */
2294
2487
  const coverage = acceptanceCoverage(expectedAcceptance, acceptance)
2295
2488
  if (coverage.total > 0 && coverage.missing.length > 0) {
2489
+ /*
2490
+ * [2.1.0] 先把「为什么没读到」说清楚,再要求补证据。
2491
+ *
2492
+ * 旧文案只有一句「验收项未被逐条回应」,于是「真没回」「层级写错」
2493
+ * 「被截断」三种完全不同的原因长得一模一样,主 Agent 只能反复重派。
2494
+ */
2495
+ const rawText = String(parsed.raw ?? '')
2496
+ const rawHasAcceptance = /"acceptance"\s*:/.test(rawText)
2497
+ const hint = acceptance.length === 0 && rawHasAcceptance
2498
+ ? '(原始结果块里确实写了 acceptance,但没有落在顶层:通常是 phases 少一个 } 导致层级错位,已尝试自动归位仍未读到)'
2499
+ : parsed.repaired
2500
+ ? '(结果块 JSON 有语法错误,已修复;若 acceptance 位于错误点之后,会被一起裁掉)'
2501
+ : ''
2296
2502
  return {
2297
2503
  status: 'blocked',
2298
2504
  verification: 'unverified',
@@ -2300,7 +2506,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2300
2506
  artifacts,
2301
2507
  needs,
2302
2508
  error: `验收项未被逐条回应(${coverage.covered}/${coverage.total}):缺少 ${coverage.missing
2303
- .map((item: string) => truncate(String(item), 120)).slice(0, 5).join(';')}。请按计划验收逐条给出证据后再回报。`,
2509
+ .map((item: string) => truncate(String(item), 120)).slice(0, 5).join(';')}${hint}。请按计划验收逐条给出证据后再回报。`,
2304
2510
  }
2305
2511
  }
2306
2512
  /*
@@ -2327,6 +2533,46 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2327
2533
  phases: null,
2328
2534
  }
2329
2535
  }
2536
+ /*
2537
+ * [2.1.0] 沟通交流格式门禁(用户 2026-11-06 的强制要求,契约见
2538
+ * `src/comm-format.ts`)。
2539
+ *
2540
+ * 主 Agent 派发任务时随提示词附带《沟通交流格式规范》(renderCommFormatSpec),
2541
+ * 部门人员提交前须逐条自查;这里按同一份规范对「其它门禁都已通过、
2542
+ * 即将判 done」的结果做最终核验:任一不合规即退回(blocked/comm-format),
2543
+ * 不合规条目随下一次激活的 previousFailure 发回,通知其重新自查后重交。
2544
+ *
2545
+ * 只拦 done 路径:解析失败、验收缺口、三阶段缺失等已被上方门禁拦下的结果,
2546
+ * 维持原受阻原因,不用格式条目覆盖更有针对性的诊断。
2547
+ */
2548
+ const commFormat = requirePhases === false
2549
+ /*
2550
+ * [2.1.0] 兼容边界:`requirePhases:false` 是「历史回放 / 明确关闭新契约」
2551
+ * 的既有开关(1.13.0 语义)。格式契约只对实时执行生效,不得追溯否决
2552
+ * 旧会话日志里按当时规则合法的 done。
2553
+ */
2554
+ ? { compliant: true as const, violations: [], version: 0 }
2555
+ : checkCommFormatCompliance(
2556
+ payload,
2557
+ text,
2558
+ Array.isArray(expectedAcceptance) ? expectedAcceptance.length : 0,
2559
+ )
2560
+ if (!commFormat.compliant) {
2561
+ return {
2562
+ status: 'blocked',
2563
+ verification: 'unverified',
2564
+ acceptance,
2565
+ artifacts,
2566
+ needs,
2567
+ error: `沟通交流格式不合规,结果已退回重交:${commFormat.violations
2568
+ .map((v) => `${v.ruleId} ${v.message}`)
2569
+ .slice(0, 6)
2570
+ .join(';')}`,
2571
+ blockedKind: 'comm-format',
2572
+ commFormatViolations: commFormat.violations,
2573
+ commFormatRejection: renderCommFormatRejection(commFormat),
2574
+ }
2575
+ }
2330
2576
  return {
2331
2577
  status: 'done',
2332
2578
  verification: hasUnverified ? 'unverified' : 'structured',
@@ -4098,5 +4344,16 @@ export function buildChildPrompt({
4098
4344
  '- needs 写需要其他部门配合的事项,每条写清「哪个部门 + 需要什么 + 用来做什么」;它会被登记为待处理需求,主 Agent 必须处置后计划才能交付。不要直连其他子 Agent。',
4099
4345
  '- question/options 只在受阻上报时填写;done 时保持空字符串/空数组。',
4100
4346
  '- 整块不超过 12000 字符;不要把这段模板本身抄进结果块。',
4347
+ '',
4348
+ /*
4349
+ * [2.1.0] 派发工作时附带统一沟通交流格式要求(用户 2026-11-06 的强制要求)。
4350
+ *
4351
+ * 规范文本与主 Agent 核验结果用的是同一份数据(src/comm-format.ts),
4352
+ * 「附带的要求」与「核验的尺子」由此不可能长成两个版本。
4353
+ */
4354
+ renderCommFormatSpec(),
4355
+ '提交前自查(强制):逐条对照上面《沟通交流格式规范》F1–F9,确认全部满足后再提交;'
4356
+ + '主 Agent 收到结果后按同一份规范逐条核验,任一不合规即立刻退回,你会收到列明不合规条目的退回通知,'
4357
+ + '须逐条修正、重新自查通过后再重新提交完整结果。',
4101
4358
  ].join('\n'))
4102
4359
  }