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.
@@ -0,0 +1,251 @@
1
+ /**
2
+ * [3.0.6][第 3 批②] dsh-workplan 专用通知台账(notice ledger)。
3
+ *
4
+ * 审计病根:插件通知唯一的持久可见通道是 user/message,与用户真实输入混在同
5
+ * 一条事件流里(source.kind 虽可区分,但没有任何插件侧权威台账可供工具/前端
6
+ * 直接消费)。
7
+ *
8
+ * 官方约束(dsh-agent-preset/skills/dsh-doc/references/practices.md:21):
9
+ * 1. 禁止给 Session 新增自定义事件类型——live Session.append 无法打
10
+ * ignorable 标记,重启后 Session 会拒绝重新打开;
11
+ * 2. appendPluginRecord() 保留给 DSH 实验包,本插件不得使用;
12
+ * 3. 插件自有数据应放在插件自己的存储里。
13
+ *
14
+ * 因此 v1 专用通道 = 插件自有 JSONL 台账(默认 ~/.dsh/workplan/notices.jsonl,
15
+ * 可用 DSH_WORKPLAN_NOTICES_FILE 覆盖):
16
+ * - appendUserMessage 每次成功落盘一条 workplan 通知后,同步追加一行台账;
17
+ * - 台账行自带 sessionId/planId/kind/form/summary/text,是机器可读的权威
18
+ * 通知流(区别于用户真实输入——真实输入永远不会进本文件);
19
+ * - 写入失败不拖垮通知投递(user/message 才是模型的权威通道,且已通过
20
+ * 回读校验):失败行进内存环形缓冲,下一次写入时先行补落,尽最大努力
21
+ * 不丢、且绝不静默。
22
+ *
23
+ * 纪律与 lessons.ts(第 1 批)一致:同步读写、整行 JSON、坏行读端跳过/写端
24
+ * 原样保留。审计证据默认永久保留,不做轮转(与 journalRetentionDays 默认 0
25
+ * 的裁决一致)。
26
+ *
27
+ * [复审修复][第 4 批] 治理与安全加固:
28
+ * - 行数上限 NOTICE_LEDGER_MAX_LINES(默认 5000,可被正整数环境变量
29
+ * DSH_WORKPLAN_NOTICES_MAX_LINES 覆盖):超限即重写为「最新 N 行」
30
+ * (读全 → 取末 N → tmp+rename 原子替换),重写失败 best-effort 不拖垮写入;
31
+ * - 权限:目录 0o700、文件 0o600(新建以 mode 落盘、既有文件 best-effort chmod);
32
+ * - 防符号链接投毒:写/重写前 lstatSync 目标文件,是符号链接则跳过写入并
33
+ * console.warn(不抛错),绝不跟随链接写任意路径。
34
+ */
35
+ import { appendFileSync, chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
36
+ import { homedir } from 'node:os'
37
+ import { dirname, join } from 'node:path'
38
+
39
+ export const NOTICE_LEDGER_VERSION = 1
40
+ /** 写失败时的内存环形缓冲上限(尽最大努力补落,绝不清空丢弃)。 */
41
+ export const NOTICE_LEDGER_OVERFLOW_MAX = 100
42
+ /** 台账行数上限:超过即重写为「最新 N 行」。可被 DSH_WORKPLAN_NOTICES_MAX_LINES(正整数)覆盖。 */
43
+ export const NOTICE_LEDGER_MAX_LINES = 5000
44
+
45
+ function errorText(error: unknown): string {
46
+ const text = error instanceof Error ? error.message : String(error)
47
+ return text.slice(0, 500)
48
+ }
49
+
50
+ /** 解析行数上限(env 优先,沿用 resolveNoticeLedgerFile 的解析风格)。 */
51
+ function resolveNoticeLedgerMaxLines(env: NodeJS.ProcessEnv = process.env): number {
52
+ const raw = typeof env?.DSH_WORKPLAN_NOTICES_MAX_LINES === 'string'
53
+ ? env.DSH_WORKPLAN_NOTICES_MAX_LINES.trim()
54
+ : ''
55
+ if (!raw) return NOTICE_LEDGER_MAX_LINES
56
+ const parsed = Number(raw)
57
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : NOTICE_LEDGER_MAX_LINES
58
+ }
59
+
60
+ /** 统计文本中的行数(按换行计;本模块写盘恒以 \n 结尾,行数 == \n 数)。 */
61
+ function countNewlines(text: string): number {
62
+ let count = 0
63
+ for (let i = 0; i < text.length; i += 1) {
64
+ if (text.charCodeAt(i) === 10) count += 1
65
+ }
66
+ return count
67
+ }
68
+
69
+ /**
70
+ * 行数治理:写后若总行数超过上限,重写为「最新 N 行」。
71
+ * 全程 best-effort:任何失败只 console.warn,绝不抛错、绝不拖垮已成功的写入。
72
+ */
73
+ function enforceNoticeLedgerCap(file: string, maxLines: number): void {
74
+ if (!Number.isSafeInteger(maxLines) || maxLines <= 0) return
75
+ let text: string
76
+ try {
77
+ text = readFileSync(file, 'utf8')
78
+ } catch (error) {
79
+ console.warn(`dsh-workplan: notice 台账行数统计失败(不重写)file=${file}(${errorText(error)})`)
80
+ return
81
+ }
82
+ const total = countNewlines(text)
83
+ if (total <= maxLines) return
84
+ // 防符号链接投毒:重写前再确认目标是普通文件(TOCTOU 缩小面;rename 只换链接本身也不跟随,但按纪律跳过)。
85
+ try {
86
+ if (lstatSync(file).isSymbolicLink()) {
87
+ console.warn(`dsh-workplan: notice 台账是符号链接,跳过重写 file=${file}`)
88
+ return
89
+ }
90
+ } catch (error) {
91
+ console.warn(`dsh-workplan: notice 台账重写前 lstat 失败(不重写)file=${file}(${errorText(error)})`)
92
+ return
93
+ }
94
+ const kept = text.split('\n').filter((line) => line.trim() !== '').slice(-maxLines)
95
+ const body = kept.length > 0 ? `${kept.join('\n')}\n` : ''
96
+ const tmp = `${file}.tmp-${process.pid}`
97
+ try {
98
+ writeFileSync(tmp, body, { encoding: 'utf8', mode: 0o600 })
99
+ renameSync(tmp, file)
100
+ } catch (error) {
101
+ console.warn(`dsh-workplan: notice 台账超限重写失败(保留原文件)file=${file}(${errorText(error)})`)
102
+ try {
103
+ unlinkSync(tmp)
104
+ } catch {
105
+ /* 临时文件清理失败可忽略。 */
106
+ }
107
+ }
108
+ }
109
+
110
+ export type NoticeLedgerRecord = {
111
+ version: number
112
+ at: number
113
+ sessionId: string
114
+ planId: string
115
+ kind: string
116
+ form: string
117
+ summary: string
118
+ text: string
119
+ /** 对应的 user/message 事件 seq(写入时未知则为 -1)。 */
120
+ surfaceSeq: number
121
+ }
122
+
123
+ /** 台账文件位置:默认用户主目录,跨项目保留;测试可用环境变量覆盖。 */
124
+ export function resolveNoticeLedgerFile(env: NodeJS.ProcessEnv = process.env): string {
125
+ const override = typeof env?.DSH_WORKPLAN_NOTICES_FILE === 'string'
126
+ ? env.DSH_WORKPLAN_NOTICES_FILE.trim()
127
+ : ''
128
+ if (override) return override
129
+ return join(homedir(), '.dsh', 'workplan', 'notices.jsonl')
130
+ }
131
+
132
+ function isRecord(value: unknown): value is Record<string, unknown> {
133
+ return !!value && typeof value === 'object' && !Array.isArray(value)
134
+ }
135
+
136
+ function coerceRecord(raw: unknown): NoticeLedgerRecord | null {
137
+ if (!isRecord(raw)) return null
138
+ return {
139
+ version: Number(raw.version) || NOTICE_LEDGER_VERSION,
140
+ at: Number(raw.at) || 0,
141
+ sessionId: typeof raw.sessionId === 'string' ? raw.sessionId : '',
142
+ planId: typeof raw.planId === 'string' ? raw.planId : '',
143
+ kind: typeof raw.kind === 'string' ? raw.kind : '',
144
+ form: typeof raw.form === 'string' ? raw.form : '',
145
+ summary: typeof raw.summary === 'string' ? raw.summary : '',
146
+ text: typeof raw.text === 'string' ? raw.text : '',
147
+ surfaceSeq: Number.isSafeInteger(Number(raw.surfaceSeq)) ? Number(raw.surfaceSeq) : -1,
148
+ }
149
+ }
150
+
151
+ /** 读端:坏行跳过不拖垮整份台账。 */
152
+ export function readNoticeLedger(file: string = resolveNoticeLedgerFile()): NoticeLedgerRecord[] {
153
+ if (!existsSync(file)) return []
154
+ let text = ''
155
+ try {
156
+ text = readFileSync(file, 'utf8')
157
+ } catch {
158
+ return []
159
+ }
160
+ const out: NoticeLedgerRecord[] = []
161
+ for (const line of text.split('\n')) {
162
+ const trimmed = line.trim()
163
+ if (!trimmed) continue
164
+ try {
165
+ const parsed = coerceRecord(JSON.parse(trimmed))
166
+ if (parsed) out.push(parsed)
167
+ } catch {
168
+ // 单行损坏跳过:append-only 文件不做重写,坏行原样留在盘上。
169
+ }
170
+ }
171
+ return out
172
+ }
173
+
174
+ /** 内存补落缓冲:文件写入失败时暂存,下一次写入先行补落。 */
175
+ let overflow: string[] = []
176
+
177
+ /** 取出当前积压的补落行数(可观测性/测试用)。 */
178
+ export function noticeLedgerOverflowSize(): number {
179
+ return overflow.length
180
+ }
181
+
182
+ function textOfMessage(message: any): string {
183
+ const content = message?.content
184
+ if (typeof content === 'string') return content
185
+ if (Array.isArray(content)) {
186
+ return content
187
+ .map((block: any) => (typeof block?.text === 'string' ? block.text : ''))
188
+ .filter(Boolean)
189
+ .join('\n')
190
+ }
191
+ return ''
192
+ }
193
+
194
+ /**
195
+ * 追加一行通知台账(同步、尽力而为)。
196
+ *
197
+ * @returns 是否写入(含补落)成功;失败行留在内存环形缓冲等待下次补落。
198
+ */
199
+ export function appendNoticeLedger(
200
+ sessionId: string,
201
+ message: any,
202
+ file: string = resolveNoticeLedgerFile(),
203
+ now: number = Date.now(),
204
+ ): boolean {
205
+ const source = isRecord(message?.source) ? message.source : {}
206
+ const record: NoticeLedgerRecord = {
207
+ version: NOTICE_LEDGER_VERSION,
208
+ at: now,
209
+ sessionId: String(sessionId ?? ''),
210
+ planId: typeof source.planId === 'string' ? source.planId
211
+ : (typeof message?.planId === 'string' ? message.planId : ''),
212
+ kind: typeof source.kind === 'string' ? source.kind : 'workplan',
213
+ form: typeof source.form === 'string' ? source.form : 'notice',
214
+ summary: typeof source.summary === 'string' ? source.summary : '',
215
+ text: textOfMessage(message),
216
+ surfaceSeq: typeof message?.seq === 'number' ? message.seq : -1,
217
+ }
218
+ return flushNoticeLedger(file, [JSON.stringify(record)])
219
+ }
220
+
221
+ /** 先补落积压行,再写新行;全部成功才清空缓冲。 */
222
+ function flushNoticeLedger(file: string, freshLines: string[]): boolean {
223
+ const pending = [...overflow, ...freshLines]
224
+ // 防符号链接投毒:目标是符号链接则跳过写入并告警(不抛错,行留缓冲等待下次)。
225
+ try {
226
+ if (lstatSync(file).isSymbolicLink()) {
227
+ console.warn(`dsh-workplan: notice 台账目标是符号链接,跳过写入 file=${file}`)
228
+ overflow = pending.slice(-NOTICE_LEDGER_OVERFLOW_MAX)
229
+ return false
230
+ }
231
+ } catch {
232
+ /* 文件不存在(ENOENT,首写)或 lstat 失败:交给 appendFileSync 显式成败。 */
233
+ }
234
+ try {
235
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
236
+ appendFileSync(file, `${pending.join('\n')}\n`, { encoding: 'utf8', mode: 0o600 })
237
+ try {
238
+ // 既有文件权限收紧为 0o600(best-effort;新建文件已由 mode 覆盖)。
239
+ chmodSync(file, 0o600)
240
+ } catch {
241
+ /* best-effort:权限收紧失败不阻断追加。 */
242
+ }
243
+ overflow = []
244
+ // 行数治理(best-effort):超限即重写为「最新 N 行」,失败只 warn 不拖垮写入。
245
+ enforceNoticeLedgerCap(file, resolveNoticeLedgerMaxLines())
246
+ return true
247
+ } catch {
248
+ overflow = pending.slice(-NOTICE_LEDGER_OVERFLOW_MAX)
249
+ return false
250
+ }
251
+ }
package/src/plan.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * runtime and by unit tests.
8
8
  */
9
9
 
10
+ import { appendNoticeLedger } from './notice-ledger.js'
10
11
  import { createHash, randomUUID } from 'node:crypto'
11
12
 
12
13
  import { DEPARTMENT_CAPABILITIES, DEPARTMENT_EXPERT_STANDARD, departmentCapability } from './departments.js'
@@ -1696,7 +1697,7 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
1696
1697
  resumes > 0
1697
1698
  ? `- 受阻后自动续跑额度 ${resumes} 次;需要时计划会暂停并在下一轮继续。`
1698
1699
  : '- 自动续跑额度为 0;计划不会因轮次预算被暂停。',
1699
- '- [3.0.0][用户要求 3/5] 每个子任务必须写 qualityRequirements(1-8 条字符串):这是主 Agent 派给部门负责人时随任务书一起下达的「结果质量要求」,写清成果必须达到什么要求、什么算合格。缺失质量要求的子任务在派发时会被系统直接拒发(DISPATCH_QUALITY_REQUIREMENTS_MISSING,不启动部门 Agent),必须 replan 补齐后重新派发。同时子任务必须是简单到 1+1=2 的单项工作:一个目标、一个主产物、一项可独立验收;不要在一个子任务里塞并列的多件事(出现「并且/同时/另外/还要/以及/分别/顺便」或多句并列时应拆成多个子任务)。',
1700
+ '- [3.0.0][用户要求 3/5] 每个子任务必须写 qualityRequirements(1-8 条字符串):这是主 Agent 派给部门负责人时随任务书一起下达的「结果质量要求」,写清成果必须达到什么要求、什么算合格。缺失质量要求的子任务在派发时会被系统直接拒发(DISPATCH_QUALITY_REQUIREMENTS_MISSING,不启动部门 Agent),必须 replan 补齐后重新派发。同时子任务必须是简单到 1+1=2 的单项工作:一个目标、一个主产物、一项可独立验收;不要在一个子任务里塞并列的多件事(出现「并且/并/同时/另外/还要/以及/分别/顺便/然后/接着/再」或多句并列——含英文句点 `.` 分隔的多句——时应拆成多个子任务)。',
1700
1701
  '- 每个子任务必须写 estimateMinutes(整数 1-240,如实预估):只用于安排协调与告知用户,仅供参考、非承诺;不会派生执行截止,不会因超过预估算超时,也不影响 done 验收。取值整数与范围校验仅防止离谱输入,缺失不报错。',
1701
1702
  /*
1702
1703
  * [2.2.0][T13/推理等级] 子 Agent 必须自决推理等级,禁止继承主 Agent。
@@ -1883,7 +1884,11 @@ function flushPreHeadNotices(session: any) {
1883
1884
  // 头未就绪绝不补发(否则又把通知写到 head 之前);等 head 落地后的下一次写入再补。
1884
1885
  if (!surfaceHeadExists(session)) return
1885
1886
  preHeadNoticeQueue.delete(session)
1886
- for (const message of queue) session.append('user/message', toJsonSafe(message), { surfaceOp: 'append' })
1887
+ for (const message of queue) {
1888
+ session.append('user/message', toJsonSafe(message), { surfaceOp: 'append' })
1889
+ /* [T3][回读校验] 补发直写同样写后读回比对关键字段,不一致即抛(见补丁头部注释)。 */
1890
+ verifySessionAppendReadback(session, message, 'flushPreHeadNotices')
1891
+ }
1887
1892
  }
1888
1893
 
1889
1894
  /*
@@ -2206,6 +2211,94 @@ export function toJsonSafe(value: any, seen?: WeakSet<object>): any {
2206
2211
  }
2207
2212
  }
2208
2213
 
2214
+ /*
2215
+ * [T3][回读校验·补丁头部注释] 落盘后回读校验(部门负责人 2026-11-17 方案 A 指示)。
2216
+ * 依据来源:reports/wp-member-expert-persist-call-T1.json(写盘点①-⑨)与
2217
+ * reports/wp-member-expert-storage-T1-storage.json(journal/lessons 路径与写入代码),
2218
+ * 辅以 dsh-workplan-patch/dispatch-survey.md §3「落盘丢失+派发照跑」缺口与
2219
+ * reports/T2-hardening-assessment.md H4(落盘后回读校验)。
2220
+ * 覆盖映射(调研报告写盘点 → 本补丁 hunk,一一对应、无新增写盘点):
2221
+ * plan.ts:2284 appendUserMessage 统一会话写入器 → hunk「appendUserMessage 写后校验」
2222
+ * plan.ts:1886 flushPreHeadNotices 暂存队列补发直写 → hunk「flushPreHeadNotices 写后校验」
2223
+ * plan.ts:2540-2606 PLAN_MARKER / runtime.ts:11010-11023、:11018、:11284 计划投递
2224
+ * / plan.ts:4248、2936、3109 + runtime.ts:5897、6048、6874、6202 durable 信封
2225
+ * / plan.ts:2100-2143 合并归档 —— 以上 call_site 全部 funnel 经 appendUserMessage
2226
+ * 落会话日志 → 由「appendUserMessage 写后校验」同一 hunk 全覆盖,不逐点重复插桩
2227
+ * dept-journal.ts:290-308 journal 留痕文件追加 → 本补丁 src/dept-journal.ts hunk
2228
+ * lessons.ts:243-249、328-329 → 负责人硬性要求②明确排除
2229
+ * (非计划持久化写入点),本补丁不覆盖
2230
+ * 行号漂移复核(2026-11-17,grep -n + read 对照当前工作树):plan.ts:1886/2209/2284、
2231
+ * dept-journal.ts:302/303 与 T1 报告一致、无漂移;
2232
+ * dispatch-survey.md 锚点 runtime.ts:9166(dispatchTool)/9597(releaseTool) 一致,
2233
+ * NO_PLAN 报告写 9204、实际 9203(差 1 行),以实际为准。
2234
+ * 语义:会话事件日志 append 成功后立即用 session.eventAt(session.seq - 1) 读回最近
2235
+ * 事件,JSON 解析后比对关键字段(source.kind/form/summary、plan.planId、文本头 120
2236
+ * 字与长度摘要)。不一致或读不到事件 → 抛含会话路径与期望/实际摘要、处置指引
2237
+ * (重试或让主 Agent 手动制定计划)的显式错误,禁止静默(硬性要求③)。
2238
+ * 纯读校验、无副作用、不写盘 → 幂等(硬性要求④)。单线程事件循环内 append 与
2239
+ * eventAt 之间无 await,seq-1 必为本条,无并发错位。
2240
+ */
2241
+ function sessionAppendKeyDigest(message: any): string {
2242
+ const source = isRecord(message?.source) ? message.source : {}
2243
+ const text = messageText(message) ?? ''
2244
+ return JSON.stringify({
2245
+ kind: String(source.kind ?? ''),
2246
+ form: String(source.form ?? ''),
2247
+ summary: String(source.summary ?? ''),
2248
+ planId: typeof message?.plan?.planId === 'string' ? message.plan.planId : '',
2249
+ textHead: text.slice(0, 120),
2250
+ textLength: text.length,
2251
+ })
2252
+ }
2253
+
2254
+ function sessionAppendReadbackPath(session: any): string {
2255
+ for (const key of ['file', 'path', 'filePath', 'sessionFile']) {
2256
+ const value = session?.[key]
2257
+ if (typeof value === 'string' && value) return value
2258
+ }
2259
+ const id = session?.id ?? session?.sessionId
2260
+ return typeof id === 'string' && id ? `session:${id}` : 'unknown-session'
2261
+ }
2262
+
2263
+ function normalizeEventData(data: any): any {
2264
+ if (typeof data !== 'string') return data
2265
+ try {
2266
+ return JSON.parse(data)
2267
+ } catch {
2268
+ return data
2269
+ }
2270
+ }
2271
+
2272
+ function verifySessionAppendReadback(session: any, written: any, context: string): void {
2273
+ /*
2274
+ * 单元桩会话只有 append、没有事件日志介质(生产宿主必有 eventAt——
2275
+ * reconstructFromSession runtime.ts:4203 依赖它回放计划),无介质可读时不构成
2276
+ * 「落盘内容不一致」,原样放行;生产路径一律严格校验、失败即抛。
2277
+ */
2278
+ if (typeof session?.eventAt !== 'function') return
2279
+ let event: any
2280
+ try {
2281
+ event = session.eventAt(session.seq - 1)
2282
+ } catch (error) {
2283
+ throw new Error(
2284
+ `dsh-workplan: 会话落档回读校验失败(${context}):读回事件抛错 ${String(error)};`
2285
+ + `会话路径=${sessionAppendReadbackPath(session)}。请重试;若多次失败请让主 Agent 手动制定计划。`,
2286
+ )
2287
+ }
2288
+ /* [T3][R1 修正] 期望摘要必须与落盘口径一致:写入侧落盘的是 toJsonSafe(message),
2289
+ * 读回比对也必须对 toJsonSafe(written) 取摘要。若对原始 message 取摘要,NaN/Date/Map
2290
+ * 等 T2 类负载会被 toJsonSafe 改写后与读回值不符,导致误抛「回读校验失败」。 */
2291
+ const expected = sessionAppendKeyDigest(toJsonSafe(written))
2292
+ const actual = event ? sessionAppendKeyDigest(normalizeEventData(event.data)) : '<读回不到事件>'
2293
+ if (!event || event.type !== 'user/message' || actual !== expected) {
2294
+ throw new Error(
2295
+ `dsh-workplan: 会话落档回读校验失败(${context}):写入内容与读回内容关键字段不一致。`
2296
+ + `会话路径=${sessionAppendReadbackPath(session)} 期望=${expected.slice(0, 300)}`
2297
+ + ` 实际=${String(actual).slice(0, 300)}。请重试;若多次失败请让主 Agent 手动制定计划。`,
2298
+ )
2299
+ }
2300
+ }
2301
+
2209
2302
  export function appendUserMessage(session: any, payload: any, source?: any, opts?: { deferUntilHead?: boolean; allowBanned?: boolean }) {
2210
2303
  if (!session || typeof session.append !== 'function') return undefined
2211
2304
  let message = payload
@@ -2281,7 +2374,19 @@ export function appendUserMessage(session: any, payload: any, source?: any, opts
2281
2374
  flushPreHeadNotices(session)
2282
2375
  /* [T2][治本] 写入前净化为纯 JSON:NaN/undefined/Date/Map/Set/循环引用等
2283
2376
  * 一律转为可序列化值,杜绝宿主 snapshotJsonValue 校验抛错导致的重试刷屏。 */
2284
- return session.append('user/message', toJsonSafe(message), { surfaceOp: 'append' })
2377
+ const appended = session.append('user/message', toJsonSafe(message), { surfaceOp: 'append' })
2378
+ /* [T3][回读校验] 写后立即读回比对关键字段,不一致抛显式错误(见补丁头部注释)。 */
2379
+ verifySessionAppendReadback(session, message, 'appendUserMessage')
2380
+ /*
2381
+ * [3.0.6][第 3 批②] 专用通知台账:workplan 通知成功落盘后同步追加一行
2382
+ * 插件自有 JSONL 台账(见 notice-ledger.ts 头部——宿主禁止自定义事件类型,
2383
+ * 故通道是插件存储而非 Session 事件)。台账失败不拖垮投递:失败行进内存
2384
+ * 环形缓冲等待下次补落。真实用户输入不走本函数,因此不会混入台账。
2385
+ */
2386
+ if (String(message?.source?.kind ?? '').startsWith('workplan')) {
2387
+ appendNoticeLedger(session.id, { ...message, seq: appended?.seq })
2388
+ }
2389
+ return appended
2285
2390
  }
2286
2391
 
2287
2392
  /*
@@ -3179,10 +3284,26 @@ export function parseCancelMessage(message: any) {
3179
3284
  * 这里用规范化后的包含关系做匹配:允许「必须给出命令与退出码」与
3180
3285
  * 「给出命令与退出码」这类措辞差异,但不允许完全不同的一条顶替。
3181
3286
  * 短文本(< 6 字)只接受等值,避免 "ok" 命中任意单词。
3287
+ *
3288
+ * [3.0.3] 验收措辞归一化:子 Agent 换个措辞汇报(加标点、大小写、多余
3289
+ * 空格、全角字符、「已完成:」式完成态前缀)就永远 missing → 验收被无限
3290
+ * 退回。比较前对两侧做同一套归一化:
3291
+ * 1. trim;
3292
+ * 2. 全角→半角(U+FF01–FF5E、全角空格 U+3000)——必须在去标点之前做,
3293
+ * 否则全角标点先消失、全角字母数字留着,两边仍然对不上;
3294
+ * 3. 小写化;
3295
+ * 4. 去常见完成态前缀(已完成/完成/已/done/yes)。CJK 前缀允许与正文直接
3296
+ * 相接(「完成接口测试」⇔「已完成:接口测试」);英文 done/yes 必须后随
3297
+ * 标点或空白,避免误吃 yesterday 这类以 yes 开头的词。该步在去标点前
3298
+ * 做,使「已完成:」「已完成:」与「已完成」归一到同一串。
3182
3299
  */
3183
3300
  export function normaliseCriterion(value: any) {
3184
3301
  return String(value ?? '')
3302
+ .trim()
3303
+ .replace(/[!-~]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 0xFEE0))
3304
+ .replace(/ /g, ' ')
3185
3305
  .toLowerCase()
3306
+ .replace(/^(?:已完成|完成|已|done|yes)(?=[\s::,,。.!!??;;、\-—–]|$)|^(?:已完成|完成|已)/i, '')
3186
3307
  .replace(/[\s,。;、,.;::!!??"'“”‘’()()\[\]【】《》<>]/g, '')
3187
3308
  .replace(/^(必须|需要|应当|应该|请|务必)/, '')
3188
3309
  }
@@ -4058,7 +4179,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
4058
4179
  acceptance,
4059
4180
  artifacts,
4060
4181
  needs,
4061
- error: `三阶段证据不完整(未按「规划→执行→验证」回报):${phaseCheck.errors.slice(0, 6).join(';')}`,
4182
+ error: `五步证据不完整(未按「任务梳理→资源工具方案研究→准备→执行验证→JSON 交付」回报):${phaseCheck.errors.slice(0, 6).join(';')}`,
4062
4183
  phases: null,
4063
4184
  }
4064
4185
  }
@@ -6688,7 +6809,7 @@ export function buildChildPrompt({
6688
6809
  '',
6689
6810
  '结果回传(必填):在汇报的最后附上一个结构化结果块,主 Agent 会按它逐项核对,不再只依赖自述。',
6690
6811
  EVIDENCE_MARKER_BEGIN,
6691
- '{"status":"done","blockedReason":"","phases":{"planning":{"problemAnalysis":["要解决的问题 1(含现状/约束/未知/主要矛盾)"],"constraints":["..."],"unknowns":["..."],"approach":["第 1 步:做什么 → 产出什么 → 如何证明"]},"execution":{"steps":["实际执行的步骤"],"deviations":[]},"verification":{"allPassed":true,"checks":[{"criterion":"A1","method":"怎么验证","evidence":"命令输出/文件/引用"}],"requirementCheck":"逐条核对用户原要求的结果","retrospective":{"problems":["本次遇到的问题(现象+根因)"],"detours":["走过的弯路/返工/无效尝试;确实没有就写 []"],"resolutions":["最终是如何解决的"],"prevention":["以后如何预防再犯:遇到…先…"]}}},"acceptance":[{"criterion":"A1 把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[],"question":"","options":[],"timeSpentMinutes":0,"finalEstimateMinutes":0}',
6812
+ '{"status":"done","blockedReason":"","phases":{"planning":{"problemAnalysis":["要解决的问题 1(含现状/约束/未知/主要矛盾)"],"constraints":["..."],"unknowns":["..."],"resources":["完成本任务需要的资源:数据/文件/权限/人/知识/时间(逐项写用途与获取方式)"],"tools":["需要的工具及用途(为什么选它)"],"approach":["第 1 步:做什么 → 产出什么 → 如何证明"]},"preparation":{"prepared":["已备齐的资源/工具:准备了什么、在哪里、是否可用"],"evidence":["每项就绪证据:命令输出/文件路径/配置项/版本号/引用"]},"execution":{"steps":["实际执行的步骤"],"deviations":[]},"verification":{"allPassed":true,"checks":[{"criterion":"A1","method":"怎么验证","evidence":"命令输出/文件/引用"}],"requirementCheck":"逐条核对用户原要求的结果","retrospective":{"problems":["本次遇到的问题(现象+根因)"],"detours":["走过的弯路/返工/无效尝试;确实没有就写 []"],"resolutions":["最终是如何解决的"],"prevention":["以后如何预防再犯:遇到…先…"]}}},"acceptance":[{"criterion":"A1 把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[],"question":"","options":[],"timeSpentMinutes":0,"finalEstimateMinutes":0}',
6692
6813
  EVIDENCE_MARKER_END,
6693
6814
  '- [2.2.9] 盘上结算备份(必做):发送结果块之前,先把同一份 JSON 写入 reports/wp-settlement-<你的子任务 ID>.json(相对工作目录)。收尾消息因异常(error/截断/超时)丢失时,宿主会自动采纳该备份结算,避免「已完成的工作」被误判为「缺失回报」而受阻并级联冻结下游。[2.5.2][T4b] 备份 JSON 顶层必须带 planId 与 subtaskId(childId 若已知也带上),且必须是本次执行新写(覆盖同名旧文件):宿主采纳前会校验新鲜度(文件修改时间不早于本次尝试开始时间)与归属(planId/subtaskId 必须匹配本计划/本子任务),陈旧或跨计划的备份会被拒绝采纳并留审计痕。',
6694
6815
  '- status 只能是 done / blocked / partial;partial 会被当作受阻处理。',