dsh-workplan 1.12.0 → 1.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runtime.ts CHANGED
@@ -13,8 +13,8 @@
13
13
  */
14
14
 
15
15
  import { randomUUID } from 'node:crypto'
16
- import { existsSync, statSync } from 'node:fs'
17
- import { isAbsolute, resolve } from 'node:path'
16
+ import { existsSync, realpathSync, statSync } from 'node:fs'
17
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
18
18
 
19
19
  import {
20
20
  MAX_CONCURRENT,
@@ -2443,7 +2443,12 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
2443
2443
  if (snap) {
2444
2444
  try {
2445
2445
  snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
2446
- status: update.status,
2446
+ /*
2447
+ * handoff 的 durable 记录携带的是状态快照,不是一次状态迁移。
2448
+ * 重放时若再走 done 分支,会把已经 reported 的行打回 done 并抛
2449
+ * INVALID_TRANSITION(wp-79c31abf 的 H1 就是这样被丢掉的)。
2450
+ */
2451
+ status: update.handoffs === undefined ? update.status : undefined,
2447
2452
  progress: typeof update.progress === 'number' ? update.progress : undefined,
2448
2453
  summary: typeof update.note === 'string' ? update.note : undefined,
2449
2454
  // [1.8.13] Evidence written through the update tool must survive replay.
@@ -2451,6 +2456,7 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
2451
2456
  acceptance: update.acceptance,
2452
2457
  artifacts: update.artifacts,
2453
2458
  missingArtifacts: update.missingArtifacts,
2459
+ handoffs: update.handoffs,
2454
2460
  revision: Number.isInteger(update.revision) ? update.revision : undefined,
2455
2461
  updatedBy: 'agent',
2456
2462
  })
@@ -5391,6 +5397,36 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5391
5397
  entries: Array<{ raw: string; canonical?: string; planIds: string[] }>
5392
5398
  }>()
5393
5399
 
5400
+ /*
5401
+ * [1.12.2] G3 修复:符号链接必须归一到同一个文件。
5402
+ * 1.8.18 的 canonicalPath 只做 path.resolve,同一个文件因此有无限种写法——
5403
+ * 交付的是 /a/report.md,改 /link/report.md(link 指向 a)就被放过。
5404
+ * 这里再用 realpath.native 把路径解析成真实身份,两侧都解析才能比对。
5405
+ * 文件尚不存在时解析最近的存在祖先后拼回剩余段落;完全解析不了时
5406
+ * 返回 undefined,调用方回落到旧的 path.resolve 结果(不改变旧行为)。
5407
+ */
5408
+ function realPathIdentity(value: string) {
5409
+ try {
5410
+ return realpathSync.native(value)
5411
+ } catch {
5412
+ // 文件可能尚未创建,继续找最近的存在祖先。
5413
+ }
5414
+ let cursor = value
5415
+ const tail: string[] = []
5416
+ for (let depth = 0; depth < 64; depth += 1) {
5417
+ const parent = dirname(cursor)
5418
+ if (!parent || parent === cursor) return undefined
5419
+ tail.unshift(basename(cursor))
5420
+ cursor = parent
5421
+ try {
5422
+ return join(realpathSync.native(cursor), ...tail)
5423
+ } catch {
5424
+ // 继续向上。
5425
+ }
5426
+ }
5427
+ return undefined
5428
+ }
5429
+
5394
5430
  function canonicalPath(session: any, value: any) {
5395
5431
  if (typeof value !== 'string' || value.trim() === '') return undefined
5396
5432
  if (isAbsolute(value)) return resolve(value)
@@ -5398,6 +5434,12 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5398
5434
  return typeof cwd === 'string' && cwd ? resolve(cwd, value) : undefined
5399
5435
  }
5400
5436
 
5437
+ function identityPath(session: any, value: any) {
5438
+ const canonical = canonicalPath(session, value)
5439
+ if (canonical === undefined) return undefined
5440
+ return realPathIdentity(canonical) ?? canonical
5441
+ }
5442
+
5401
5443
  function presentedEntries(session: any) {
5402
5444
  if (typeof session?.eventAt !== 'function' || !(Number(session.seq) >= 0)) return []
5403
5445
  const cache = presentedPaths.get(session.id)
@@ -5422,7 +5464,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5422
5464
  const planIds = [...seen]
5423
5465
  for (const file of event.data?.files ?? []) {
5424
5466
  if (typeof file?.path !== 'string' || file.path.trim() === '') continue
5425
- entries.push({ raw: file.path, canonical: canonicalPath(session, file.path), planIds })
5467
+ entries.push({ raw: file.path, canonical: identityPath(session, file.path), planIds })
5426
5468
  }
5427
5469
  }
5428
5470
  presentedPaths.set(session.id, {
@@ -5441,15 +5483,22 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5441
5483
 
5442
5484
  function presentedWriteDenialReason(agent: any, args: any) {
5443
5485
  const session = agent?.session
5444
- if (!session || !isRootSession(session)) return undefined
5486
+ if (!session) return undefined
5445
5487
  if (isPlanModeActive(ctx, session)) return undefined
5446
5488
  const entries = presentedEntries(session)
5447
5489
  if (entries.length === 0) return undefined
5448
5490
  const requested = args?.file_path ?? args?.path
5449
5491
  if (typeof requested !== 'string' || requested.trim() === '') return undefined
5450
- const canonical = canonicalPath(session, requested)
5492
+ // [1.12.2] G3: compare by real file identity (symlinks resolved).
5493
+ const canonical = identityPath(session, requested)
5494
+ /*
5495
+ * [1.12.2] G3: compare like-for-like. The entry now holds the real identity
5496
+ * of the presented path, so a link delivered earlier and a write through
5497
+ * the real path (or vice versa) resolve to the same string.
5498
+ */
5451
5499
  const matched = entries.filter((entry: any) =>
5452
5500
  entry.raw === requested
5501
+ || (entry.raw !== undefined && identityPath(session, entry.raw) === canonical)
5453
5502
  || (canonical !== undefined && entry.canonical !== undefined && entry.canonical === canonical))
5454
5503
  if (matched.length === 0) return undefined
5455
5504
  const planIds = new Set<string>()
@@ -5469,6 +5518,28 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5469
5518
  + '(present 之后新建的计划不受此限制。)'
5470
5519
  }
5471
5520
 
5521
+ /**
5522
+ * [1.12.2] G2: every path a single write call can touch.
5523
+ * apply_patch carries many files in one string; parsing the directives here
5524
+ * lets the guard deny the whole call instead of letting an unrelated path
5525
+ * in the arguments form a blind spot.
5526
+ */
5527
+ function writeTargets(_agent: any, args: any): string[] {
5528
+ const targets: string[] = []
5529
+ const single = args?.file_path ?? args?.path
5530
+ if (typeof single === 'string' && single.trim() !== '') targets.push(single)
5531
+ const patch = typeof args?.input === 'string' ? args.input : (typeof args?.patch === 'string' ? args.patch : '')
5532
+ if (patch) {
5533
+ const directive = /^\*\*\* (?:Update File|Add File|Delete File|Move to): (.+)$/gm
5534
+ let match
5535
+ while ((match = directive.exec(patch)) !== null) {
5536
+ const path = match[1].trim()
5537
+ if (path !== '') targets.push(path)
5538
+ }
5539
+ }
5540
+ return targets
5541
+ }
5542
+
5472
5543
  function plansPayload(sessionId: any) {
5473
5544
  /*
5474
5545
  * [1.8.15] The feed must carry build identity too.
@@ -5561,6 +5632,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5561
5632
  presentDenialVerdict,
5562
5633
  supersededDenialVerdict,
5563
5634
  presentedWriteDenialReason,
5635
+ writeTargets,
5564
5636
  updateStatus,
5565
5637
  cancelPlan,
5566
5638
  dispatchTool,
@@ -76,6 +76,24 @@ export const MAX_AUDITED_SUBTASKS = 15
76
76
  */
77
77
  export const MISMATCH_BLOCKING_SCORE = 3
78
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
+
79
97
  /** Hard anchors are the only elements that can fail a plan by themselves. */
80
98
  export type TaskElementKind =
81
99
  | 'version'
@@ -98,9 +116,15 @@ export interface TaskElement {
98
116
 
99
117
  export interface TaskReference {
100
118
  token: string
101
- /** `context` = resolved by conversation; `inline-noun` = e.g. 「这个插件」. */
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
+ */
102
124
  resolvedBy: 'context' | 'inline-noun' | 'none'
103
125
  resolved: boolean
126
+ /** The noun phrase taken from the conversation that this token points at. */
127
+ antecedent?: string
104
128
  evidence: string
105
129
  }
106
130
 
@@ -138,6 +162,13 @@ export interface DepartmentAssignment {
138
162
  declaredRationale: string
139
163
  }
140
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
+
141
172
  export interface TaskAnchor {
142
173
  text: string
143
174
  sha256: string
@@ -160,6 +191,12 @@ export interface UnderstandingAudit {
160
191
  assignments: DepartmentAssignment[]
161
192
  departmentsUsed: string[]
162
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 }>
163
200
  }
164
201
  stage3: {
165
202
  verdict: 'aligned' | 'deviation' | 'needs-clarification' | 'needs-context' | 'degraded'
@@ -431,22 +468,192 @@ function extractReferences(text: string): TaskReference[] {
431
468
  })
432
469
  }
433
470
  }
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
- }
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
+ })
446
489
  }
447
490
  return references
448
491
  }
449
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
+
450
657
  function extractConflicts(text: string): TaskConflict[] {
451
658
  const conflicts: TaskConflict[] = []
452
659
  const seen = new Set<string>()
@@ -551,6 +758,57 @@ function flattenPlanSubtasks(plan: any): any[] {
551
758
  return subtasks
552
759
  }
553
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
+
554
812
  /**
555
813
  * Explain one department choice with the catalog keywords that support it.
556
814
  *
@@ -682,7 +940,7 @@ function emptyAudit(anchor: TaskAnchor | null, reason: string): UnderstandingAud
682
940
  version: UNDERSTANDING_AUDIT_VERSION,
683
941
  anchor,
684
942
  stage1: { elements: [], hardCount: 0, references: [], conflicts: [], deliverableClauses: [] },
685
- stage2: { assignments: [], departmentsUsed: [], mismatches: [] },
943
+ stage2: { assignments: [], departmentsUsed: [], mismatches: [], requiredDepartments: [], missingDepartments: [], excludedDepartments: [] },
686
944
  stage3: {
687
945
  verdict: 'degraded',
688
946
  rewritten: false,
@@ -713,6 +971,7 @@ export function auditTaskUnderstanding(plan: any, context: PlanAuditContext = {}
713
971
  const planText = collectPlanText(plan)
714
972
  const assignments = flattenPlanSubtasks(plan).map((subtask) => departmentFit(subtask, taskText))
715
973
  const departmentsUsed = [...new Set(assignments.map((entry) => entry.department))]
974
+ const coverage = auditDepartmentCoverage(taskText, plan)
716
975
  const mismatches = assignments
717
976
  .filter((entry) => entry.verdict === 'mismatch')
718
977
  .map((entry) => `${entry.subtaskId || '(无 ID)'} → ${entry.departmentLabel}:${entry.reason}`)
@@ -741,15 +1000,25 @@ export function auditTaskUnderstanding(plan: any, context: PlanAuditContext = {}
741
1000
  const hardTotal = extracted.elements.filter((element) => element.hard).length
742
1001
  const summaryCoverage = hardTotal === 0 ? 1 : (hardTotal - droppedFromSummary.length) / hardTotal
743
1002
 
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
- ))
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)
753
1022
 
754
1023
  const reasons: string[] = []
755
1024
  let verdict: UnderstandingAudit['stage3']['verdict'] = 'aligned'
@@ -757,6 +1026,10 @@ export function auditTaskUnderstanding(plan: any, context: PlanAuditContext = {}
757
1026
  verdict = 'deviation'
758
1027
  reasons.push(`用户原要求中的 ${missingHardAnchors.length} 个硬要素在计划中完全缺失:${missingHardAnchors.slice(0, 6).join('、')}`)
759
1028
  }
1029
+ if (coverage.missing.length > 0) {
1030
+ verdict = 'deviation'
1031
+ reasons.push(`用户原要求涉及 ${coverage.missing.length} 个部门领域,计划既未安排也未写明排除理由:${coverage.missing.map((entry) => entry.departmentLabel).join('、')}`)
1032
+ }
760
1033
  if (mismatches.length > 0) {
761
1034
  if (verdict === 'aligned') verdict = 'deviation'
762
1035
  reasons.push(`${mismatches.length} 个子任务的部门与用户原要求矛盾:${mismatches.slice(0, 4).join(';')}`)
@@ -767,7 +1040,7 @@ export function auditTaskUnderstanding(plan: any, context: PlanAuditContext = {}
767
1040
  }
768
1041
  if (unresolved.length > 0) {
769
1042
  if (verdict === 'aligned') verdict = 'needs-context'
770
- reasons.push(`含指代的任务缺少对话上下文:${unresolved.map((reference) => reference.token).join('、')},不应在未澄清前派发`)
1043
+ reasons.push(`含指代的任务在最近对话里找不到先行词:${unresolved.map((reference) => reference.token).join('、')},不应在未澄清前派发`)
771
1044
  }
772
1045
  if (verdict === 'aligned') {
773
1046
  reasons.push(`硬要素 ${hardTotal - missingHardAnchors.length}/${hardTotal} 全部保留;${assignments.length} 个子任务的部门有目录关键词支撑`)
@@ -783,7 +1056,14 @@ export function auditTaskUnderstanding(plan: any, context: PlanAuditContext = {}
783
1056
  conflicts: extracted.conflicts,
784
1057
  deliverableClauses: extracted.deliverableClauses,
785
1058
  },
786
- stage2: { assignments, departmentsUsed, mismatches },
1059
+ stage2: {
1060
+ assignments,
1061
+ departmentsUsed,
1062
+ mismatches,
1063
+ requiredDepartments: coverage.required,
1064
+ missingDepartments: coverage.missing,
1065
+ excludedDepartments: coverage.excluded,
1066
+ },
787
1067
  stage3: {
788
1068
  verdict,
789
1069
  rewritten: !verbatim,
@@ -831,11 +1111,19 @@ export function validatePlanContext(plan: any, context: PlanAuditContext = {}):
831
1111
  errors.push(`CLARIFY: ${audit.stage3.reasons.find((reason) => reason.includes('自相矛盾')) ?? '用户要求存在矛盾,必须先向用户确认'}`)
832
1112
  }
833
1113
  if (audit.stage3.verdict === 'needs-context') {
834
- errors.push(`CONTEXT: ${audit.stage3.reasons.find((reason) => reason.includes('指代')) ?? '任务含指代但缺少对话上下文,必须先向用户确认'}`)
1114
+ errors.push(`CONTEXT: ${audit.stage3.reasons.find((reason) => reason.includes('指代')) ?? '任务含指代但在最近对话中找不到先行词,必须先向用户确认'}`)
835
1115
  }
836
1116
  for (const missing of audit.stage3.missingHardAnchors.slice(0, 6)) {
837
1117
  errors.push(`DEVIATION: 用户原要求中的硬要素「${missing}」在计划中完全缺失,请补回或说明为什么可以省略`)
838
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
+ }
839
1127
  for (const assignment of audit.stage2.assignments) {
840
1128
  if (assignment.verdict !== 'mismatch') continue
841
1129
  errors.push(`DEVIATION: 子任务 ${assignment.subtaskId || '(无 ID)'} 分配给「${assignment.departmentLabel}」缺乏依据:${assignment.reason}`)
@@ -879,6 +1167,22 @@ export function compactUnderstandingAudit(audit: UnderstandingAudit): any {
879
1167
  })),
880
1168
  departmentsUsed: audit.stage2.departmentsUsed,
881
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
+ })),
882
1186
  },
883
1187
  stage3: {
884
1188
  verdict: audit.stage3.verdict,