dsh-workplan 1.11.0 → 1.12.0

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,749 @@
1
+ /**
2
+ * Structured task understanding, department matching and anchor deviation check
3
+ * (T10 / M1 + M2, 1.12.0).
4
+ *
5
+ * Why this module exists
6
+ * ----------------------
7
+ * Before 1.12.0 the planner was a single model call:
8
+ *
9
+ * user task -> model -> JSON plan -> twelve-value enum check -> dispatch
10
+ *
11
+ * `validatePlan` only asked "is `department` one of the twelve keys?". It had no
12
+ * access to the user's original words, no notion of what a department can do,
13
+ * and no way to notice that a subtask had drifted away from the request. The T4
14
+ * diagnosis proved the consequence with a counter-example: a picture-book task
15
+ * carrying a penetration-testing subtask still validated `ok:true`.
16
+ *
17
+ * This module adds the three deterministic stages the acceptance criterion asks
18
+ * for, *after* the model produces its plan and *before* anything is dispatched:
19
+ *
20
+ * 1. extract — pull hard requirements out of the user's own text
21
+ * (versions, counts, dates, paths, ids, numeric bounds,
22
+ * explicit negations, pronoun references, contradictions);
23
+ * 2. match — score every subtask against the department capability
24
+ * catalog and explain the score with the exact keywords hit;
25
+ * 3. check — compare the plan (and the model's own restatement) against the
26
+ * read-only anchor, and report every dropped hard element.
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.
32
+ *
33
+ * Failure policy (why not everything blocks)
34
+ * ------------------------------------------
35
+ * A false rejection is worse than a warning: it turns a valid task into a
36
+ * degraded plan. Only contradictions strong enough to be wrong in any reading
37
+ * are blocking:
38
+ *
39
+ * - a hard anchor (version / date / count / path / id / numeric bound) that
40
+ * exists in the user text but appears nowhere in the plan;
41
+ * - a subtask assigned to a guarded department (security/legal/finance/
42
+ * operations) whose domain vocabulary appears only in the subtask and never
43
+ * in the user's request, with no shared content token at all.
44
+ *
45
+ * Pronouns without context and contradictory requirements are reported as
46
+ * warnings, never as silent passes: the plan message tells the main Agent to
47
+ * clarify before dispatch. All thresholds are named constants so a test can pin
48
+ * them instead of relying on prose.
49
+ */
50
+ import { createHash } from 'node:crypto';
51
+ import { DEPARTMENT_CAPABILITIES, DEPARTMENT_INTRUSION_GUARDED, departmentCapability, keywordHit, matchDepartmentKeywords, scoreDepartments, } from './departments.js';
52
+ export const UNDERSTANDING_AUDIT_VERSION = 1;
53
+ /** Same cap the planner prompt uses for the task text. */
54
+ export const MAX_TASK_ANCHOR_CHARS = 16000;
55
+ /** Enough to cover a dense six-part request without turning the audit into a dump. */
56
+ export const MAX_TASK_ELEMENTS = 40;
57
+ /** A plan with more subtasks than this cannot exist (`MAX_SUBTASKS`), kept local to avoid a cycle. */
58
+ export const MAX_AUDITED_SUBTASKS = 15;
59
+ /**
60
+ * A mismatch is blocking when the chosen department has zero supporting
61
+ * keywords and another department has at least this many. Three is high enough
62
+ * that a single incidental word cannot trigger it.
63
+ */
64
+ export const MISMATCH_BLOCKING_SCORE = 3;
65
+ const NEGATION_PATTERN = /(?:不要|禁止|不得|严禁|不能|不可|切勿|避免)\s*([^\s,。;、,.;:!?!?\n]{1,28})/g;
66
+ const QUANTITY_PATTERN = /(?:最多|至少|不超过|不能超过|上限|下限|必须|只能|只允许|仅)\s*([^,。;;!?!?\n]{1,40})/g;
67
+ const HARD_QUANTITY_PREFIX = /^(?:最多|至少|不超过|不能超过|上限|下限)/;
68
+ /**
69
+ * Normalise for "does the plan still mention this literal" checks. It strips
70
+ * whitespace and punctuation only — never Chinese characters, digits or latin
71
+ * letters — so a match cannot be manufactured by dropping content.
72
+ */
73
+ export function normalizeForMatch(value) {
74
+ return String(value ?? '')
75
+ .replace(/[\s\u3000]+/g, '')
76
+ .replace(/[%]/g, '%')
77
+ .replace(/[,。;、!?"'“”‘’()()【】\[\]<>《》]/g, '')
78
+ .toLowerCase();
79
+ }
80
+ function clauseOf(text, index, length) {
81
+ const start = Math.max(0, index - 36);
82
+ const end = Math.min(text.length, index + length + 36);
83
+ return text.slice(start, end).replace(/\s+/g, ' ').trim();
84
+ }
85
+ function pushElement(target, seen, element) {
86
+ const key = `${element.kind}|${normalizeForMatch(element.value)}`;
87
+ if (!element.value || seen.has(key))
88
+ return;
89
+ seen.add(key);
90
+ target.push(element);
91
+ }
92
+ function collectMatches(text, pattern, make) {
93
+ const found = [];
94
+ const seen = new Set();
95
+ // A local clone keeps the shared literal's lastIndex from leaking between calls.
96
+ const regex = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`);
97
+ let match;
98
+ while ((match = regex.exec(text)) !== null) {
99
+ const element = make(match);
100
+ if (element)
101
+ pushElement(found, seen, element);
102
+ if (match.index === regex.lastIndex)
103
+ regex.lastIndex += 1;
104
+ }
105
+ return found;
106
+ }
107
+ function splitClauses(text) {
108
+ return text
109
+ .split(/[。;;\n!!??]+/)
110
+ .map((clause) => clause.trim())
111
+ .filter((clause) => clause.length > 0);
112
+ }
113
+ function cjkBigrams(text) {
114
+ const clean = String(text ?? '').replace(/[^\u4e00-\u9fff]+/g, ' ');
115
+ const bigrams = new Set();
116
+ for (const run of clean.split(/\s+/)) {
117
+ for (let i = 0; i + 2 <= run.length; i += 1) {
118
+ bigrams.add(run.slice(i, i + 2));
119
+ }
120
+ }
121
+ return bigrams;
122
+ }
123
+ const STOP_BIGRAMS = new Set([
124
+ '的是', '我们', '你们', '他们', '这个', '那个', '这些', '那些', '一个', '已经',
125
+ '可以', '需要', '必须', '应该', '进行', '以及', '或者', '但是', '因为', '所以',
126
+ '如果', '没有', '不是', '就是', '通过', '对于', '时候', '现在', '问题', '要求',
127
+ '这里', '那里', '同时', '并且', '而且', '还有', '全部', '所有', '任何', '其他',
128
+ ]);
129
+ function contentBigrams(text) {
130
+ const result = new Set();
131
+ for (const bigram of cjkBigrams(text)) {
132
+ if (!STOP_BIGRAMS.has(bigram))
133
+ result.add(bigram);
134
+ }
135
+ return result;
136
+ }
137
+ function intersectionSize(a, b) {
138
+ let count = 0;
139
+ for (const value of a)
140
+ if (b.has(value))
141
+ count += 1;
142
+ return count;
143
+ }
144
+ const SELF_CONTAINED_REFERENCE = /^(?:这个|那个|该|上述|前述|这些|那些|上一项|前一项|前者|后者)/;
145
+ /**
146
+ * Extract hard requirements and ambiguity signals from the user's own words.
147
+ *
148
+ * Deliberately literal: no stemming, no synonyms, no model. The cost is that a
149
+ * heavily paraphrased plan may look lossy; the benefit is that every finding can
150
+ * be checked by searching the two strings involved.
151
+ */
152
+ export function extractTaskElements(taskText) {
153
+ const text = typeof taskText === 'string' ? taskText.trim() : '';
154
+ const elements = [];
155
+ const seen = new Set();
156
+ // Order matters: `MAX_TASK_ELEMENTS` keeps the highest-signal kinds first.
157
+ for (const element of collectMatches(text, /\bv?(\d+\.\d+(?:\.\d+)?)\b/g, (match) => ({
158
+ kind: 'version',
159
+ value: match[0].replace(/^v/i, ''),
160
+ evidence: clauseOf(text, match.index, match[0].length),
161
+ hard: true,
162
+ })))
163
+ pushElement(elements, seen, element);
164
+ for (const element of collectMatches(text, /\b(?:20\d{2})[-/年.]\d{1,2}(?:[-/月.]\d{1,2}日?)?/g, (match) => ({
165
+ kind: 'date',
166
+ value: match[0],
167
+ evidence: clauseOf(text, match.index, match[0].length),
168
+ hard: true,
169
+ })))
170
+ pushElement(elements, seen, element);
171
+ for (const element of collectMatches(text, /\b\d{1,2}月\d{1,2}日/g, (match) => ({
172
+ kind: 'date',
173
+ value: match[0],
174
+ evidence: clauseOf(text, match.index, match[0].length),
175
+ hard: true,
176
+ })))
177
+ pushElement(elements, seen, element);
178
+ for (const element of collectMatches(text, /\b(?:T|D|U|S|Q|P|E|R|C|M|H|W|XB)-?\d{1,3}\b/g, (match) => ({
179
+ kind: 'id',
180
+ value: match[0],
181
+ evidence: clauseOf(text, match.index, match[0].length),
182
+ hard: true,
183
+ })))
184
+ pushElement(elements, seen, element);
185
+ for (const element of collectMatches(text, /[A-Za-z0-9_./-]+\.(?:ts|tsx|js|mjs|cjs|json|md|yml|yaml|patch|log|csv|py|html|css|svg|tgz)\b/g, (match) => ({
186
+ kind: 'path',
187
+ value: match[0],
188
+ evidence: clauseOf(text, match.index, match[0].length),
189
+ hard: true,
190
+ })))
191
+ pushElement(elements, seen, element);
192
+ for (const element of collectMatches(text, /\b\d+(?:\.\d+)?\s*(?:个|页|条|项|次|份|张|台|人日|人|天|小时|分钟|秒|字|%|万|亿|KB|MB|GB)/gi, (match) => ({
193
+ kind: 'count',
194
+ value: match[0].replace(/\s+/g, ''),
195
+ evidence: clauseOf(text, match.index, match[0].length),
196
+ hard: true,
197
+ })))
198
+ pushElement(elements, seen, element);
199
+ for (const element of collectMatches(text, QUANTITY_PATTERN, (match) => {
200
+ const head = match[0];
201
+ return {
202
+ kind: 'quantity',
203
+ value: head.replace(/\s+/g, ''),
204
+ evidence: clauseOf(text, match.index, match[0].length),
205
+ hard: HARD_QUANTITY_PREFIX.test(head),
206
+ };
207
+ }))
208
+ pushElement(elements, seen, element);
209
+ /*
210
+ * Negations are recorded for readability but are not blocking by themselves.
211
+ * A negation's object often includes the verb ("不要修改业务代码"), so a
212
+ * legitimate synonym ("不得改动业务代码") would be a false deviation. When the
213
+ * object is a path, id or number it is already covered by the hard kinds
214
+ * above, so nothing checkable is lost.
215
+ */
216
+ for (const element of collectMatches(text, NEGATION_PATTERN, (match) => ({
217
+ kind: 'negation',
218
+ value: `禁止:${match[1]}`,
219
+ evidence: clauseOf(text, match.index, match[0].length),
220
+ hard: false,
221
+ })))
222
+ pushElement(elements, seen, element);
223
+ const deliverableClauses = splitClauses(text)
224
+ .filter((clause) => /(?:交付|产出|输出|发布|提供|生成|给出)/.test(clause))
225
+ .slice(0, 10);
226
+ return {
227
+ textLength: text.length,
228
+ elements: elements.slice(0, MAX_TASK_ELEMENTS),
229
+ hardCount: elements.filter((element) => element.hard).length,
230
+ references: extractReferences(text),
231
+ conflicts: extractConflicts(text),
232
+ deliverableClauses,
233
+ };
234
+ }
235
+ function extractReferences(text) {
236
+ if (!text)
237
+ return [];
238
+ const references = [];
239
+ const seen = new Set();
240
+ const inlineTokens = ['这个', '那个', '该', '上述', '前述', '这些', '那些', '上一项', '前一项', '前者', '后者'];
241
+ for (const token of inlineTokens) {
242
+ let index = text.indexOf(token);
243
+ while (index >= 0) {
244
+ const before = text[index - 1] ?? '';
245
+ if (before === '其') {
246
+ index = text.indexOf(token, index + token.length);
247
+ continue;
248
+ }
249
+ if (!seen.has(token)) {
250
+ const after = text.slice(index + token.length, index + token.length + 6);
251
+ /*
252
+ * 「该」 is also a modal ("该怎么做"), which is not a reference at all.
253
+ * Skipping it keeps a real task from being blocked by a false pronoun
254
+ * while 「该模块」 still resolves inline.
255
+ */
256
+ if (token === '该' && /^(?:怎么|如何|怎样|是否|做|不|应)/.test(after)) {
257
+ index = text.indexOf(token, index + token.length);
258
+ continue;
259
+ }
260
+ seen.add(token);
261
+ const selfContained = SELF_CONTAINED_REFERENCE.test(token) && /^[\u4e00-\u9fff]{2}/.test(after);
262
+ references.push({
263
+ token,
264
+ resolvedBy: selfContained ? 'inline-noun' : 'none',
265
+ resolved: selfContained,
266
+ evidence: clauseOf(text, index, token.length),
267
+ });
268
+ }
269
+ index = text.indexOf(token, index + token.length);
270
+ }
271
+ }
272
+ // Bare 「它」 is the real ambiguity: it can only be resolved by context.
273
+ for (let index = text.indexOf('它'); index >= 0; index = text.indexOf('它', index + 1)) {
274
+ const before = text[index - 1] ?? '';
275
+ if (before === '其')
276
+ continue;
277
+ if (!seen.has('它')) {
278
+ seen.add('它');
279
+ references.push({
280
+ token: '它',
281
+ resolvedBy: 'none',
282
+ resolved: false,
283
+ evidence: clauseOf(text, index, 1),
284
+ });
285
+ }
286
+ }
287
+ // Option letters are only references when the text also talks about options.
288
+ if (/(?:选|选项|方案|可选|建议)/.test(text)) {
289
+ const option = /(?:^|[^A-Za-z])([A-D])(?![A-Za-z])/.exec(text);
290
+ if (option && !seen.has(option[1])) {
291
+ seen.add(option[1]);
292
+ references.push({
293
+ token: option[1],
294
+ resolvedBy: 'none',
295
+ resolved: false,
296
+ evidence: clauseOf(text, option.index, option[0].length),
297
+ });
298
+ }
299
+ }
300
+ return references;
301
+ }
302
+ function extractConflicts(text) {
303
+ const conflicts = [];
304
+ const seen = new Set();
305
+ const add = (conflict) => {
306
+ const key = `${conflict.kind}|${normalizeForMatch(conflict.a)}|${normalizeForMatch(conflict.b)}`;
307
+ if (seen.has(key))
308
+ return;
309
+ seen.add(key);
310
+ conflicts.push(conflict);
311
+ };
312
+ const open = /默认(?:展开|打开|显示)/.exec(text);
313
+ const closed = /默认(?:不展开|不打开|收起|折叠|关闭|隐藏)/.exec(text);
314
+ if (open && closed) {
315
+ add({
316
+ kind: 'default-state',
317
+ a: open[0],
318
+ b: closed[0],
319
+ reason: '同一默认状态被同时要求展开与收起,二选一必须由用户决定',
320
+ });
321
+ }
322
+ const only = /只(?:改|修改|动|做)\s*([^\s,。;、,;!?!?]{1,24})/.exec(text);
323
+ const also = /(?:同时|还要|也要|并且|另外)(?:改|修改|动|做)\s*([^\s,。;、,;!?!?]{1,24})/.exec(text);
324
+ if (only && also && normalizeForMatch(only[1]) !== normalizeForMatch(also[1])) {
325
+ add({
326
+ kind: 'scope',
327
+ a: only[0],
328
+ b: also[0],
329
+ reason: `范围冲突:既要求只处理「${only[1]}」,又要求处理「${also[1]}」`,
330
+ });
331
+ }
332
+ const clauses = splitClauses(text);
333
+ for (const forbidClause of clauses) {
334
+ const forbid = /(?:不要|禁止|不得|严禁)\s*(?:修改|改动|改|动|删除|移除)\s*([^\s,。;、,;!?!?]{1,24})/.exec(forbidClause);
335
+ if (!forbid)
336
+ continue;
337
+ for (const requireClause of clauses) {
338
+ if (requireClause === forbidClause)
339
+ continue;
340
+ const require = /(?:必须|需要|务必|要)\s*(?:修改|改动|改|动|删除|移除)\s*([^\s,。;、,;!?!?]{1,24})/.exec(requireClause);
341
+ if (!require)
342
+ continue;
343
+ const a = normalizeForMatch(forbid[1]);
344
+ const b = normalizeForMatch(require[1]);
345
+ const overlap = a === b || a.includes(b) || b.includes(a)
346
+ || intersectionSize(contentBigrams(forbid[1]), contentBigrams(require[1])) > 0;
347
+ if (overlap) {
348
+ add({
349
+ kind: 'polarity',
350
+ a: forbid[0],
351
+ b: require[0],
352
+ reason: `同一对象「${forbid[1]}」既被禁止修改又被要求修改`,
353
+ });
354
+ }
355
+ }
356
+ }
357
+ for (const clause of clauses) {
358
+ const change = /(?:改成|改为|设为|调整为|更新为)\s*([^\s,。;、,;!?!?]{1,24})/.exec(clause);
359
+ if (!change)
360
+ continue;
361
+ for (const otherClause of clauses) {
362
+ if (otherClause === clause)
363
+ continue;
364
+ const keep = /(?:保持|保持不变|仍为|保留)\s*([^\s,。;、,;!?!?]{1,24})/.exec(otherClause);
365
+ if (!keep)
366
+ continue;
367
+ if (normalizeForMatch(change[1]) === normalizeForMatch(keep[1]))
368
+ continue;
369
+ const shared = intersectionSize(contentBigrams(clause), contentBigrams(otherClause));
370
+ if (shared === 0)
371
+ continue;
372
+ add({
373
+ kind: 'value',
374
+ a: change[0],
375
+ b: keep[0],
376
+ reason: `同一对象被要求改成「${change[1]}」又要求保持「${keep[1]}」`,
377
+ });
378
+ }
379
+ }
380
+ return conflicts.slice(0, 8);
381
+ }
382
+ function subtaskText(subtask) {
383
+ const parts = [
384
+ subtask?.title,
385
+ subtask?.role,
386
+ subtask?.objective,
387
+ ...(Array.isArray(subtask?.method) ? subtask.method : []),
388
+ ...(Array.isArray(subtask?.inputs) ? subtask.inputs : []),
389
+ ...(Array.isArray(subtask?.outputs) ? subtask.outputs : []),
390
+ ...(Array.isArray(subtask?.acceptance) ? subtask.acceptance : []),
391
+ ];
392
+ return parts
393
+ .filter((part) => typeof part === 'string' && part.trim() !== '')
394
+ .join(' ');
395
+ }
396
+ function flattenPlanSubtasks(plan) {
397
+ const stages = Array.isArray(plan?.stages) ? plan.stages : [];
398
+ const subtasks = [];
399
+ for (const stage of stages) {
400
+ for (const subtask of Array.isArray(stage?.subtasks) ? stage.subtasks : []) {
401
+ subtasks.push(subtask);
402
+ if (subtasks.length >= MAX_AUDITED_SUBTASKS)
403
+ return subtasks;
404
+ }
405
+ }
406
+ return subtasks;
407
+ }
408
+ /**
409
+ * Explain one department choice with the catalog keywords that support it.
410
+ *
411
+ * `verdict` is intentionally coarse:
412
+ * - `fit` — the chosen department has at least one matching keyword;
413
+ * - `weak` — no keyword anywhere; insufficient evidence, not an error;
414
+ * - `mismatch`— the chosen department has zero evidence while another has a
415
+ * strong one (>= MISMATCH_BLOCKING_SCORE).
416
+ */
417
+ export function departmentFit(subtask, anchorText = '') {
418
+ const department = typeof subtask?.department === 'string' ? subtask.department : '';
419
+ const capability = departmentCapability(department);
420
+ const text = subtaskText(subtask);
421
+ const matched = capability ? capability.keywords.filter((keyword) => keywordHit(text, keyword)) : [];
422
+ const anchorMatched = capability && anchorText.trim() !== ''
423
+ ? capability.keywords.filter((keyword) => keywordHit(anchorText, keyword))
424
+ : [];
425
+ const scores = scoreDepartments(text).filter((entry) => entry.id !== department);
426
+ const best = scores.length > 0 && scores[0].score > 0 ? scores[0] : null;
427
+ const chosenScore = matched.length;
428
+ let intrusion = false;
429
+ if (capability && DEPARTMENT_INTRUSION_GUARDED.includes(department) && chosenScore > 0 && anchorText.trim() !== '') {
430
+ const anchorHits = matchDepartmentKeywords(anchorText, department);
431
+ if (anchorHits.length === 0) {
432
+ const overlap = intersectionSize(contentBigrams(text), contentBigrams(anchorText));
433
+ // No shared content bigram at all = the request never talks about this
434
+ // domain. One shared topic word is enough to make it a warning instead.
435
+ intrusion = overlap === 0;
436
+ }
437
+ }
438
+ let verdict = 'fit';
439
+ let reason = '';
440
+ if (!capability) {
441
+ verdict = 'mismatch';
442
+ reason = `未知部门「${department}」,不在 12 个部门目录内`;
443
+ }
444
+ else if (chosenScore === 0 && anchorMatched.length === 0 && best && best.score >= MISMATCH_BLOCKING_SCORE) {
445
+ verdict = 'mismatch';
446
+ reason = `「${capability.zh}」无任何目录关键词命中,而「${best.zh}」命中 ${best.score} 个(${best.matched.slice(0, 4).join('、')})`;
447
+ }
448
+ else if (intrusion) {
449
+ verdict = 'mismatch';
450
+ reason = `「${capability.zh}」领域词(${matched.slice(0, 3).join('、')})只出现在子任务中,用户原要求从未涉及该领域`;
451
+ }
452
+ else if (chosenScore === 0 && anchorMatched.length === 0) {
453
+ verdict = 'weak';
454
+ reason = `「${capability.zh}」在子任务与用户原要求中都没有目录关键词命中,属证据不足(不阻断)`;
455
+ }
456
+ else if (chosenScore === 0) {
457
+ reason = `子任务未命中「${capability.zh}」职责词,但用户原要求命中:${anchorMatched.slice(0, 5).join('、')}`;
458
+ }
459
+ else {
460
+ reason = `命中「${capability.zh}」职责关键词 ${chosenScore} 个:${matched.slice(0, 5).join('、')}`;
461
+ if (anchorMatched.length > 0)
462
+ reason += `;用户原要求也命中:${anchorMatched.slice(0, 5).join('、')}`;
463
+ }
464
+ const declared = typeof subtask?.departmentRationale === 'string'
465
+ ? subtask.departmentRationale.trim().slice(0, 600)
466
+ : '';
467
+ return {
468
+ subtaskId: typeof subtask?.id === 'string' ? subtask.id : '',
469
+ department,
470
+ departmentLabel: capability?.zh ?? department,
471
+ score: chosenScore,
472
+ matched,
473
+ anchorMatched,
474
+ bestAlternative: best
475
+ ? { id: best.id, zh: best.zh, score: best.score, matched: best.matched.slice(0, 5) }
476
+ : null,
477
+ intrusion,
478
+ verdict,
479
+ reason,
480
+ declaredRationale: declared,
481
+ };
482
+ }
483
+ export function buildTaskAnchor(taskText, sourceMessageIds = []) {
484
+ const text = typeof taskText === 'string' ? taskText.trim() : '';
485
+ if (!text)
486
+ return null;
487
+ const ids = Array.isArray(sourceMessageIds)
488
+ ? sourceMessageIds.filter((id) => typeof id === 'string').slice(0, 30)
489
+ : [];
490
+ return {
491
+ text: text.slice(0, MAX_TASK_ANCHOR_CHARS),
492
+ sha256: createHash('sha256').update(text, 'utf8').digest('hex'),
493
+ length: text.length,
494
+ sourceMessageIds: ids,
495
+ };
496
+ }
497
+ function collectPlanText(plan) {
498
+ const understanding = plan?.taskUnderstanding ?? {};
499
+ const parts = [plan?.title];
500
+ for (const key of ['originalRequest', 'deliverable']) {
501
+ if (typeof understanding?.[key] === 'string')
502
+ parts.push(understanding[key]);
503
+ }
504
+ for (const key of ['successCriteria', 'constraints', 'knownFacts', 'unknowns', 'assumptions']) {
505
+ if (Array.isArray(understanding?.[key]))
506
+ parts.push(...understanding[key]);
507
+ }
508
+ for (const stage of Array.isArray(plan?.stages) ? plan.stages : []) {
509
+ for (const key of ['name', 'goal', 'rationale', 'checkpoint']) {
510
+ if (typeof stage?.[key] === 'string')
511
+ parts.push(stage[key]);
512
+ }
513
+ for (const subtask of Array.isArray(stage?.subtasks) ? stage.subtasks : []) {
514
+ parts.push(subtaskText(subtask));
515
+ }
516
+ }
517
+ for (const entry of Array.isArray(plan?.verification) ? plan.verification : []) {
518
+ for (const key of ['item', 'method', 'evidence']) {
519
+ if (typeof entry?.[key] === 'string')
520
+ parts.push(entry[key]);
521
+ }
522
+ }
523
+ return parts.filter((part) => typeof part === 'string').join('\n');
524
+ }
525
+ function elementPresent(planText, element) {
526
+ const haystack = normalizeForMatch(planText);
527
+ if (!haystack)
528
+ return false;
529
+ if (element.kind === 'id') {
530
+ const value = normalizeForMatch(element.value);
531
+ return haystack.includes(value) || haystack.includes(value.replace(/-/g, ''));
532
+ }
533
+ if (element.kind === 'negation') {
534
+ return haystack.includes(normalizeForMatch(element.value.replace(/^禁止:/, '')));
535
+ }
536
+ return haystack.includes(normalizeForMatch(element.value));
537
+ }
538
+ function emptyAudit(anchor, reason) {
539
+ return {
540
+ version: UNDERSTANDING_AUDIT_VERSION,
541
+ anchor,
542
+ stage1: { elements: [], hardCount: 0, references: [], conflicts: [], deliverableClauses: [] },
543
+ stage2: { assignments: [], departmentsUsed: [], mismatches: [] },
544
+ stage3: {
545
+ verdict: 'degraded',
546
+ rewritten: false,
547
+ summaryCoverage: 0,
548
+ droppedFromSummary: [],
549
+ missingHardAnchors: [],
550
+ missingDeliverables: [],
551
+ reasons: [reason],
552
+ },
553
+ };
554
+ }
555
+ /**
556
+ * Run the three stages against one plan.
557
+ *
558
+ * A legacy/replayed plan without the original task text returns a `degraded`
559
+ * audit instead of throwing: replay must keep working, and "cannot check" is
560
+ * not the same as "checked and passed" (which is why the verdict says so).
561
+ */
562
+ export function auditTaskUnderstanding(plan, context = {}) {
563
+ const taskText = typeof context.taskText === 'string' ? context.taskText.trim() : '';
564
+ const anchor = buildTaskAnchor(taskText, context.sourceMessageIds);
565
+ if (!anchor) {
566
+ return emptyAudit(null, '没有用户原文(旧计划/回放),锚点偏离校验降级为不阻断');
567
+ }
568
+ const extracted = extractTaskElements(taskText);
569
+ const planText = collectPlanText(plan);
570
+ const assignments = flattenPlanSubtasks(plan).map((subtask) => departmentFit(subtask, taskText));
571
+ const departmentsUsed = [...new Set(assignments.map((entry) => entry.department))];
572
+ const mismatches = assignments
573
+ .filter((entry) => entry.verdict === 'mismatch')
574
+ .map((entry) => `${entry.subtaskId || '(无 ID)'} → ${entry.departmentLabel}:${entry.reason}`);
575
+ const missingElements = extracted.elements
576
+ .filter((element) => element.hard && !elementPresent(planText, element));
577
+ const missingHardAnchors = missingElements.map((element) => `${element.kind}:${element.value}`);
578
+ const missingDeliverables = extracted.deliverableClauses.filter((clause) => {
579
+ const haystack = normalizeForMatch(planText);
580
+ const bigrams = [...contentBigrams(clause)];
581
+ if (bigrams.length === 0)
582
+ return false;
583
+ const hits = bigrams.filter((bigram) => haystack.includes(bigram)).length;
584
+ return hits < Math.max(1, Math.ceil(bigrams.length * 0.5));
585
+ });
586
+ const originalRequest = typeof plan?.taskUnderstanding?.originalRequest === 'string'
587
+ ? plan.taskUnderstanding.originalRequest
588
+ : '';
589
+ const summaryNorm = normalizeForMatch(originalRequest);
590
+ const anchorNorm = normalizeForMatch(taskText);
591
+ const verbatim = summaryNorm.length > 0 && anchorNorm.includes(summaryNorm);
592
+ const droppedFromSummary = extracted.elements
593
+ .filter((element) => element.hard && !normalizeForMatch(originalRequest).includes(normalizeForMatch(element.value)))
594
+ .map((element) => `${element.kind}:${element.value}`);
595
+ const hardTotal = extracted.elements.filter((element) => element.hard).length;
596
+ const summaryCoverage = hardTotal === 0 ? 1 : (hardTotal - droppedFromSummary.length) / hardTotal;
597
+ const unresolved = extracted.references.filter((reference) => !reference.resolved
598
+ && (typeof context.conversationContext !== 'string' || context.conversationContext.trim() === ''));
599
+ const resolvedByContext = extracted.references.map((reference) => (!reference.resolved
600
+ && typeof context.conversationContext === 'string'
601
+ && context.conversationContext.trim() !== ''
602
+ ? { ...reference, resolved: true, resolvedBy: 'context' }
603
+ : reference));
604
+ const reasons = [];
605
+ let verdict = 'aligned';
606
+ if (missingHardAnchors.length > 0) {
607
+ verdict = 'deviation';
608
+ reasons.push(`用户原要求中的 ${missingHardAnchors.length} 个硬要素在计划中完全缺失:${missingHardAnchors.slice(0, 6).join('、')}`);
609
+ }
610
+ if (mismatches.length > 0) {
611
+ if (verdict === 'aligned')
612
+ verdict = 'deviation';
613
+ reasons.push(`${mismatches.length} 个子任务的部门与用户原要求矛盾:${mismatches.slice(0, 4).join(';')}`);
614
+ }
615
+ if (extracted.conflicts.length > 0) {
616
+ if (verdict === 'aligned')
617
+ verdict = 'needs-clarification';
618
+ reasons.push(`用户要求自相矛盾 ${extracted.conflicts.length} 处:${extracted.conflicts.map((conflict) => conflict.reason).slice(0, 3).join(';')}`);
619
+ }
620
+ if (unresolved.length > 0) {
621
+ if (verdict === 'aligned')
622
+ verdict = 'needs-context';
623
+ reasons.push(`含指代的任务缺少对话上下文:${unresolved.map((reference) => reference.token).join('、')},不应在未澄清前派发`);
624
+ }
625
+ if (verdict === 'aligned') {
626
+ reasons.push(`硬要素 ${hardTotal - missingHardAnchors.length}/${hardTotal} 全部保留;${assignments.length} 个子任务的部门有目录关键词支撑`);
627
+ }
628
+ return {
629
+ version: UNDERSTANDING_AUDIT_VERSION,
630
+ anchor,
631
+ stage1: {
632
+ elements: extracted.elements,
633
+ hardCount: extracted.hardCount,
634
+ references: resolvedByContext,
635
+ conflicts: extracted.conflicts,
636
+ deliverableClauses: extracted.deliverableClauses,
637
+ },
638
+ stage2: { assignments, departmentsUsed, mismatches },
639
+ stage3: {
640
+ verdict,
641
+ rewritten: !verbatim,
642
+ summaryCoverage: Number(summaryCoverage.toFixed(3)),
643
+ droppedFromSummary,
644
+ missingHardAnchors,
645
+ missingDeliverables,
646
+ reasons,
647
+ },
648
+ };
649
+ }
650
+ /**
651
+ * Convert an audit into retry errors.
652
+ *
653
+ * `strict:false` is the rollback switch: every finding becomes a warning and the
654
+ * plan proceeds exactly like 1.11.1. This is what an operator flips if a
655
+ * release starts rejecting legitimate tasks, without reverting code.
656
+ */
657
+ export function validatePlanContext(plan, context = {}) {
658
+ const audit = auditTaskUnderstanding(plan, context);
659
+ const warnings = [];
660
+ const errors = [];
661
+ const strict = context.strict !== false;
662
+ for (const reason of audit.stage3.reasons) {
663
+ if (audit.stage3.verdict === 'aligned')
664
+ continue;
665
+ warnings.push(reason);
666
+ }
667
+ for (const missing of audit.stage3.missingDeliverables) {
668
+ warnings.push(`交付物子句可能未被计划覆盖:${missing}`);
669
+ }
670
+ for (const assignment of audit.stage2.assignments) {
671
+ if (assignment.verdict === 'weak')
672
+ warnings.push(`${assignment.subtaskId} 部门「${assignment.departmentLabel}」证据不足:${assignment.reason}`);
673
+ }
674
+ if (strict) {
675
+ /*
676
+ * A plan must not resolve a contradiction by silently picking a side, and
677
+ * must not guess what 「它」 means. Both need the user, so both block the
678
+ * dispatch under strict mode and degrade to a recorded warning only when
679
+ * the rollback switch is on.
680
+ */
681
+ if (audit.stage3.verdict === 'needs-clarification') {
682
+ errors.push(`CLARIFY: ${audit.stage3.reasons.find((reason) => reason.includes('自相矛盾')) ?? '用户要求存在矛盾,必须先向用户确认'}`);
683
+ }
684
+ if (audit.stage3.verdict === 'needs-context') {
685
+ errors.push(`CONTEXT: ${audit.stage3.reasons.find((reason) => reason.includes('指代')) ?? '任务含指代但缺少对话上下文,必须先向用户确认'}`);
686
+ }
687
+ for (const missing of audit.stage3.missingHardAnchors.slice(0, 6)) {
688
+ errors.push(`DEVIATION: 用户原要求中的硬要素「${missing}」在计划中完全缺失,请补回或说明为什么可以省略`);
689
+ }
690
+ for (const assignment of audit.stage2.assignments) {
691
+ if (assignment.verdict !== 'mismatch')
692
+ continue;
693
+ errors.push(`DEVIATION: 子任务 ${assignment.subtaskId || '(无 ID)'} 分配给「${assignment.departmentLabel}」缺乏依据:${assignment.reason}`);
694
+ if (errors.length >= 12)
695
+ break;
696
+ }
697
+ }
698
+ return { ok: errors.length === 0, errors: errors.slice(0, 12), warnings: warnings.slice(0, 20), audit };
699
+ }
700
+ /**
701
+ * Compact audit kept on the plan message. The full audit (with evidence clauses)
702
+ * stays available from `auditTaskUnderstanding`; the stored copy is trimmed so a
703
+ * 15-subtask plan does not double its own JSON size.
704
+ */
705
+ export function compactUnderstandingAudit(audit) {
706
+ return {
707
+ version: audit.version,
708
+ anchor: audit.anchor
709
+ ? { sha256: audit.anchor.sha256, length: audit.anchor.length, sourceMessageIds: audit.anchor.sourceMessageIds }
710
+ : null,
711
+ stage1: {
712
+ elements: audit.stage1.elements.map((element) => ({ kind: element.kind, value: element.value, hard: element.hard })),
713
+ hardCount: audit.stage1.hardCount,
714
+ references: audit.stage1.references.map((reference) => ({
715
+ token: reference.token,
716
+ resolved: reference.resolved,
717
+ resolvedBy: reference.resolvedBy,
718
+ })),
719
+ conflicts: audit.stage1.conflicts,
720
+ },
721
+ stage2: {
722
+ assignments: audit.stage2.assignments.map((assignment) => ({
723
+ subtaskId: assignment.subtaskId,
724
+ department: assignment.department,
725
+ verdict: assignment.verdict,
726
+ score: assignment.score,
727
+ matched: assignment.matched.slice(0, 5),
728
+ reason: assignment.reason,
729
+ declaredRationale: assignment.declaredRationale,
730
+ })),
731
+ departmentsUsed: audit.stage2.departmentsUsed,
732
+ mismatches: audit.stage2.mismatches,
733
+ },
734
+ stage3: {
735
+ verdict: audit.stage3.verdict,
736
+ rewritten: audit.stage3.rewritten,
737
+ summaryCoverage: audit.stage3.summaryCoverage,
738
+ droppedFromSummary: audit.stage3.droppedFromSummary,
739
+ missingHardAnchors: audit.stage3.missingHardAnchors,
740
+ missingDeliverables: audit.stage3.missingDeliverables,
741
+ reasons: audit.stage3.reasons,
742
+ },
743
+ };
744
+ }
745
+ /**
746
+ * The department catalogue is the contract behind every match above; keep the
747
+ * 12 ids in sync with `DEPARTMENTS` in plan.ts.
748
+ */
749
+ export const UNDERSTANDING_DEPARTMENT_IDS = Object.freeze(DEPARTMENT_CAPABILITIES.map((entry) => entry.id));