dsh-workplan 1.11.1 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1205 @@
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
+ /**
80
+ * [P0-1] Domain coverage threshold.
81
+ *
82
+ * The MS2 run (2026-11-03) measured 11/29 required departments present: plans
83
+ * silently dropped whole domains (design/legal/security/devops) the user's own
84
+ * request names. A single incidental keyword is not evidence of a domain, so a
85
+ * department counts as *implied by the request* only when at least two of its
86
+ * catalogue keywords occur in the user text. Named so tests pin it.
87
+ */
88
+ export const REQUIRED_DEPARTMENT_MIN_HITS = 2
89
+
90
+ /**
91
+ * Wording that turns a missing department into a deliberate exclusion. The plan
92
+ * must say 「不安排<部门>:理由」 in taskUnderstanding.assumptions; silence is
93
+ * what the gate rejects.
94
+ */
95
+ export const DEPARTMENT_EXCLUSION_CUES = /(?:不安排|不需要|未涉及|不涉及|排除|不含|无需|不启用)/
96
+
97
+ /** Hard anchors are the only elements that can fail a plan by themselves. */
98
+ export type TaskElementKind =
99
+ | 'version'
100
+ | 'date'
101
+ | 'count'
102
+ | 'path'
103
+ | 'id'
104
+ | 'quantity'
105
+ | 'negation'
106
+
107
+ export interface TaskElement {
108
+ kind: TaskElementKind
109
+ /** The literal requirement, normalised only for whitespace. */
110
+ value: string
111
+ /** Surrounding clause, for a human reading the audit. */
112
+ evidence: string
113
+ /** Whether dropping this element is a blocking deviation. */
114
+ hard: boolean
115
+ }
116
+
117
+ export interface TaskReference {
118
+ token: string
119
+ /**
120
+ * `context` = an antecedent for this token was actually found in the recent
121
+ * conversation and quoted in `antecedent`; `inline-noun` = e.g. 「这个插件」;
122
+ * `none` = still ambiguous.
123
+ */
124
+ resolvedBy: 'context' | 'inline-noun' | 'none'
125
+ resolved: boolean
126
+ /** The noun phrase taken from the conversation that this token points at. */
127
+ antecedent?: string
128
+ evidence: string
129
+ }
130
+
131
+ export interface TaskConflict {
132
+ kind: 'default-state' | 'scope' | 'polarity' | 'value'
133
+ a: string
134
+ b: string
135
+ reason: string
136
+ }
137
+
138
+ export interface TaskElements {
139
+ textLength: number
140
+ elements: TaskElement[]
141
+ hardCount: number
142
+ references: TaskReference[]
143
+ conflicts: TaskConflict[]
144
+ /** Soft deliverable clauses (`交付/产出/输出/发布…`), reported but not blocking. */
145
+ deliverableClauses: string[]
146
+ }
147
+
148
+ export interface DepartmentAssignment {
149
+ subtaskId: string
150
+ department: string
151
+ departmentLabel: string
152
+ score: number
153
+ matched: string[]
154
+ /** Chosen department's keywords that also occur in the user's own request. */
155
+ anchorMatched: string[]
156
+ bestAlternative: { id: string; zh: string; score: number; matched: string[] } | null
157
+ /** Set when the department is guarded and its vocabulary is absent from the request. */
158
+ intrusion: boolean
159
+ verdict: 'fit' | 'weak' | 'mismatch'
160
+ reason: string
161
+ /** What the model said about its choice, when the planner emitted the field. */
162
+ declaredRationale: string
163
+ }
164
+
165
+ /** One department the user's request implies, with the evidence words. */
166
+ export interface DepartmentCoverageEntry {
167
+ department: string
168
+ departmentLabel: string
169
+ hits: string[]
170
+ }
171
+
172
+ export interface TaskAnchor {
173
+ text: string
174
+ sha256: string
175
+ length: number
176
+ sourceMessageIds: string[]
177
+ }
178
+
179
+ export interface UnderstandingAudit {
180
+ version: number
181
+ /** `null` for legacy plans / replays without the original request. */
182
+ anchor: TaskAnchor | null
183
+ stage1: {
184
+ elements: TaskElement[]
185
+ hardCount: number
186
+ references: TaskReference[]
187
+ conflicts: TaskConflict[]
188
+ deliverableClauses: string[]
189
+ }
190
+ stage2: {
191
+ assignments: DepartmentAssignment[]
192
+ departmentsUsed: string[]
193
+ mismatches: string[]
194
+ /** Departments the user's own request implies (>= REQUIRED_DEPARTMENT_MIN_HITS keywords). */
195
+ requiredDepartments: DepartmentCoverageEntry[]
196
+ /** Implied departments with no subtask and no stated exclusion — the U3 gap. */
197
+ missingDepartments: DepartmentCoverageEntry[]
198
+ /** Implied departments that the plan deliberately excluded, with the stated reason. */
199
+ excludedDepartments: Array<DepartmentCoverageEntry & { reason: string }>
200
+ }
201
+ stage3: {
202
+ verdict: 'aligned' | 'deviation' | 'needs-clarification' | 'needs-context' | 'degraded'
203
+ rewritten: boolean
204
+ summaryCoverage: number
205
+ droppedFromSummary: string[]
206
+ missingHardAnchors: string[]
207
+ missingDeliverables: string[]
208
+ reasons: string[]
209
+ }
210
+ }
211
+
212
+ export interface PlanAuditContext {
213
+ taskText?: string
214
+ conversationContext?: string
215
+ sourceMessageIds?: string[]
216
+ /** `false` downgrades every blocking error to a warning (rollback switch). */
217
+ strict?: boolean
218
+ }
219
+
220
+ export interface PlanContextValidation {
221
+ ok: boolean
222
+ errors: string[]
223
+ warnings: string[]
224
+ audit: UnderstandingAudit
225
+ }
226
+
227
+ const NEGATION_PATTERN = /(?:不要|禁止|不得|严禁|不能|不可|切勿|避免)\s*([^\s,。;、,.;:!?!?\n]{1,28})/g
228
+ const QUANTITY_PATTERN = /(?:最多|至少|不超过|不能超过|上限|下限|必须|只能|只允许|仅)\s*([^,。;;!?!?\n]{1,40})/g
229
+ const HARD_QUANTITY_PREFIX = /^(?:最多|至少|不超过|不能超过|上限|下限)/
230
+
231
+ /**
232
+ * Normalise for "does the plan still mention this literal" checks. It strips
233
+ * whitespace and punctuation only — never Chinese characters, digits or latin
234
+ * letters — so a match cannot be manufactured by dropping content.
235
+ */
236
+ export function normalizeForMatch(value: unknown): string {
237
+ return String(value ?? '')
238
+ .replace(/[\s\u3000]+/g, '')
239
+ .replace(/[%]/g, '%')
240
+ .replace(/[,。;、!?"'“”‘’()()【】\[\]<>《》]/g, '')
241
+ .toLowerCase()
242
+ }
243
+
244
+ function clauseOf(text: string, index: number, length: number): string {
245
+ const start = Math.max(0, index - 36)
246
+ const end = Math.min(text.length, index + length + 36)
247
+ return text.slice(start, end).replace(/\s+/g, ' ').trim()
248
+ }
249
+
250
+ function pushElement(target: TaskElement[], seen: Set<string>, element: TaskElement): void {
251
+ const key = `${element.kind}|${normalizeForMatch(element.value)}`
252
+ if (!element.value || seen.has(key)) return
253
+ seen.add(key)
254
+ target.push(element)
255
+ }
256
+
257
+ function collectMatches(
258
+ text: string,
259
+ pattern: RegExp,
260
+ make: (match: RegExpExecArray) => TaskElement | null,
261
+ ): TaskElement[] {
262
+ const found: TaskElement[] = []
263
+ const seen = new Set<string>()
264
+ // A local clone keeps the shared literal's lastIndex from leaking between calls.
265
+ const regex = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`)
266
+ let match: RegExpExecArray | null
267
+ while ((match = regex.exec(text)) !== null) {
268
+ const element = make(match)
269
+ if (element) pushElement(found, seen, element)
270
+ if (match.index === regex.lastIndex) regex.lastIndex += 1
271
+ }
272
+ return found
273
+ }
274
+
275
+ function splitClauses(text: string): string[] {
276
+ return text
277
+ .split(/[。;;\n!!??]+/)
278
+ .map((clause) => clause.trim())
279
+ .filter((clause) => clause.length > 0)
280
+ }
281
+
282
+ function cjkBigrams(text: string): Set<string> {
283
+ const clean = String(text ?? '').replace(/[^\u4e00-\u9fff]+/g, ' ')
284
+ const bigrams = new Set<string>()
285
+ for (const run of clean.split(/\s+/)) {
286
+ for (let i = 0; i + 2 <= run.length; i += 1) {
287
+ bigrams.add(run.slice(i, i + 2))
288
+ }
289
+ }
290
+ return bigrams
291
+ }
292
+
293
+ const STOP_BIGRAMS = new Set([
294
+ '的是', '我们', '你们', '他们', '这个', '那个', '这些', '那些', '一个', '已经',
295
+ '可以', '需要', '必须', '应该', '进行', '以及', '或者', '但是', '因为', '所以',
296
+ '如果', '没有', '不是', '就是', '通过', '对于', '时候', '现在', '问题', '要求',
297
+ '这里', '那里', '同时', '并且', '而且', '还有', '全部', '所有', '任何', '其他',
298
+ ])
299
+
300
+ function contentBigrams(text: string): Set<string> {
301
+ const result = new Set<string>()
302
+ for (const bigram of cjkBigrams(text)) {
303
+ if (!STOP_BIGRAMS.has(bigram)) result.add(bigram)
304
+ }
305
+ return result
306
+ }
307
+
308
+ function intersectionSize(a: Set<string>, b: Set<string>): number {
309
+ let count = 0
310
+ for (const value of a) if (b.has(value)) count += 1
311
+ return count
312
+ }
313
+
314
+ const SELF_CONTAINED_REFERENCE = /^(?:这个|那个|该|上述|前述|这些|那些|上一项|前一项|前者|后者)/
315
+
316
+ /**
317
+ * Extract hard requirements and ambiguity signals from the user's own words.
318
+ *
319
+ * Deliberately literal: no stemming, no synonyms, no model. The cost is that a
320
+ * heavily paraphrased plan may look lossy; the benefit is that every finding can
321
+ * be checked by searching the two strings involved.
322
+ */
323
+ export function extractTaskElements(taskText: unknown): TaskElements {
324
+ const text = typeof taskText === 'string' ? taskText.trim() : ''
325
+ const elements: TaskElement[] = []
326
+ const seen = new Set<string>()
327
+
328
+ // Order matters: `MAX_TASK_ELEMENTS` keeps the highest-signal kinds first.
329
+ for (const element of collectMatches(text, /\bv?(\d+\.\d+(?:\.\d+)?)\b/g, (match) => ({
330
+ kind: 'version' as const,
331
+ value: match[0].replace(/^v/i, ''),
332
+ evidence: clauseOf(text, match.index, match[0].length),
333
+ hard: true,
334
+ }))) pushElement(elements, seen, element)
335
+
336
+ for (const element of collectMatches(text, /\b(?:20\d{2})[-/年.]\d{1,2}(?:[-/月.]\d{1,2}日?)?/g, (match) => ({
337
+ kind: 'date' as const,
338
+ value: match[0],
339
+ evidence: clauseOf(text, match.index, match[0].length),
340
+ hard: true,
341
+ }))) pushElement(elements, seen, element)
342
+
343
+ for (const element of collectMatches(text, /\b\d{1,2}月\d{1,2}日/g, (match) => ({
344
+ kind: 'date' as const,
345
+ value: match[0],
346
+ evidence: clauseOf(text, match.index, match[0].length),
347
+ hard: true,
348
+ }))) pushElement(elements, seen, element)
349
+
350
+ for (const element of collectMatches(
351
+ text,
352
+ /\b(?:T|D|U|S|Q|P|E|R|C|M|H|W|XB)-?\d{1,3}\b/g,
353
+ (match) => ({
354
+ kind: 'id' as const,
355
+ value: match[0],
356
+ evidence: clauseOf(text, match.index, match[0].length),
357
+ hard: true,
358
+ }),
359
+ )) pushElement(elements, seen, element)
360
+
361
+ for (const element of collectMatches(
362
+ text,
363
+ /[A-Za-z0-9_./-]+\.(?:ts|tsx|js|mjs|cjs|json|md|yml|yaml|patch|log|csv|py|html|css|svg|tgz)\b/g,
364
+ (match) => ({
365
+ kind: 'path' as const,
366
+ value: match[0],
367
+ evidence: clauseOf(text, match.index, match[0].length),
368
+ hard: true,
369
+ }),
370
+ )) pushElement(elements, seen, element)
371
+
372
+ for (const element of collectMatches(
373
+ text,
374
+ /\b\d+(?:\.\d+)?\s*(?:个|页|条|项|次|份|张|台|人日|人|天|小时|分钟|秒|字|%|万|亿|KB|MB|GB)/gi,
375
+ (match) => ({
376
+ kind: 'count' as const,
377
+ value: match[0].replace(/\s+/g, ''),
378
+ evidence: clauseOf(text, match.index, match[0].length),
379
+ hard: true,
380
+ }),
381
+ )) pushElement(elements, seen, element)
382
+
383
+ for (const element of collectMatches(text, QUANTITY_PATTERN, (match) => {
384
+ const head = match[0]
385
+ return {
386
+ kind: 'quantity' as const,
387
+ value: head.replace(/\s+/g, ''),
388
+ evidence: clauseOf(text, match.index, match[0].length),
389
+ hard: HARD_QUANTITY_PREFIX.test(head),
390
+ }
391
+ })) pushElement(elements, seen, element)
392
+
393
+ /*
394
+ * Negations are recorded for readability but are not blocking by themselves.
395
+ * A negation's object often includes the verb ("不要修改业务代码"), so a
396
+ * legitimate synonym ("不得改动业务代码") would be a false deviation. When the
397
+ * object is a path, id or number it is already covered by the hard kinds
398
+ * above, so nothing checkable is lost.
399
+ */
400
+ for (const element of collectMatches(text, NEGATION_PATTERN, (match) => ({
401
+ kind: 'negation' as const,
402
+ value: `禁止:${match[1]}`,
403
+ evidence: clauseOf(text, match.index, match[0].length),
404
+ hard: false,
405
+ }))) pushElement(elements, seen, element)
406
+
407
+ const deliverableClauses = splitClauses(text)
408
+ .filter((clause) => /(?:交付|产出|输出|发布|提供|生成|给出)/.test(clause))
409
+ .slice(0, 10)
410
+
411
+ return {
412
+ textLength: text.length,
413
+ elements: elements.slice(0, MAX_TASK_ELEMENTS),
414
+ hardCount: elements.filter((element) => element.hard).length,
415
+ references: extractReferences(text),
416
+ conflicts: extractConflicts(text),
417
+ deliverableClauses,
418
+ }
419
+ }
420
+
421
+ function extractReferences(text: string): TaskReference[] {
422
+ if (!text) return []
423
+ const references: TaskReference[] = []
424
+ const seen = new Set<string>()
425
+ const inlineTokens = ['这个', '那个', '该', '上述', '前述', '这些', '那些', '上一项', '前一项', '前者', '后者']
426
+ for (const token of inlineTokens) {
427
+ let index = text.indexOf(token)
428
+ while (index >= 0) {
429
+ const before = text[index - 1] ?? ''
430
+ if (before === '其') {
431
+ index = text.indexOf(token, index + token.length)
432
+ continue
433
+ }
434
+ if (!seen.has(token)) {
435
+ const after = text.slice(index + token.length, index + token.length + 6)
436
+ /*
437
+ * 「该」 is also a modal ("该怎么做"), which is not a reference at all.
438
+ * Skipping it keeps a real task from being blocked by a false pronoun
439
+ * while 「该模块」 still resolves inline.
440
+ */
441
+ if (token === '该' && /^(?:怎么|如何|怎样|是否|做|不|应)/.test(after)) {
442
+ index = text.indexOf(token, index + token.length)
443
+ continue
444
+ }
445
+ seen.add(token)
446
+ const selfContained = SELF_CONTAINED_REFERENCE.test(token) && /^[\u4e00-\u9fff]{2}/.test(after)
447
+ references.push({
448
+ token,
449
+ resolvedBy: selfContained ? 'inline-noun' : 'none',
450
+ resolved: selfContained,
451
+ evidence: clauseOf(text, index, token.length),
452
+ })
453
+ }
454
+ index = text.indexOf(token, index + token.length)
455
+ }
456
+ }
457
+ // Bare 「它」 is the real ambiguity: it can only be resolved by context.
458
+ for (let index = text.indexOf('它'); index >= 0; index = text.indexOf('它', index + 1)) {
459
+ const before = text[index - 1] ?? ''
460
+ if (before === '其') continue
461
+ if (!seen.has('它')) {
462
+ seen.add('它')
463
+ references.push({
464
+ token: '它',
465
+ resolvedBy: 'none',
466
+ resolved: false,
467
+ evidence: clauseOf(text, index, 1),
468
+ })
469
+ }
470
+ }
471
+ /*
472
+ * [P0-2] Option letters are references only when a choice cue selects one.
473
+ *
474
+ * The old rule fired on any A-D letter as soon as the text said 建议/方案
475
+ * anywhere: MS2 case T05-04 ("A/B 探针…建议移入") was blocked as an unresolved
476
+ * pronoun it never contained, and Markdown list markers "A." would do the
477
+ * same. A letter now counts only when it directly follows a selection verb,
478
+ * which is the only structure that can actually mean "choose this option".
479
+ */
480
+ const option = /(?:选|选项|方案|可选|建议|采用|按)\s*(?:用\s*)?([A-D])(?![A-Za-z\/])/.exec(text)
481
+ if (option && !seen.has(option[1])) {
482
+ seen.add(option[1])
483
+ references.push({
484
+ token: option[1],
485
+ resolvedBy: 'none',
486
+ resolved: false,
487
+ evidence: clauseOf(text, option.index, option[0].length),
488
+ })
489
+ }
490
+ return references
491
+ }
492
+
493
+ /**
494
+ * [P0-2] Pronoun antecedent extraction.
495
+ *
496
+ * Before this, any non-empty conversation turned every pronoun into
497
+ * `resolvedBy: 'context'` — the audit claimed "它 was resolved" even when the
498
+ * context was "进展到哪一步了" or talked about something else entirely, so a
499
+ * plan could be dispatched on a guess. Resolution now requires an actual noun
500
+ * phrase in the recent conversation:
501
+ *
502
+ * - a cue (`用户…:` / `使用` / `针对` / `把`…) followed by the phrase, or
503
+ * - a topic sentence (`我们在聊…`, `讨论了…`);
504
+ *
505
+ * and phrases made only of function words (`把` / `问题` / `这个`…) are refused,
506
+ * so an empty promise cannot be manufactured. When nothing qualifies the
507
+ * reference stays unresolved and the plan is blocked as `needs-context`
508
+ * (strict mode) or recorded as a warning (rollback switch).
509
+ */
510
+ const ANTECEDENT_CUES = [
511
+ /(?:^|[::。;;\n])\s*(?:用户|需求|任务|要求|目标|对象)?\s*(?:上一轮|上一条|刚才|之前|前面)?\s*[说讲提]:?\s*/g,
512
+ /(?:使用|针对|关于|围绕|涉及|改造|修改|调整|优化|修复|处理|把|将|对)\s*/g,
513
+ /(?:和|与|同|跟)\s*[\u4e00-\u9fffA-Za-z0-9_\-\.]{2,12}?(?:相关|有关|有关联)/g,
514
+ // Options: "给出 A 方案(…)与 B 方案(只跑增量)", "我们在聊 X"/"讨论了 X".
515
+ /(?:在聊|聊到|讨论了|商量了|谈到了|提到|列出|提供|给出|可选)\s*/g,
516
+ ]
517
+ const FUNCTION_WORD_ONLY = /^(?:那|这|些|个|位|次|样|里|边|面|中|上|下|我们|你们|他们|它|他|她|是|的|了|在|有|做|干|弄|搞|看|说|问|聊|讨论|事情|东西|问题|内容|功能|东西|部分|那块|这块)+$/
518
+ const ANTECEDENT_MAX_LENGTH = 12
519
+
520
+ export interface AntecedentResult {
521
+ /** The noun phrase the pronoun points at. */
522
+ antecedent: string
523
+ /** The conversation snippet the phrase was taken from. */
524
+ source: string
525
+ }
526
+
527
+ /** Refuse function-word-only fragments: they carry no referent. */
528
+ function isMeaningfulAntecedent(candidate: string): boolean {
529
+ const value = candidate.trim()
530
+ if (value.length < 2 || value.length > ANTECEDENT_MAX_LENGTH) return false
531
+ // An option label ("A 方案") is a referent: it points at a lettered choice.
532
+ if (/^[A-D](?:方案|选项)$/.test(value)) return true
533
+ /*
534
+ * A pronoun is not its own antecedent: "把它改一下" leaves "它" behind at the
535
+ * start of the clause, and accepting that would resolve 它 to itself.
536
+ */
537
+ if (/^(?:它|他|她|这|那|其)(?:们)?$/.test(value) || /^(?:它|他|她|这|那|其)/.test(value)) return false
538
+ if (!/[\u4e00-\u9fffA-Za-z]/.test(value)) return false
539
+ return !FUNCTION_WORD_ONLY.test(value)
540
+ }
541
+
542
+ /**
543
+ * Find the phrase a pronoun points at in the recent conversation.
544
+ *
545
+ * Returns `null` — never a fabricated phrase — when the conversation names no
546
+ * candidate. Callers must treat `null` as "still ambiguous".
547
+ */
548
+ export function resolvePronounAntecedent(token: string, conversationContext: string): AntecedentResult | null {
549
+ const text = String(conversationContext ?? '').trim()
550
+ if (!text || text.length > 20000) return null
551
+ for (const pattern of ANTECEDENT_CUES) {
552
+ pattern.lastIndex = 0
553
+ for (const match of text.matchAll(pattern)) {
554
+ const start = (match.index ?? 0) + match[0].length
555
+ const found = antecedentAfterCue(text, start)
556
+ if (found) return found
557
+ }
558
+ }
559
+ return null
560
+ }
561
+
562
+ /**
563
+ * Split one clause into candidate noun phrases.
564
+ *
565
+ * Whitespace, 、 and the connectors 与/和/及 separate phrases — but an option
566
+ * letter is a prefix, not a phrase of its own: "A 方案" must stay one candidate,
567
+ * otherwise the letter is lost and the option cannot be matched.
568
+ */
569
+ export function splitAntecedentCandidates(clause: string): string[] {
570
+ const parts: string[] = []
571
+ let current = ''
572
+ const isWordChar = (char: string | undefined): boolean => !!char && /[\u4e00-\u9fffA-Za-z0-9_]/.test(char)
573
+ for (let index = 0; index < clause.length; index += 1) {
574
+ const char = clause[index]
575
+ if (',,、'.includes(char)) {
576
+ parts.push(current)
577
+ current = ''
578
+ continue
579
+ }
580
+ if ('与和及'.includes(char)) {
581
+ // "A 方案与 B 方案": a connector right after an option label is a separator.
582
+ const soFar = current.trim()
583
+ if (/[A-D](?:方案|选项)$/.test(soFar)) {
584
+ parts.push(current)
585
+ current = ''
586
+ continue
587
+ }
588
+ }
589
+ if (/s/.test(char) || char === ' ') {
590
+ const soFar = current.trim()
591
+ const next = clause.slice(index).trimStart()
592
+ // Glue an option letter to the word that follows it.
593
+ if (/^[A-D]$/.test(soFar) && /^(?:方案|选项)/.test(next)) {
594
+ current += char
595
+ continue
596
+ }
597
+ if (isWordChar(clause[index - 1]) || isWordChar(next[0])) {
598
+ parts.push(current)
599
+ current = ''
600
+ continue
601
+ }
602
+ continue
603
+ }
604
+ if ('()()'.includes(char)) {
605
+ // Parentheses are skipped entirely; their content is not the referent.
606
+ const close = clause.indexOf(char === '(' ? ')' : char === '(' ? ')' : char, index + 1)
607
+ if (close >= 0) {
608
+ index = close
609
+ parts.push(current)
610
+ current = ''
611
+ continue
612
+ }
613
+ }
614
+ current += char
615
+ }
616
+ parts.push(current)
617
+ return parts
618
+ .map((part) => part.replace(/[(())]/g, '').trim())
619
+ .filter((part) => part.length > 0)
620
+ }
621
+
622
+ function cleanAntecedentCandidate(part: string): string {
623
+ return part
624
+ .replace(/\u0000/g, '')
625
+ .replace(/^(?:把|将|对|使用|针对|关于|围绕|涉及|改造|修改|调整|优化|修复|处理)\s*/, '')
626
+ .replace(/(?:改成|改为|修正成|调整成|设成|变为|换成|变成|默认为|默认|保持|不用|不要|可以|需要|看看|检查一下|是什么|怎么样|如何).*$/, '')
627
+ // Parentheticals are not part of the referent: "B 方案(只跑增量)" -> "B 方案".
628
+ .replace(/[((][^))]*[))]/g, '')
629
+ .replace(/[,,。!?!?;;::、\s]+$/, '')
630
+ .trim()
631
+ }
632
+
633
+ /**
634
+ * Read the clause that starts at `start` and return the first meaningful noun
635
+ * phrase in it. A verb left at the start (`把…`) is dropped by
636
+ * `cleanAntecedentCandidate`; the clause never crosses a sentence boundary.
637
+ */
638
+ function antecedentAfterCue(text: string, start: number): AntecedentResult | null {
639
+ const tail = text.slice(start)
640
+ const stop = tail.search(/[。!?!?\n;;]/)
641
+ const clause = (stop >= 0 ? tail.slice(0, stop) : tail).trim()
642
+ if (!clause) return null
643
+ /*
644
+ * The clause may chain several noun phrases ("A 方案…与 B 方案…"). Split at
645
+ * the connector and at whitespace so each candidate is one noun phrase; the
646
+ * caller compares them to the pronoun token and picks the matching one.
647
+ */
648
+ const parts = splitAntecedentCandidates(clause)
649
+ for (const part of parts) {
650
+ const cleaned = cleanAntecedentCandidate(part).replace(/^[((]|[))]$/g, '')
651
+ if (isMeaningfulAntecedent(cleaned)) return { antecedent: cleaned, source: clause.slice(0, 80) }
652
+ }
653
+ return null
654
+ }
655
+
656
+
657
+ function extractConflicts(text: string): TaskConflict[] {
658
+ const conflicts: TaskConflict[] = []
659
+ const seen = new Set<string>()
660
+ const add = (conflict: TaskConflict): void => {
661
+ const key = `${conflict.kind}|${normalizeForMatch(conflict.a)}|${normalizeForMatch(conflict.b)}`
662
+ if (seen.has(key)) return
663
+ seen.add(key)
664
+ conflicts.push(conflict)
665
+ }
666
+
667
+ const open = /默认(?:展开|打开|显示)/.exec(text)
668
+ const closed = /默认(?:不展开|不打开|收起|折叠|关闭|隐藏)/.exec(text)
669
+ if (open && closed) {
670
+ add({
671
+ kind: 'default-state',
672
+ a: open[0],
673
+ b: closed[0],
674
+ reason: '同一默认状态被同时要求展开与收起,二选一必须由用户决定',
675
+ })
676
+ }
677
+
678
+ const only = /只(?:改|修改|动|做)\s*([^\s,。;、,;!?!?]{1,24})/.exec(text)
679
+ const also = /(?:同时|还要|也要|并且|另外)(?:改|修改|动|做)\s*([^\s,。;、,;!?!?]{1,24})/.exec(text)
680
+ if (only && also && normalizeForMatch(only[1]) !== normalizeForMatch(also[1])) {
681
+ add({
682
+ kind: 'scope',
683
+ a: only[0],
684
+ b: also[0],
685
+ reason: `范围冲突:既要求只处理「${only[1]}」,又要求处理「${also[1]}」`,
686
+ })
687
+ }
688
+
689
+ const clauses = splitClauses(text)
690
+ for (const forbidClause of clauses) {
691
+ const forbid = /(?:不要|禁止|不得|严禁)\s*(?:修改|改动|改|动|删除|移除)\s*([^\s,。;、,;!?!?]{1,24})/.exec(forbidClause)
692
+ if (!forbid) continue
693
+ for (const requireClause of clauses) {
694
+ if (requireClause === forbidClause) continue
695
+ const require = /(?:必须|需要|务必|要)\s*(?:修改|改动|改|动|删除|移除)\s*([^\s,。;、,;!?!?]{1,24})/.exec(requireClause)
696
+ if (!require) continue
697
+ const a = normalizeForMatch(forbid[1])
698
+ const b = normalizeForMatch(require[1])
699
+ const overlap = a === b || a.includes(b) || b.includes(a)
700
+ || intersectionSize(contentBigrams(forbid[1]), contentBigrams(require[1])) > 0
701
+ if (overlap) {
702
+ add({
703
+ kind: 'polarity',
704
+ a: forbid[0],
705
+ b: require[0],
706
+ reason: `同一对象「${forbid[1]}」既被禁止修改又被要求修改`,
707
+ })
708
+ }
709
+ }
710
+ }
711
+
712
+ for (const clause of clauses) {
713
+ const change = /(?:改成|改为|设为|调整为|更新为)\s*([^\s,。;、,;!?!?]{1,24})/.exec(clause)
714
+ if (!change) continue
715
+ for (const otherClause of clauses) {
716
+ if (otherClause === clause) continue
717
+ const keep = /(?:保持|保持不变|仍为|保留)\s*([^\s,。;、,;!?!?]{1,24})/.exec(otherClause)
718
+ if (!keep) continue
719
+ if (normalizeForMatch(change[1]) === normalizeForMatch(keep[1])) continue
720
+ const shared = intersectionSize(contentBigrams(clause), contentBigrams(otherClause))
721
+ if (shared === 0) continue
722
+ add({
723
+ kind: 'value',
724
+ a: change[0],
725
+ b: keep[0],
726
+ reason: `同一对象被要求改成「${change[1]}」又要求保持「${keep[1]}」`,
727
+ })
728
+ }
729
+ }
730
+
731
+ return conflicts.slice(0, 8)
732
+ }
733
+
734
+ function subtaskText(subtask: any): string {
735
+ const parts = [
736
+ subtask?.title,
737
+ subtask?.role,
738
+ subtask?.objective,
739
+ ...(Array.isArray(subtask?.method) ? subtask.method : []),
740
+ ...(Array.isArray(subtask?.inputs) ? subtask.inputs : []),
741
+ ...(Array.isArray(subtask?.outputs) ? subtask.outputs : []),
742
+ ...(Array.isArray(subtask?.acceptance) ? subtask.acceptance : []),
743
+ ]
744
+ return parts
745
+ .filter((part) => typeof part === 'string' && part.trim() !== '')
746
+ .join(' ')
747
+ }
748
+
749
+ function flattenPlanSubtasks(plan: any): any[] {
750
+ const stages = Array.isArray(plan?.stages) ? plan.stages : []
751
+ const subtasks: any[] = []
752
+ for (const stage of stages) {
753
+ for (const subtask of Array.isArray(stage?.subtasks) ? stage.subtasks : []) {
754
+ subtasks.push(subtask)
755
+ if (subtasks.length >= MAX_AUDITED_SUBTASKS) return subtasks
756
+ }
757
+ }
758
+ return subtasks
759
+ }
760
+
761
+ /**
762
+ * [P0-1] Which department domains the user's request itself implies, and which
763
+ * of them the plan never addresses.
764
+ *
765
+ * Root cause this closes: before 1.12.1 the audit only asked "does the chosen
766
+ * department fit?" — a plan could omit an entire domain the request names and
767
+ * still pass, because nothing asked "is a domain missing?". MS2 measured the
768
+ * consequence: 11/29 required departments covered.
769
+ *
770
+ * A missing department is forgiven only when the plan states the exclusion in
771
+ * `taskUnderstanding.assumptions` / `unknowns` with one of
772
+ * DEPARTMENT_EXCLUSION_CUES, so omission must be a written decision instead of
773
+ * silence. Pure and deterministic: no model, no I/O.
774
+ */
775
+ export function auditDepartmentCoverage(taskText: string, plan: any): {
776
+ required: DepartmentCoverageEntry[]
777
+ missing: DepartmentCoverageEntry[]
778
+ excluded: Array<DepartmentCoverageEntry & { reason: string }>
779
+ } {
780
+ const text = typeof taskText === 'string' ? taskText.trim() : ''
781
+ if (text === '') return { required: [], missing: [], excluded: [] }
782
+ const used = new Set<string>(
783
+ flattenPlanSubtasks(plan)
784
+ .map((subtask) => (typeof subtask?.department === 'string' ? subtask.department : ''))
785
+ .filter((department) => department !== ''),
786
+ )
787
+ const statements: string[] = []
788
+ for (const key of ['assumptions', 'unknowns']) {
789
+ const list = plan?.taskUnderstanding?.[key]
790
+ if (!Array.isArray(list)) continue
791
+ for (const item of list) if (typeof item === 'string' && item.trim() !== '') statements.push(item.trim())
792
+ }
793
+ const required: DepartmentCoverageEntry[] = []
794
+ const missing: DepartmentCoverageEntry[] = []
795
+ const excluded: Array<DepartmentCoverageEntry & { reason: string }> = []
796
+ for (const capability of DEPARTMENT_CAPABILITIES) {
797
+ const hits = matchDepartmentKeywords(text, capability.id)
798
+ if (hits.length < REQUIRED_DEPARTMENT_MIN_HITS) continue
799
+ const entry: DepartmentCoverageEntry = { department: capability.id, departmentLabel: capability.zh, hits }
800
+ required.push(entry)
801
+ if (used.has(capability.id)) continue
802
+ const reason = statements.find((statement) => (
803
+ (statement.includes(capability.zh) || statement.includes(capability.id))
804
+ && DEPARTMENT_EXCLUSION_CUES.test(statement)
805
+ ))
806
+ if (reason) excluded.push({ ...entry, reason: reason.slice(0, 300) })
807
+ else missing.push(entry)
808
+ }
809
+ return { required, missing, excluded }
810
+ }
811
+
812
+ /**
813
+ * Explain one department choice with the catalog keywords that support it.
814
+ *
815
+ * `verdict` is intentionally coarse:
816
+ * - `fit` — the chosen department has at least one matching keyword;
817
+ * - `weak` — no keyword anywhere; insufficient evidence, not an error;
818
+ * - `mismatch`— the chosen department has zero evidence while another has a
819
+ * strong one (>= MISMATCH_BLOCKING_SCORE).
820
+ */
821
+ export function departmentFit(subtask: any, anchorText = ''): DepartmentAssignment {
822
+ const department = typeof subtask?.department === 'string' ? subtask.department : ''
823
+ const capability: DepartmentCapability | null = departmentCapability(department)
824
+ const text = subtaskText(subtask)
825
+ const matched = capability ? capability.keywords.filter((keyword) => keywordHit(text, keyword)) : []
826
+ const anchorMatched = capability && anchorText.trim() !== ''
827
+ ? capability.keywords.filter((keyword) => keywordHit(anchorText, keyword))
828
+ : []
829
+ const scores = scoreDepartments(text).filter((entry) => entry.id !== department)
830
+ const best = scores.length > 0 && scores[0].score > 0 ? scores[0] : null
831
+ const chosenScore = matched.length
832
+
833
+ let intrusion = false
834
+ if (capability && DEPARTMENT_INTRUSION_GUARDED.includes(department) && chosenScore > 0 && anchorText.trim() !== '') {
835
+ const anchorHits = matchDepartmentKeywords(anchorText, department)
836
+ if (anchorHits.length === 0) {
837
+ const overlap = intersectionSize(contentBigrams(text), contentBigrams(anchorText))
838
+ // No shared content bigram at all = the request never talks about this
839
+ // domain. One shared topic word is enough to make it a warning instead.
840
+ intrusion = overlap === 0
841
+ }
842
+ }
843
+
844
+ let verdict: DepartmentAssignment['verdict'] = 'fit'
845
+ let reason = ''
846
+ if (!capability) {
847
+ verdict = 'mismatch'
848
+ reason = `未知部门「${department}」,不在 12 个部门目录内`
849
+ } else if (chosenScore === 0 && anchorMatched.length === 0 && best && best.score >= MISMATCH_BLOCKING_SCORE) {
850
+ verdict = 'mismatch'
851
+ reason = `「${capability.zh}」无任何目录关键词命中,而「${best.zh}」命中 ${best.score} 个(${best.matched.slice(0, 4).join('、')})`
852
+ } else if (intrusion) {
853
+ verdict = 'mismatch'
854
+ reason = `「${capability.zh}」领域词(${matched.slice(0, 3).join('、')})只出现在子任务中,用户原要求从未涉及该领域`
855
+ } else if (chosenScore === 0 && anchorMatched.length === 0) {
856
+ verdict = 'weak'
857
+ reason = `「${capability.zh}」在子任务与用户原要求中都没有目录关键词命中,属证据不足(不阻断)`
858
+ } else if (chosenScore === 0) {
859
+ reason = `子任务未命中「${capability.zh}」职责词,但用户原要求命中:${anchorMatched.slice(0, 5).join('、')}`
860
+ } else {
861
+ reason = `命中「${capability.zh}」职责关键词 ${chosenScore} 个:${matched.slice(0, 5).join('、')}`
862
+ if (anchorMatched.length > 0) reason += `;用户原要求也命中:${anchorMatched.slice(0, 5).join('、')}`
863
+ }
864
+
865
+ const declared = typeof subtask?.departmentRationale === 'string'
866
+ ? subtask.departmentRationale.trim().slice(0, 600)
867
+ : ''
868
+
869
+ return {
870
+ subtaskId: typeof subtask?.id === 'string' ? subtask.id : '',
871
+ department,
872
+ departmentLabel: capability?.zh ?? department,
873
+ score: chosenScore,
874
+ matched,
875
+ anchorMatched,
876
+ bestAlternative: best
877
+ ? { id: best.id, zh: best.zh, score: best.score, matched: best.matched.slice(0, 5) }
878
+ : null,
879
+ intrusion,
880
+ verdict,
881
+ reason,
882
+ declaredRationale: declared,
883
+ }
884
+ }
885
+
886
+ export function buildTaskAnchor(taskText: unknown, sourceMessageIds: unknown = []): TaskAnchor | null {
887
+ const text = typeof taskText === 'string' ? taskText.trim() : ''
888
+ if (!text) return null
889
+ const ids = Array.isArray(sourceMessageIds)
890
+ ? sourceMessageIds.filter((id): id is string => typeof id === 'string').slice(0, 30)
891
+ : []
892
+ return {
893
+ text: text.slice(0, MAX_TASK_ANCHOR_CHARS),
894
+ sha256: createHash('sha256').update(text, 'utf8').digest('hex'),
895
+ length: text.length,
896
+ sourceMessageIds: ids,
897
+ }
898
+ }
899
+
900
+ function collectPlanText(plan: any): string {
901
+ const understanding = plan?.taskUnderstanding ?? {}
902
+ const parts: string[] = [plan?.title]
903
+ for (const key of ['originalRequest', 'deliverable']) {
904
+ if (typeof understanding?.[key] === 'string') parts.push(understanding[key])
905
+ }
906
+ for (const key of ['successCriteria', 'constraints', 'knownFacts', 'unknowns', 'assumptions']) {
907
+ if (Array.isArray(understanding?.[key])) parts.push(...understanding[key])
908
+ }
909
+ for (const stage of Array.isArray(plan?.stages) ? plan.stages : []) {
910
+ for (const key of ['name', 'goal', 'rationale', 'checkpoint']) {
911
+ if (typeof stage?.[key] === 'string') parts.push(stage[key])
912
+ }
913
+ for (const subtask of Array.isArray(stage?.subtasks) ? stage.subtasks : []) {
914
+ parts.push(subtaskText(subtask))
915
+ }
916
+ }
917
+ for (const entry of Array.isArray(plan?.verification) ? plan.verification : []) {
918
+ for (const key of ['item', 'method', 'evidence']) {
919
+ if (typeof entry?.[key] === 'string') parts.push(entry[key])
920
+ }
921
+ }
922
+ return parts.filter((part) => typeof part === 'string').join('\n')
923
+ }
924
+
925
+ function elementPresent(planText: string, element: TaskElement): boolean {
926
+ const haystack = normalizeForMatch(planText)
927
+ if (!haystack) return false
928
+ if (element.kind === 'id') {
929
+ const value = normalizeForMatch(element.value)
930
+ return haystack.includes(value) || haystack.includes(value.replace(/-/g, ''))
931
+ }
932
+ if (element.kind === 'negation') {
933
+ return haystack.includes(normalizeForMatch(element.value.replace(/^禁止:/, '')))
934
+ }
935
+ return haystack.includes(normalizeForMatch(element.value))
936
+ }
937
+
938
+ function emptyAudit(anchor: TaskAnchor | null, reason: string): UnderstandingAudit {
939
+ return {
940
+ version: UNDERSTANDING_AUDIT_VERSION,
941
+ anchor,
942
+ stage1: { elements: [], hardCount: 0, references: [], conflicts: [], deliverableClauses: [] },
943
+ stage2: { assignments: [], departmentsUsed: [], mismatches: [], requiredDepartments: [], missingDepartments: [], excludedDepartments: [] },
944
+ stage3: {
945
+ verdict: 'degraded',
946
+ rewritten: false,
947
+ summaryCoverage: 0,
948
+ droppedFromSummary: [],
949
+ missingHardAnchors: [],
950
+ missingDeliverables: [],
951
+ reasons: [reason],
952
+ },
953
+ }
954
+ }
955
+
956
+ /**
957
+ * Run the three stages against one plan.
958
+ *
959
+ * A legacy/replayed plan without the original task text returns a `degraded`
960
+ * audit instead of throwing: replay must keep working, and "cannot check" is
961
+ * not the same as "checked and passed" (which is why the verdict says so).
962
+ */
963
+ export function auditTaskUnderstanding(plan: any, context: PlanAuditContext = {}): UnderstandingAudit {
964
+ const taskText = typeof context.taskText === 'string' ? context.taskText.trim() : ''
965
+ const anchor = buildTaskAnchor(taskText, context.sourceMessageIds)
966
+ if (!anchor) {
967
+ return emptyAudit(null, '没有用户原文(旧计划/回放),锚点偏离校验降级为不阻断')
968
+ }
969
+
970
+ const extracted = extractTaskElements(taskText)
971
+ const planText = collectPlanText(plan)
972
+ const assignments = flattenPlanSubtasks(plan).map((subtask) => departmentFit(subtask, taskText))
973
+ const departmentsUsed = [...new Set(assignments.map((entry) => entry.department))]
974
+ const coverage = auditDepartmentCoverage(taskText, plan)
975
+ const mismatches = assignments
976
+ .filter((entry) => entry.verdict === 'mismatch')
977
+ .map((entry) => `${entry.subtaskId || '(无 ID)'} → ${entry.departmentLabel}:${entry.reason}`)
978
+
979
+ const missingElements = extracted.elements
980
+ .filter((element) => element.hard && !elementPresent(planText, element))
981
+ const missingHardAnchors = missingElements.map((element) => `${element.kind}:${element.value}`)
982
+
983
+ const missingDeliverables = extracted.deliverableClauses.filter((clause) => {
984
+ const haystack = normalizeForMatch(planText)
985
+ const bigrams = [...contentBigrams(clause)]
986
+ if (bigrams.length === 0) return false
987
+ const hits = bigrams.filter((bigram) => haystack.includes(bigram)).length
988
+ return hits < Math.max(1, Math.ceil(bigrams.length * 0.5))
989
+ })
990
+
991
+ const originalRequest = typeof plan?.taskUnderstanding?.originalRequest === 'string'
992
+ ? plan.taskUnderstanding.originalRequest
993
+ : ''
994
+ const summaryNorm = normalizeForMatch(originalRequest)
995
+ const anchorNorm = normalizeForMatch(taskText)
996
+ const verbatim = summaryNorm.length > 0 && anchorNorm.includes(summaryNorm)
997
+ const droppedFromSummary = extracted.elements
998
+ .filter((element) => element.hard && !normalizeForMatch(originalRequest).includes(normalizeForMatch(element.value)))
999
+ .map((element) => `${element.kind}:${element.value}`)
1000
+ const hardTotal = extracted.elements.filter((element) => element.hard).length
1001
+ const summaryCoverage = hardTotal === 0 ? 1 : (hardTotal - droppedFromSummary.length) / hardTotal
1002
+
1003
+ /*
1004
+ * [P0-2] Resolution requires an antecedent, not merely a non-empty context.
1005
+ * The old rule marked every pronoun resolved as soon as any conversation
1006
+ * existed, so "把它改成默认收起" passed with a context that talked about
1007
+ * something else. Now the phrase is extracted and quoted; otherwise the
1008
+ * reference stays unresolved and blocks (or warns in rollback mode).
1009
+ */
1010
+ const conversation = typeof context.conversationContext === 'string' ? context.conversationContext : ''
1011
+ const resolvedByContext = extracted.references.map((reference) => {
1012
+ if (reference.resolved) return reference
1013
+ const found = resolvePronounAntecedent(reference.token, conversation)
1014
+ if (!found) return reference
1015
+ // Option letters are resolved only when the conversation lists that option
1016
+ // as a listed choice ("A 方案" / "B 选项"), not a bare letter in a word.
1017
+ const listedOption = new RegExp('(?:^|[^A-Za-z])' + reference.token + '\\s*(?:方案|选项)')
1018
+ if (/^[A-D]$/.test(reference.token) && !listedOption.test(conversation)) return reference
1019
+ return { ...reference, resolved: true, resolvedBy: 'context' as const, antecedent: found.antecedent }
1020
+ })
1021
+ const unresolved = resolvedByContext.filter((reference) => !reference.resolved)
1022
+
1023
+ const reasons: string[] = []
1024
+ let verdict: UnderstandingAudit['stage3']['verdict'] = 'aligned'
1025
+ if (missingHardAnchors.length > 0) {
1026
+ verdict = 'deviation'
1027
+ reasons.push(`用户原要求中的 ${missingHardAnchors.length} 个硬要素在计划中完全缺失:${missingHardAnchors.slice(0, 6).join('、')}`)
1028
+ }
1029
+ if (coverage.missing.length > 0) {
1030
+ verdict = 'deviation'
1031
+ reasons.push(`用户原要求涉及 ${coverage.missing.length} 个部门领域,计划既未安排也未写明排除理由:${coverage.missing.map((entry) => entry.departmentLabel).join('、')}`)
1032
+ }
1033
+ if (mismatches.length > 0) {
1034
+ if (verdict === 'aligned') verdict = 'deviation'
1035
+ reasons.push(`${mismatches.length} 个子任务的部门与用户原要求矛盾:${mismatches.slice(0, 4).join(';')}`)
1036
+ }
1037
+ if (extracted.conflicts.length > 0) {
1038
+ if (verdict === 'aligned') verdict = 'needs-clarification'
1039
+ reasons.push(`用户要求自相矛盾 ${extracted.conflicts.length} 处:${extracted.conflicts.map((conflict) => conflict.reason).slice(0, 3).join(';')}`)
1040
+ }
1041
+ if (unresolved.length > 0) {
1042
+ if (verdict === 'aligned') verdict = 'needs-context'
1043
+ reasons.push(`含指代的任务在最近对话里找不到先行词:${unresolved.map((reference) => reference.token).join('、')},不应在未澄清前派发`)
1044
+ }
1045
+ if (verdict === 'aligned') {
1046
+ reasons.push(`硬要素 ${hardTotal - missingHardAnchors.length}/${hardTotal} 全部保留;${assignments.length} 个子任务的部门有目录关键词支撑`)
1047
+ }
1048
+
1049
+ return {
1050
+ version: UNDERSTANDING_AUDIT_VERSION,
1051
+ anchor,
1052
+ stage1: {
1053
+ elements: extracted.elements,
1054
+ hardCount: extracted.hardCount,
1055
+ references: resolvedByContext,
1056
+ conflicts: extracted.conflicts,
1057
+ deliverableClauses: extracted.deliverableClauses,
1058
+ },
1059
+ stage2: {
1060
+ assignments,
1061
+ departmentsUsed,
1062
+ mismatches,
1063
+ requiredDepartments: coverage.required,
1064
+ missingDepartments: coverage.missing,
1065
+ excludedDepartments: coverage.excluded,
1066
+ },
1067
+ stage3: {
1068
+ verdict,
1069
+ rewritten: !verbatim,
1070
+ summaryCoverage: Number(summaryCoverage.toFixed(3)),
1071
+ droppedFromSummary,
1072
+ missingHardAnchors,
1073
+ missingDeliverables,
1074
+ reasons,
1075
+ },
1076
+ }
1077
+ }
1078
+
1079
+ /**
1080
+ * Convert an audit into retry errors.
1081
+ *
1082
+ * `strict:false` is the rollback switch: every finding becomes a warning and the
1083
+ * plan proceeds exactly like 1.11.1. This is what an operator flips if a
1084
+ * release starts rejecting legitimate tasks, without reverting code.
1085
+ */
1086
+ export function validatePlanContext(plan: any, context: PlanAuditContext = {}): PlanContextValidation {
1087
+ const audit = auditTaskUnderstanding(plan, context)
1088
+ const warnings: string[] = []
1089
+ const errors: string[] = []
1090
+ const strict = context.strict !== false
1091
+
1092
+ for (const reason of audit.stage3.reasons) {
1093
+ if (audit.stage3.verdict === 'aligned') continue
1094
+ warnings.push(reason)
1095
+ }
1096
+ for (const missing of audit.stage3.missingDeliverables) {
1097
+ warnings.push(`交付物子句可能未被计划覆盖:${missing}`)
1098
+ }
1099
+ for (const assignment of audit.stage2.assignments) {
1100
+ if (assignment.verdict === 'weak') warnings.push(`${assignment.subtaskId} 部门「${assignment.departmentLabel}」证据不足:${assignment.reason}`)
1101
+ }
1102
+
1103
+ if (strict) {
1104
+ /*
1105
+ * A plan must not resolve a contradiction by silently picking a side, and
1106
+ * must not guess what 「它」 means. Both need the user, so both block the
1107
+ * dispatch under strict mode and degrade to a recorded warning only when
1108
+ * the rollback switch is on.
1109
+ */
1110
+ if (audit.stage3.verdict === 'needs-clarification') {
1111
+ errors.push(`CLARIFY: ${audit.stage3.reasons.find((reason) => reason.includes('自相矛盾')) ?? '用户要求存在矛盾,必须先向用户确认'}`)
1112
+ }
1113
+ if (audit.stage3.verdict === 'needs-context') {
1114
+ errors.push(`CONTEXT: ${audit.stage3.reasons.find((reason) => reason.includes('指代')) ?? '任务含指代但在最近对话中找不到先行词,必须先向用户确认'}`)
1115
+ }
1116
+ for (const missing of audit.stage3.missingHardAnchors.slice(0, 6)) {
1117
+ errors.push(`DEVIATION: 用户原要求中的硬要素「${missing}」在计划中完全缺失,请补回或说明为什么可以省略`)
1118
+ }
1119
+ /*
1120
+ * [P0-1] Missing domain coverage is blocking, not a warning: MS2 showed a
1121
+ * plan can look internally consistent while silently dropping design/legal/
1122
+ * security/devops, which is exactly what "必须高" cannot tolerate.
1123
+ */
1124
+ for (const entry of audit.stage2.missingDepartments.slice(0, 6)) {
1125
+ errors.push(`COVERAGE: 用户原要求涉及「${entry.departmentLabel}」领域(命中 ${entry.hits.slice(0, 4).join('、')}),计划既没有该部门的子任务,也没有在 taskUnderstanding.assumptions 写明「不安排${entry.departmentLabel}:理由」`)
1126
+ }
1127
+ for (const assignment of audit.stage2.assignments) {
1128
+ if (assignment.verdict !== 'mismatch') continue
1129
+ errors.push(`DEVIATION: 子任务 ${assignment.subtaskId || '(无 ID)'} 分配给「${assignment.departmentLabel}」缺乏依据:${assignment.reason}`)
1130
+ if (errors.length >= 12) break
1131
+ }
1132
+ }
1133
+
1134
+ return { ok: errors.length === 0, errors: errors.slice(0, 12), warnings: warnings.slice(0, 20), audit }
1135
+ }
1136
+
1137
+ /**
1138
+ * Compact audit kept on the plan message. The full audit (with evidence clauses)
1139
+ * stays available from `auditTaskUnderstanding`; the stored copy is trimmed so a
1140
+ * 15-subtask plan does not double its own JSON size.
1141
+ */
1142
+ export function compactUnderstandingAudit(audit: UnderstandingAudit): any {
1143
+ return {
1144
+ version: audit.version,
1145
+ anchor: audit.anchor
1146
+ ? { sha256: audit.anchor.sha256, length: audit.anchor.length, sourceMessageIds: audit.anchor.sourceMessageIds }
1147
+ : null,
1148
+ stage1: {
1149
+ elements: audit.stage1.elements.map((element) => ({ kind: element.kind, value: element.value, hard: element.hard })),
1150
+ hardCount: audit.stage1.hardCount,
1151
+ references: audit.stage1.references.map((reference) => ({
1152
+ token: reference.token,
1153
+ resolved: reference.resolved,
1154
+ resolvedBy: reference.resolvedBy,
1155
+ })),
1156
+ conflicts: audit.stage1.conflicts,
1157
+ },
1158
+ stage2: {
1159
+ assignments: audit.stage2.assignments.map((assignment) => ({
1160
+ subtaskId: assignment.subtaskId,
1161
+ department: assignment.department,
1162
+ verdict: assignment.verdict,
1163
+ score: assignment.score,
1164
+ matched: assignment.matched.slice(0, 5),
1165
+ reason: assignment.reason,
1166
+ declaredRationale: assignment.declaredRationale,
1167
+ })),
1168
+ departmentsUsed: audit.stage2.departmentsUsed,
1169
+ mismatches: audit.stage2.mismatches,
1170
+ requiredDepartments: audit.stage2.requiredDepartments.map((entry) => ({
1171
+ department: entry.department,
1172
+ departmentLabel: entry.departmentLabel,
1173
+ hits: entry.hits.slice(0, 4),
1174
+ })),
1175
+ missingDepartments: audit.stage2.missingDepartments.map((entry) => ({
1176
+ department: entry.department,
1177
+ departmentLabel: entry.departmentLabel,
1178
+ hits: entry.hits.slice(0, 4),
1179
+ })),
1180
+ excludedDepartments: audit.stage2.excludedDepartments.map((entry) => ({
1181
+ department: entry.department,
1182
+ departmentLabel: entry.departmentLabel,
1183
+ hits: entry.hits.slice(0, 4),
1184
+ reason: entry.reason,
1185
+ })),
1186
+ },
1187
+ stage3: {
1188
+ verdict: audit.stage3.verdict,
1189
+ rewritten: audit.stage3.rewritten,
1190
+ summaryCoverage: audit.stage3.summaryCoverage,
1191
+ droppedFromSummary: audit.stage3.droppedFromSummary,
1192
+ missingHardAnchors: audit.stage3.missingHardAnchors,
1193
+ missingDeliverables: audit.stage3.missingDeliverables,
1194
+ reasons: audit.stage3.reasons,
1195
+ },
1196
+ }
1197
+ }
1198
+
1199
+ /**
1200
+ * The department catalogue is the contract behind every match above; keep the
1201
+ * 12 ids in sync with `DEPARTMENTS` in plan.ts.
1202
+ */
1203
+ export const UNDERSTANDING_DEPARTMENT_IDS: readonly string[] = Object.freeze(
1204
+ DEPARTMENT_CAPABILITIES.map((entry) => entry.id),
1205
+ )