dsh-workplan 1.10.6 → 1.11.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.
package/lib/replan.js ADDED
@@ -0,0 +1,678 @@
1
+ /**
2
+ * [1.11.0] 子任务级重规划:把「需求变更」落成一条可回放、可追溯的状态迁移。
3
+ *
4
+ * 为什么单独一个文件:重规划同时改两样东西——计划定义(新增/替换子任务)与
5
+ * 状态条目(旧行标 `closure:'replanned'`)。如果实时路径改内存、回放路径靠
6
+ * 重新解析 plan 消息,两条路径必然分叉(旧行复活、分母漂移)。因此:
7
+ *
8
+ * 1. `planReplan()` 是纯函数:输入旧计划 + 旧状态 + 变更表,输出「修订后
9
+ * 的完整计划 + 旧行标记 + 新行清单」,不读时钟、不碰会话;
10
+ * 2. 实时路径与回放路径都调用同一个 `applyReplanStatuses()`;
11
+ * 3. durable 记录 `workplan-replan` 里带**完整修订计划**,回放直接采用,
12
+ * 不需要重新推导,因此刷新/重启后看到的是同一份定义。
13
+ *
14
+ * 旧行不删除:它在计划里保留 `supersededAt/replacedBy`,在状态里保留
15
+ * `closure:'replanned'`。展示层据此渲染「已重规划 → 修订 rN」并灰化,计数与
16
+ * 调度器则把它排除(见 plan.ts 的 `isReplannedStatus`、`definedSubtaskCount`)。
17
+ */
18
+ import { DEPARTMENTS, MAX_STAGES, MAX_SUBTASKS, PLAN_VERSION, applyStatus, flattenSubtasks, isRecord, makeUserMessage, messageText, truncate, } from './plan.js';
19
+ export const REPLAN_MARKER_BEGIN = '<!-- DSH-WORKPLAN-REPLAN:BEGIN -->';
20
+ export const REPLAN_MARKER_END = '<!-- DSH-WORKPLAN-REPLAN:END -->';
21
+ export const REPLAN_ACTIONS = Object.freeze(['cancel', 'replace', 'add']);
22
+ export const MAX_REPLAN_CHANGES = 12;
23
+ /**
24
+ * [1.11.0] 重规划是第二个写计划定义的入口,部门合法性必须与首次规划同强度。
25
+ * 修复前 replace/add 接受任意值(数字、对象、注入文本),会绕过
26
+ * `validatePlan` 直接进提示词。
27
+ */
28
+ function replanDepartment(value) {
29
+ if (typeof value !== 'string')
30
+ return null;
31
+ return Object.prototype.hasOwnProperty.call(DEPARTMENTS, value) ? value : null;
32
+ }
33
+ /** 单个变更理由上限,避免模型把整段对话塞进 durable 消息。 */
34
+ export const MAX_REPLAN_REASON_CHARS = 2000;
35
+ export const REPLAN_CODES = {
36
+ NO_PLAN: 'REPLAN_NO_PLAN',
37
+ REASON_REQUIRED: 'REPLAN_REASON_REQUIRED',
38
+ NO_CHANGES: 'REPLAN_NO_CHANGES',
39
+ TOO_MANY_CHANGES: 'REPLAN_TOO_MANY_CHANGES',
40
+ UNKNOWN_SUBTASK: 'REPLAN_UNKNOWN_SUBTASK',
41
+ ALREADY_SUPERSEDED: 'REPLAN_ALREADY_SUPERSEDED',
42
+ INVALID_ACTION: 'REPLAN_INVALID_ACTION',
43
+ DUPLICATE_CHANGE: 'REPLAN_DUPLICATE_CHANGE',
44
+ INVALID_REPLACEMENT: 'REPLAN_INVALID_REPLACEMENT',
45
+ INVALID_SUBTASK: 'REPLAN_INVALID_SUBTASK',
46
+ GRAPH_INVALID: 'REPLAN_GRAPH_INVALID',
47
+ WRITE_FAILED: 'REPLAN_WRITE_FAILED',
48
+ };
49
+ function fail(code, error) {
50
+ return { ok: false, code, error };
51
+ }
52
+ function clone(value) {
53
+ return JSON.parse(JSON.stringify(value));
54
+ }
55
+ /** 子任务在修订计划中的线性位置,用于依赖顺序校验。 */
56
+ function orderMap(plan) {
57
+ const order = new Map();
58
+ let next = 0;
59
+ for (const entry of flattenSubtasks(plan)) {
60
+ order.set(String(entry.subtask?.id ?? ''), next);
61
+ next += 1;
62
+ }
63
+ return order;
64
+ }
65
+ function hasSubtasks(plan) {
66
+ try {
67
+ return flattenSubtasks(plan).length > 0;
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
73
+ function subtaskOf(plan, id) {
74
+ for (const entry of flattenSubtasks(plan)) {
75
+ if (String(entry.subtask?.id ?? '') === id)
76
+ return entry;
77
+ }
78
+ return null;
79
+ }
80
+ /**
81
+ * 图的最后一道闸:ID 唯一、依赖存在且在前、总数与阶段数不超限。
82
+ *
83
+ * 不复用 `validatePlan()`:它按固定 schema 重建子任务,会把 `supersededAt` /
84
+ * `replacedBy` 这类审计字段丢掉,重规划标记就失效了。这里只校验结构,
85
+ * 不改写对象。
86
+ */
87
+ function checkReplanGraph(plan) {
88
+ const errors = [];
89
+ const stages = Array.isArray(plan?.stages) ? plan.stages : [];
90
+ if (stages.length < 1)
91
+ errors.push('修订后的计划至少需要 1 个阶段');
92
+ if (stages.length > MAX_STAGES)
93
+ errors.push(`阶段数 ${stages.length} 超过上限 ${MAX_STAGES}`);
94
+ const order = orderMap(plan);
95
+ /*
96
+ * [1.11.0] 容量只数「仍在计划里的行」(T4 D-T4-04)。
97
+ *
98
+ * superseded 旧行是为审计保留的历史,不是待办;把它们计入 15 项,会让
99
+ * 满编计划第一次 replace 就撞墙,用户被迫删历史才能改计划。
100
+ */
101
+ const active = flattenSubtasks(plan).filter((entry) => !entry.subtask?.supersededAt).length;
102
+ if (active > MAX_SUBTASKS)
103
+ errors.push(`子任务总数 ${active} 超过上限 ${MAX_SUBTASKS}`);
104
+ for (const entry of flattenSubtasks(plan)) {
105
+ const subtask = entry.subtask ?? {};
106
+ const id = String(subtask.id ?? '');
107
+ if (!id) {
108
+ errors.push('存在 id 为空的子任务');
109
+ continue;
110
+ }
111
+ const dependencies = Array.isArray(subtask.dependsOn) ? subtask.dependsOn : [];
112
+ for (const dependency of dependencies) {
113
+ if (!order.has(String(dependency))) {
114
+ errors.push(`${id} 依赖了不存在的子任务 ${String(dependency)}`);
115
+ continue;
116
+ }
117
+ if (Number(order.get(String(dependency))) >= Number(order.get(id))) {
118
+ errors.push(`${id} 的依赖 ${String(dependency)} 不在它之前`);
119
+ }
120
+ }
121
+ }
122
+ return errors;
123
+ }
124
+ function nextId(plan, base) {
125
+ const taken = new Set(orderMap(plan).keys());
126
+ if (!taken.has(base))
127
+ return base;
128
+ for (const suffix of 'bcdefghijklmnopqrstuvwxyz') {
129
+ const candidate = `${base}${suffix}`;
130
+ if (!taken.has(candidate))
131
+ return candidate;
132
+ }
133
+ let index = 2;
134
+ while (taken.has(`${base}${index}`))
135
+ index += 1;
136
+ return `${base}${index}`;
137
+ }
138
+ const REPLACEMENT_FIELDS = [
139
+ 'title',
140
+ 'department',
141
+ 'role',
142
+ 'objective',
143
+ 'method',
144
+ 'inputs',
145
+ 'outputs',
146
+ 'acceptance',
147
+ 'risk',
148
+ ];
149
+ /** 用调用方给的替换内容覆盖旧子任务的同名字段;未给字段原样继承。 */
150
+ function mergeReplacement(old, replacement, id, reason) {
151
+ const next = clone(old);
152
+ for (const key of REPLACEMENT_FIELDS) {
153
+ if (replacement?.[key] !== undefined)
154
+ next[key] = clone(replacement[key]);
155
+ }
156
+ next.id = id;
157
+ delete next.supersededAt;
158
+ delete next.supersededRevision;
159
+ delete next.replacedBy;
160
+ next.replaces = old.id;
161
+ next.insertedBy = 'replan';
162
+ next.replannedReason = reason;
163
+ return next;
164
+ }
165
+ /**
166
+ * 纯重规划:改计划定义 + 产出旧行标记。
167
+ *
168
+ * @param plan - 当前计划定义。
169
+ * @param changes - 模型给出的变更表(每项一个 subtaskId)。
170
+ * @param options - `reason` 必填;`revision` 为新修订号;`at` 由调用方给,
171
+ * 保证回放与实时不使用两次时钟。
172
+ */
173
+ /**
174
+ * [1.11.0] replan 是第二个写计划定义的入口,字段强度必须对齐 validatePlan
175
+ * (T4 D-T4-03)。修复前 add 接受 14 条依赖、200 条 inputs 与 16 万字符
176
+ * 载荷,这些计划再也回灌不了 validatePlan,却能被真实派发。
177
+ */
178
+ function replanFieldError(raw) {
179
+ const list = (key, max, itemMax, required = false) => {
180
+ const value = raw?.[key];
181
+ if (value === undefined)
182
+ return required ? `${key} 不能为空` : null;
183
+ if (!Array.isArray(value))
184
+ return `${key} 必须是数组`;
185
+ if (value.length > max)
186
+ return `${key} 最多 ${max} 条`;
187
+ if (required && value.length === 0)
188
+ return `${key} 至少需要 1 条`;
189
+ for (const item of value) {
190
+ if (typeof item !== 'string')
191
+ return `${key} 的每一项必须是字符串`;
192
+ if (item.length > itemMax)
193
+ return `${key} 的单项最长 ${itemMax} 字符`;
194
+ }
195
+ return null;
196
+ };
197
+ const one = (key, max, required = false) => {
198
+ const value = raw?.[key];
199
+ if (value === undefined)
200
+ return required ? `${key} 不能为空` : null;
201
+ if (typeof value !== 'string')
202
+ return `${key} 必须是字符串`;
203
+ if (required && value.trim() === '')
204
+ return `${key} 不能为空`;
205
+ if (value.length > max)
206
+ return `${key} 最长 ${max} 字符`;
207
+ return null;
208
+ };
209
+ return list('dependsOn', 12, 16)
210
+ ?? list('method', 12, 800)
211
+ ?? list('inputs', 12, 800)
212
+ ?? list('outputs', 12, 800)
213
+ ?? list('acceptance', 8, 800)
214
+ ?? one('role', 200)
215
+ ?? one('title', 200)
216
+ ?? one('objective', 2000)
217
+ ?? one('risk', 1000);
218
+ }
219
+ export function planReplan(plan, changes, options = {}) {
220
+ const planId = String(options.planId ?? plan?.planId ?? '');
221
+ const reason = truncate(String(options.reason ?? '').trim(), MAX_REPLAN_REASON_CHARS);
222
+ const revision = Number(options.revision);
223
+ const at = Number(options.at);
224
+ if (!planId)
225
+ return fail(REPLAN_CODES.NO_PLAN, '当前会话还没有已生成的计划');
226
+ if (!hasSubtasks(plan))
227
+ return fail(REPLAN_CODES.NO_PLAN, '当前计划没有可重规划的子任务');
228
+ if (!reason)
229
+ return fail(REPLAN_CODES.REASON_REQUIRED, '重规划必须说明 reason(为什么原安排失效)');
230
+ if (!Number.isInteger(revision) || revision < 1) {
231
+ return fail(REPLAN_CODES.GRAPH_INVALID, 'revision 必须是正整数');
232
+ }
233
+ if (!Number.isFinite(at) || at <= 0)
234
+ return fail(REPLAN_CODES.GRAPH_INVALID, 'at 必须是毫秒时间戳');
235
+ if (!Array.isArray(changes) || changes.length === 0) {
236
+ return fail(REPLAN_CODES.NO_CHANGES, 'changes 至少需要 1 项');
237
+ }
238
+ if (changes.length > MAX_REPLAN_CHANGES) {
239
+ return fail(REPLAN_CODES.TOO_MANY_CHANGES, `changes 最多 ${MAX_REPLAN_CHANGES} 项`);
240
+ }
241
+ const next = clone(plan);
242
+ next.planId = plan.planId;
243
+ next.sessionId = plan.sessionId;
244
+ next.createdTurn = plan.createdTurn;
245
+ next.createdAt = plan.createdAt;
246
+ next.sourceMessageIds = Array.isArray(plan.sourceMessageIds) ? [...plan.sourceMessageIds] : [];
247
+ next.planRevision = revision;
248
+ next.replannedAt = at;
249
+ const marks = [];
250
+ const added = [];
251
+ const additions = [];
252
+ const seen = new Set();
253
+ for (const raw of changes) {
254
+ if (!isRecord(raw))
255
+ return fail(REPLAN_CODES.INVALID_ACTION, 'changes 的每一项必须是对象');
256
+ const subtaskId = String(raw.subtaskId ?? '').trim();
257
+ const action = String(raw.action ?? '').trim();
258
+ if (!subtaskId)
259
+ return fail(REPLAN_CODES.UNKNOWN_SUBTASK, 'changes 的每一项必须带 subtaskId');
260
+ if (seen.has(subtaskId))
261
+ return fail(REPLAN_CODES.DUPLICATE_CHANGE, `子任务 ${subtaskId} 在 changes 里出现了两次`);
262
+ seen.add(subtaskId);
263
+ if (!REPLAN_ACTIONS.includes(action)) {
264
+ return fail(REPLAN_CODES.INVALID_ACTION, `子任务 ${subtaskId} 的 action 必须是 cancel / replace / add`);
265
+ }
266
+ if (action === 'add') {
267
+ if (!isRecord(raw.newSubtask)) {
268
+ return fail(REPLAN_CODES.INVALID_SUBTASK, `add(${subtaskId}) 需要 newSubtask(title/objective 必填)`);
269
+ }
270
+ additions.push(raw.newSubtask);
271
+ continue;
272
+ }
273
+ const entry = subtaskOf(next, subtaskId);
274
+ if (!entry)
275
+ return fail(REPLAN_CODES.UNKNOWN_SUBTASK, `计划里没有子任务 ${subtaskId}`);
276
+ if (entry.subtask.supersededAt) {
277
+ return fail(REPLAN_CODES.ALREADY_SUPERSEDED, `子任务 ${subtaskId} 已经被重规划过(修订 r${String(entry.subtask.supersededRevision ?? '?')})`);
278
+ }
279
+ const changeReason = truncate(String(raw.reason ?? reason).trim(), MAX_REPLAN_REASON_CHARS);
280
+ const stage = entry.stage;
281
+ const index = stage.subtasks.indexOf(entry.subtask);
282
+ const old = clone(entry.subtask);
283
+ old.supersededAt = at;
284
+ old.supersededRevision = revision;
285
+ old.replannedReason = changeReason;
286
+ stage.subtasks[index] = old;
287
+ if (action === 'cancel') {
288
+ old.replacedBy = [];
289
+ marks.push({ subtaskId, action: 'cancel', replacedBy: [], reason: changeReason });
290
+ continue;
291
+ }
292
+ const replacement = isRecord(raw.replacement) ? raw.replacement : null;
293
+ if (!replacement) {
294
+ return fail(REPLAN_CODES.INVALID_REPLACEMENT, `replace(${subtaskId}) 需要 replacement:至少给出改后的 objective 或 title`);
295
+ }
296
+ if (replacement.department !== undefined && replanDepartment(replacement.department) === null) {
297
+ return fail(REPLAN_CODES.INVALID_REPLACEMENT, `replacement.department 不是合法部门:${String(replacement.department)}`);
298
+ }
299
+ const replacementError = replanFieldError(replacement);
300
+ if (replacementError)
301
+ return fail(REPLAN_CODES.INVALID_REPLACEMENT, `replacement 字段不合规:${replacementError}`);
302
+ const requestedId = typeof replacement.id === 'string' ? replacement.id.trim() : '';
303
+ if (requestedId && (requestedId === subtaskId || orderMap(next).has(requestedId))) {
304
+ return fail(REPLAN_CODES.INVALID_SUBTASK, `替换行的 id ${requestedId} 已被占用`);
305
+ }
306
+ const newId = requestedId || nextId(next, `${subtaskId}b`);
307
+ if (newId.length > 16)
308
+ return fail(REPLAN_CODES.INVALID_SUBTASK, `子任务 id 最长 16 个字符:${newId}`);
309
+ const successor = mergeReplacement(old, replacement, newId, changeReason);
310
+ successor.dependsOn = Array.isArray(old.dependsOn) ? [...old.dependsOn] : [];
311
+ old.replacedBy = [newId];
312
+ stage.subtasks.splice(index + 1, 0, successor);
313
+ /*
314
+ * 下游的 dependsOn 必须一起改指向,否则它们会永远等一个不再调度的旧行
315
+ * (契约 §7.2 硬规则 3)。只改指到 subtaskId 的那一条,其它依赖不动。
316
+ */
317
+ for (const other of flattenSubtasks(next)) {
318
+ const list = Array.isArray(other.subtask.dependsOn) ? other.subtask.dependsOn : [];
319
+ if (!list.includes(subtaskId))
320
+ continue;
321
+ other.subtask.dependsOn = list.map((dependency) => (dependency === subtaskId ? newId : dependency));
322
+ }
323
+ marks.push({ subtaskId, action: 'replace', replacedBy: [newId], reason: changeReason });
324
+ added.push({
325
+ subtaskId: newId,
326
+ stageId: String(stage.id ?? ''),
327
+ title: String(successor.title ?? ''),
328
+ department: String(successor.department ?? ''),
329
+ role: String(successor.role ?? ''),
330
+ replaces: subtaskId,
331
+ });
332
+ }
333
+ /*
334
+ * add 走独立数组:它不替代任何旧行,只是把新工作追加进新一轮。
335
+ * 放进独立阶段,避免打乱原阶段的位置/依赖顺序。
336
+ */
337
+ for (const [index, raw] of additions.entries()) {
338
+ if (!isRecord(raw))
339
+ return fail(REPLAN_CODES.INVALID_SUBTASK, 'newSubtask 必须是对象');
340
+ /*
341
+ * 阶段 ID 与用户已有阶段撞名时,不能把新任务插进计划中部(T4 反例 V):
342
+ * 位置会决定依赖顺序。撞名就换一个后缀,保证新阶段始终追加在末尾。
343
+ */
344
+ let stageId = `replan-r${revision}`;
345
+ for (let suffix = 0; next.stages.some((item) => item?.id === stageId); suffix += 1) {
346
+ stageId = `replan-r${revision}${suffix === 0 ? 'x' : `x${suffix}`}`;
347
+ }
348
+ const requestedId = typeof raw.id === 'string' ? raw.id.trim() : '';
349
+ const newId = requestedId || nextId(next, `R${revision}-${index + 1}`);
350
+ if (newId.length > 16)
351
+ return fail(REPLAN_CODES.INVALID_SUBTASK, `子任务 id 最长 16 个字符:${newId}`);
352
+ if (orderMap(next).has(newId))
353
+ return fail(REPLAN_CODES.INVALID_SUBTASK, `子任务 id 重复:${newId}`);
354
+ const department = raw.department === undefined ? 'engineering' : replanDepartment(raw.department);
355
+ if (department === null) {
356
+ return fail(REPLAN_CODES.INVALID_SUBTASK, `newSubtask.department 不是合法部门:${String(raw.department)}`);
357
+ }
358
+ const fieldError = replanFieldError(raw);
359
+ if (fieldError)
360
+ return fail(REPLAN_CODES.INVALID_SUBTASK, `newSubtask 字段不合规:${fieldError}`);
361
+ const goal = typeof raw.objective === 'string' ? raw.objective.trim() : '';
362
+ const title = typeof raw.title === 'string' ? raw.title.trim() : '';
363
+ if (!goal || !title) {
364
+ return fail(REPLAN_CODES.INVALID_SUBTASK, 'newSubtask 至少需要 title 与 objective');
365
+ }
366
+ let stage = next.stages.find((item) => item?.id === stageId);
367
+ if (!stage) {
368
+ if (next.stages.length >= MAX_STAGES) {
369
+ return fail(REPLAN_CODES.GRAPH_INVALID, `新增阶段会超过上限 ${MAX_STAGES}`);
370
+ }
371
+ stage = {
372
+ id: stageId,
373
+ name: `重规划修订 r${revision}`,
374
+ goal: truncate(reason, 400),
375
+ checkpoint: '只执行本轮新增/替换的项;旧行保留为已重规划,不再调度。',
376
+ subtasks: [],
377
+ };
378
+ next.stages.push(stage);
379
+ }
380
+ const subtask = {
381
+ id: newId,
382
+ title: truncate(title, 200),
383
+ department,
384
+ role: truncate(String(raw.role ?? '执行工程师'), 200),
385
+ objective: truncate(goal, 2000),
386
+ method: Array.isArray(raw.method) && raw.method.length > 0 ? raw.method.map((item) => truncate(String(item), 800)) : ['按目标直接执行'],
387
+ inputs: Array.isArray(raw.inputs) ? raw.inputs.map((item) => truncate(String(item), 800)) : [],
388
+ outputs: Array.isArray(raw.outputs) && raw.outputs.length > 0 ? raw.outputs.map((item) => truncate(String(item), 800)) : ['结果说明'],
389
+ dependsOn: Array.isArray(raw.dependsOn) ? raw.dependsOn.map((item) => String(item)) : [],
390
+ acceptance: Array.isArray(raw.acceptance) && raw.acceptance.length > 0
391
+ ? raw.acceptance.map((item) => truncate(String(item), 800))
392
+ : ['复述完成的工作并给出可核对证据'],
393
+ risk: truncate(String(raw.risk ?? '需求变更后新增,原计划未覆盖'), 1000),
394
+ insertedBy: 'replan',
395
+ replannedReason: truncate(String(raw.reason ?? reason), MAX_REPLAN_REASON_CHARS),
396
+ };
397
+ stage.subtasks.push(subtask);
398
+ added.push({
399
+ subtaskId: newId,
400
+ stageId,
401
+ title: subtask.title,
402
+ department: subtask.department,
403
+ role: subtask.role,
404
+ replaces: null,
405
+ });
406
+ }
407
+ if (marks.length === 0 && added.length === 0) {
408
+ return fail(REPLAN_CODES.NO_CHANGES, '没有产生任何重规划变更;如果原计划仍然有效,请直接 dispatch');
409
+ }
410
+ const graphErrors = checkReplanGraph(next);
411
+ if (graphErrors.length > 0) {
412
+ return fail(REPLAN_CODES.GRAPH_INVALID, `修订后的计划不合法:${graphErrors.slice(0, 5).join(';')}`);
413
+ }
414
+ return {
415
+ ok: true,
416
+ payload: {
417
+ kind: 'workplan-replan',
418
+ version: PLAN_VERSION,
419
+ planId,
420
+ revision,
421
+ reason,
422
+ at,
423
+ plan: next,
424
+ marks,
425
+ added,
426
+ },
427
+ };
428
+ }
429
+ /**
430
+ * 把重规划标记落到状态数组。实时与回放共用,且幂等。
431
+ *
432
+ * 旧行:`closure:'replanned'` + `status:'pending'`(用于展示「待重规划」,不参与
433
+ * 调度/计数);`replannedFrom` 保留改判前状态,便于审计。新行:pending。
434
+ */
435
+ export function applyReplanStatuses(statuses, payload) {
436
+ let next = Array.isArray(statuses) ? statuses : [];
437
+ const revision = Number(payload.revision) || 1;
438
+ for (const mark of payload.marks ?? []) {
439
+ const current = next.find((item) => item?.subtaskId === mark.subtaskId);
440
+ if (!current)
441
+ continue;
442
+ try {
443
+ next = applyStatus(next, mark.subtaskId, {
444
+ status: 'pending',
445
+ progress: 0,
446
+ summary: truncate(`已重规划:${mark.reason}`, 3000),
447
+ error: null,
448
+ closure: 'replanned',
449
+ replannedReason: mark.reason,
450
+ replannedAt: payload.at,
451
+ replacedBy: mark.replacedBy,
452
+ replannedFrom: String(current.status ?? 'pending'),
453
+ replannedFromClosure: typeof current.closure === 'string' ? current.closure : null,
454
+ revision,
455
+ updatedBy: 'agent',
456
+ });
457
+ }
458
+ catch {
459
+ // 单个畸形历史行不应中断整次重规划回放;其余行照常应用。
460
+ }
461
+ }
462
+ for (const added of payload.added ?? []) {
463
+ if (next.some((item) => item?.subtaskId === added.subtaskId))
464
+ continue;
465
+ next = [
466
+ ...next,
467
+ {
468
+ subtaskId: added.subtaskId,
469
+ stageId: added.stageId,
470
+ title: added.title,
471
+ department: added.department,
472
+ role: added.role,
473
+ status: 'pending',
474
+ progress: 0,
475
+ childId: null,
476
+ startedAt: null,
477
+ finishedAt: null,
478
+ summary: '',
479
+ error: null,
480
+ closure: 'pending',
481
+ insertedBy: 'replan',
482
+ replaces: added.replaces,
483
+ planRevision: revision,
484
+ },
485
+ ];
486
+ }
487
+ /*
488
+ * [1.11.1] D-13:cancel 不能把下游留在 pending。
489
+ *
490
+ * 旧实现只把被取消的行标成 replanned;下游既没 blocked 也没错误码,
491
+ * 调度器判定「依赖未完成」后永远不再派发——用户看到的是「卡住但没有任何原因」。
492
+ * 这里按依赖图做传递闭包:直接下游的 blockedBy 指向被取消的上游(或已阻塞的
493
+ * 中间行),间接下游的 error 必须回溯到根源取消项与取消原因,而不是只说
494
+ * 「上游 B 阻塞」。实时路径与回放路径共用本函数,因此刷新后结论一致。
495
+ */
496
+ const cancelled = new Map();
497
+ for (const mark of payload.marks ?? []) {
498
+ if (mark.action !== 'cancel')
499
+ continue;
500
+ cancelled.set(String(mark.subtaskId), String(mark.reason ?? payload.reason ?? ''));
501
+ }
502
+ if (cancelled.size > 0 && payload.plan) {
503
+ const deps = new Map();
504
+ const order = [];
505
+ for (const { subtask } of flattenSubtasks(payload.plan)) {
506
+ const id = String(subtask?.id ?? '');
507
+ if (!id)
508
+ continue;
509
+ deps.set(id, Array.isArray(subtask.dependsOn) ? subtask.dependsOn.map(String) : []);
510
+ order.push(id);
511
+ }
512
+ const cascaded = new Map();
513
+ for (const id of order) {
514
+ if (cancelled.has(id))
515
+ continue;
516
+ const direct = (deps.get(id) ?? []).filter((dep) => cancelled.has(dep));
517
+ if (direct.length > 0)
518
+ cascaded.set(id, { direct: direct[0], roots: new Set(direct) });
519
+ }
520
+ let grew = true;
521
+ while (grew) {
522
+ grew = false;
523
+ for (const id of order) {
524
+ if (cancelled.has(id) || cascaded.has(id))
525
+ continue;
526
+ const direct = (deps.get(id) ?? []).filter((dep) => cascaded.has(dep));
527
+ if (direct.length === 0)
528
+ continue;
529
+ const roots = new Set();
530
+ for (const dep of direct) {
531
+ for (const root of cascaded.get(dep)?.roots ?? [])
532
+ roots.add(root);
533
+ }
534
+ cascaded.set(id, { direct: direct[0], roots });
535
+ grew = true;
536
+ }
537
+ }
538
+ for (const [id, info] of cascaded) {
539
+ const current = next.find((item) => item?.subtaskId === id);
540
+ if (!current || current.closure === 'replanned')
541
+ continue;
542
+ if (current.status !== 'pending')
543
+ continue;
544
+ const rootText = [...info.roots].join('、');
545
+ const cause = [...info.roots]
546
+ .map((root) => cancelled.get(root))
547
+ .filter((value) => value && value.length > 0)[0] ?? String(payload.reason ?? '');
548
+ try {
549
+ next = applyStatus(next, id, {
550
+ status: 'blocked',
551
+ closure: 'blocked',
552
+ blockedBy: [{ id: info.direct, reason: `上游 ${info.direct} 因重规划取消而无法完成` }],
553
+ error: `依赖链上游 ${rootText} 已被重规划取消(取消原因:${cause || '未填写'}),本项无法继续;请用 dsh_workplan_replan(action=replace) 重新安排,或显式 cancel 它。`,
554
+ updatedBy: 'system',
555
+ revision,
556
+ });
557
+ }
558
+ catch {
559
+ // 单行冲突不中断回放;下一轮 readiness 仍会把悬挂项拦在交付门外。
560
+ }
561
+ }
562
+ }
563
+ return next;
564
+ }
565
+ /** durable `workplan-replan` 消息:正文 + 一行 JSON 载荷。 */
566
+ export function buildReplanMessage(payload) {
567
+ const changed = payload.marks.map((mark) => `${mark.subtaskId}→${mark.replacedBy.length ? mark.replacedBy.join('、') : '撤销'}`);
568
+ const summary = truncate(`【重规划 r${payload.revision}】${changed.join(',') || '新增子任务'}`, 300);
569
+ const lines = [
570
+ summary,
571
+ '',
572
+ `原因:${payload.reason}`,
573
+ '旧行保留为已重规划(不计入剩余项、不再调度);新行按 pending 进入下一轮。',
574
+ '',
575
+ REPLAN_MARKER_BEGIN,
576
+ JSON.stringify(payload),
577
+ REPLAN_MARKER_END,
578
+ ];
579
+ return makeUserMessage(lines.join('\n'), { kind: 'workplan-replan', form: 'notice', summary });
580
+ }
581
+ export function parseReplanMessage(message) {
582
+ const text = messageText(message);
583
+ const begin = text.indexOf(REPLAN_MARKER_BEGIN);
584
+ const end = text.indexOf(REPLAN_MARKER_END);
585
+ if (begin < 0 || end <= begin)
586
+ return null;
587
+ const body = text.slice(begin + REPLAN_MARKER_BEGIN.length, end).trim();
588
+ try {
589
+ const payload = JSON.parse(body);
590
+ if (!isRecord(payload) || payload.kind !== 'workplan-replan')
591
+ return null;
592
+ if (!payload.plan || !Array.isArray(payload.marks) || !Array.isArray(payload.added))
593
+ return null;
594
+ return payload;
595
+ }
596
+ catch {
597
+ return null;
598
+ }
599
+ }
600
+ /** 计划定义里被重规划替换/撤销的行数;用于分母(definedSubtaskCount)。 */
601
+ export function supersededSubtaskCount(plan) {
602
+ try {
603
+ return flattenSubtasks(plan).filter((entry) => Boolean(entry.subtask?.supersededAt)).length;
604
+ }
605
+ catch {
606
+ return 0;
607
+ }
608
+ }
609
+ /* ------------------------------------------------------------------------- *
610
+ * 执行中收到需求变更(C-12):先记录、再通知,绝不静默丢弃。
611
+ * ------------------------------------------------------------------------- */
612
+ export const CHANGE_MARKER_BEGIN = '<!-- DSH-WORKPLAN-CHANGE:BEGIN -->';
613
+ export const CHANGE_MARKER_END = '<!-- DSH-WORKPLAN-CHANGE:END -->';
614
+ /**
615
+ * durable「执行中收到变更」记录。
616
+ *
617
+ * 这不是一条普通的用户消息:它把变更原文与序号写进会话,回放时据此恢复
618
+ * `record.changeRequest`。模型看到的正文只做三件事——确认没丢、说明本轮不会
619
+ * 打断正在跑的子任务、给出落实方式(replan / update)。
620
+ */
621
+ export function buildChangeRequestMessage(payload, context = {}) {
622
+ const active = Array.isArray(context?.activeSubtasks) ? context.activeSubtasks : [];
623
+ const afterRound = context?.afterRound === true;
624
+ const lines = [
625
+ afterRound
626
+ ? `【需求变更待落实 #${payload.seq}】上一轮执行中记录的要求还没有落进计划,不能静默收尾。`
627
+ : `【需求变更已记录 #${payload.seq}】本轮计划正在执行,这条变更没有被丢弃。`,
628
+ '',
629
+ `变更内容:${truncate(payload.text, 1200)}`,
630
+ active.length > 0
631
+ ? `正在执行:${active.slice(0, 6).join('、')}(不会被中途改写;它们的产物仍然有效)`
632
+ : '没有正在跑的子任务。',
633
+ '',
634
+ afterRound ? '落实方式(现在就处理,不要启动新一轮计划把它盖掉):' : '落实方式(本轮派发结束后执行,不要静默收尾):',
635
+ '1. 变更影响范围:调用 dsh_workplan_replan,用 cancel/replace/add 逐项说明受影响的子任务;旧行会保留为「已重规划」并可追溯。',
636
+ '2. 只是补充说明、不改范围:调用 dsh_workplan_update 把说明写进对应子任务的 note。',
637
+ '3. 变更尚未明确:先向用户确认,再重规划;不要用旧计划直接交付。',
638
+ '',
639
+ CHANGE_MARKER_BEGIN,
640
+ JSON.stringify(payload),
641
+ CHANGE_MARKER_END,
642
+ ];
643
+ return makeUserMessage(lines.join('\n'), {
644
+ kind: 'workplan-change',
645
+ form: 'notice',
646
+ summary: truncate(`需求变更已记录 #${payload.seq}`, 200),
647
+ });
648
+ }
649
+ export function parseChangeRequestMessage(message) {
650
+ const text = messageText(message);
651
+ const begin = text.indexOf(CHANGE_MARKER_BEGIN);
652
+ const end = text.indexOf(CHANGE_MARKER_END);
653
+ if (begin < 0 || end <= begin)
654
+ return null;
655
+ try {
656
+ const payload = JSON.parse(text.slice(begin + CHANGE_MARKER_BEGIN.length, end).trim());
657
+ if (!isRecord(payload) || payload.kind !== 'workplan-change')
658
+ return null;
659
+ if (typeof payload.text !== 'string' || !payload.text.trim())
660
+ return null;
661
+ return {
662
+ kind: 'workplan-change',
663
+ planId: String(payload.planId ?? ''),
664
+ seq: Number.isInteger(Number(payload.seq)) ? Number(payload.seq) : 1,
665
+ at: Number(payload.at) || Date.now(),
666
+ turn: Number.isInteger(Number(payload.turn)) ? Number(payload.turn) : null,
667
+ text: truncate(payload.text, 4000),
668
+ };
669
+ }
670
+ catch {
671
+ return null;
672
+ }
673
+ }
674
+ /** 从计划定义里读重规划修订号(写入时放在 plan.revision)。 */
675
+ export function planRevisionOf(plan) {
676
+ const revision = Number(plan?.revision ?? 0);
677
+ return Number.isFinite(revision) && revision > 0 ? revision : 0;
678
+ }