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