dsh-workplan 1.12.1 → 1.12.3

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,
@@ -25,6 +25,7 @@ import {
25
25
  blockCancelledDependents,
26
26
  buildChildPrompt,
27
27
  buildCancelMessage,
28
+ buildClarifyMessage,
28
29
  buildDegradedMessage,
29
30
  buildPlanMessage,
30
31
  buildPlannerPrompt,
@@ -71,7 +72,7 @@ import {
71
72
  MAX_HANDOFF_RESPONSE_CHARS,
72
73
  } from './plan.js'
73
74
  import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
74
- import { compactUnderstandingAudit, validatePlanContext } from './understanding.js'
75
+ import { auditClarifyNeed, compactUnderstandingAudit, validatePlanContext } from './understanding.js'
75
76
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js'
76
77
  import { supersedePlanRecord } from './supersede.js'
77
78
  import { createProgressWatchdog, describeError } from './watchdog.js'
@@ -2770,6 +2771,27 @@ export type WorkplanRuntimeOptions = {
2770
2771
  * 派发)。plan 模式、已有计划执行中、预算/取消/幂等/交付门禁不受影响。
2771
2772
  */
2772
2773
  autoDispatch?: boolean
2774
+ /**
2775
+ * [1.12.3] headless「未完成不得成功收尾」硬闸门(fail-closed)。
2776
+ *
2777
+ * 事故(session-99984ebd…)暴露的最后一个缺口:`agent/turn-stopping` 的
2778
+ * steer 每个回合最多 2 次,用尽后闸门只能沉默放行;而官方 headless runner
2779
+ * 的完成判据是 `turn/end reason.kind === 'completed'`,它并不认识计划,
2780
+ * 于是「计划未完成但回合正常收尾」= 打印正文 + exit 0,自动化仍把它当成成功。
2781
+ *
2782
+ * 语义:
2783
+ * - `'auto'`(默认):只在 headless 运行中启用——判据是运行上下文提供了
2784
+ * 官方 headless 专属服务 `headlessStartup`(packages/bundle/headless/
2785
+ * src/startup.ts 提供,web/tui profile 不提供)。交互式会话行为不变。
2786
+ * - `true` / `false`:显式打开 / 关闭。
2787
+ *
2788
+ * 启用后:steer 次数用尽而计划仍未通过交付就绪检查时,闸门抛
2789
+ * `PlanError('WORKPLAN_INCOMPLETE')`。官方 `agent/turn-stopping` 是 serial
2790
+ * 事件(cordis `serial()` 逐个 await,监听器抛错会向上传播),因此该回合以
2791
+ * `error` 结束;headless runner 的 `failure` 非空 ⇒ 不打印「已完成」正文、
2792
+ * 以非零退出码结束(packages/bundle/headless/src/index.ts 的 fail())。
2793
+ */
2794
+ failClosedOnIncomplete?: boolean | 'auto'
2773
2795
  /**
2774
2796
  * [1.8.13] Package version, supplied by the host from its `meta.version`.
2775
2797
  *
@@ -2810,6 +2832,19 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2810
2832
  * resume, cancel, the host's tool timeout) agrees on the same numbers.
2811
2833
  */
2812
2834
  const pluginVersion = typeof options.version === 'string' && options.version ? options.version : 'unknown'
2835
+ /*
2836
+ * [1.12.3] fail-closed 解析:显式值优先;'auto' 只在 headless 运行中生效。
2837
+ * `ctx.get` 在普通对象(测试)上不存在,可选链保证降级为「非 headless」。
2838
+ */
2839
+ const failClosedMode: boolean | 'auto' = options.failClosedOnIncomplete ?? 'auto'
2840
+ const headlessRun = (() => {
2841
+ try {
2842
+ return ctx?.get?.('headlessStartup') !== undefined
2843
+ } catch {
2844
+ return false
2845
+ }
2846
+ })()
2847
+ const failClosedActive = failClosedMode === true || (failClosedMode === 'auto' && headlessRun)
2813
2848
  /*
2814
2849
  * [1.8.14] Build identity, captured once.
2815
2850
  *
@@ -5033,7 +5068,34 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5033
5068
  const book = record.stopSteers && record.stopSteers.turn === turn
5034
5069
  ? record.stopSteers
5035
5070
  : { turn, count: 0 }
5036
- if (book.count >= STOP_STEER_LIMIT) return
5071
+ if (book.count >= STOP_STEER_LIMIT) {
5072
+ /*
5073
+ * [1.12.3] steer 用尽后不再沉默放行。
5074
+ *
5075
+ * 旧行为(1.8.7–1.12.2):达到上限就 `return`,回合正常收尾。对交互式
5076
+ * 会话这是「避免死循环」;对 headless 却是事故复现路径——官方 runner 只
5077
+ * 看 `turn/end reason.kind==='completed'`,它会把「计划未完成但回合正常
5078
+ * 结束」打印成结果并 exit 0(session-99984ebd… 的最终现场)。
5079
+ *
5080
+ * 现在:headless(或显式开启)时抛 WORKPLAN_INCOMPLETE。turn-stopping
5081
+ * 是 serial 事件,抛错 ⇒ 该回合以 error 收尾 ⇒ runner 走 fail():
5082
+ * 不打印正文、非零退出。交互式会话维持原样(只 steer,不抛错)。
5083
+ */
5084
+ if (failClosedActive) {
5085
+ const stuck = derivePlanSnapshot(record.statuses)
5086
+ const remaining = (stuck.statuses ?? [])
5087
+ .filter((item: any) => item.status !== 'done')
5088
+ .map((item: any) => String(item.subtaskId))
5089
+ throw new PlanError(
5090
+ `未完成:剩余 ${remaining.length} 项(${remaining.join(', ')})与原因——计划 ${record.plan.planId} `
5091
+ + `仅完成 ${stuck.stats.done}/${stuck.stats.total},本回合已连续 ${book.count} 次被要求续跑/补证,`
5092
+ + '仍未通过交付就绪检查。headless 以非零退出码结束,不输出「已完成」结果。',
5093
+ 'WORKPLAN_INCOMPLETE',
5094
+ { planId: record.plan.planId, stats: stuck.stats, remaining },
5095
+ )
5096
+ }
5097
+ return
5098
+ }
5037
5099
  book.count += 1
5038
5100
  record.stopSteers = book
5039
5101
  const snapshot = derivePlanSnapshot(record.statuses)
@@ -5058,6 +5120,11 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5058
5120
  + `已在回合收尾前要求继续/如实收尾(第 ${book.count} 次)`,
5059
5121
  )
5060
5122
  } catch (error) {
5123
+ /*
5124
+ * [1.12.3] fail-closed 的硬失败必须穿过这层日志包装:
5125
+ * 这里原本把任何异常降级成一条 warn,等于把上面的抛错又吃掉。
5126
+ */
5127
+ if (error instanceof PlanError && error.code === 'WORKPLAN_INCOMPLETE') throw error
5061
5128
  ctx.logger?.warn?.(`dsh-workplan: 回合收尾检查失败:${error instanceof Error ? error.message : String(error)}`)
5062
5129
  }
5063
5130
  }
@@ -5397,6 +5464,36 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5397
5464
  entries: Array<{ raw: string; canonical?: string; planIds: string[] }>
5398
5465
  }>()
5399
5466
 
5467
+ /*
5468
+ * [1.12.2] G3 修复:符号链接必须归一到同一个文件。
5469
+ * 1.8.18 的 canonicalPath 只做 path.resolve,同一个文件因此有无限种写法——
5470
+ * 交付的是 /a/report.md,改 /link/report.md(link 指向 a)就被放过。
5471
+ * 这里再用 realpath.native 把路径解析成真实身份,两侧都解析才能比对。
5472
+ * 文件尚不存在时解析最近的存在祖先后拼回剩余段落;完全解析不了时
5473
+ * 返回 undefined,调用方回落到旧的 path.resolve 结果(不改变旧行为)。
5474
+ */
5475
+ function realPathIdentity(value: string) {
5476
+ try {
5477
+ return realpathSync.native(value)
5478
+ } catch {
5479
+ // 文件可能尚未创建,继续找最近的存在祖先。
5480
+ }
5481
+ let cursor = value
5482
+ const tail: string[] = []
5483
+ for (let depth = 0; depth < 64; depth += 1) {
5484
+ const parent = dirname(cursor)
5485
+ if (!parent || parent === cursor) return undefined
5486
+ tail.unshift(basename(cursor))
5487
+ cursor = parent
5488
+ try {
5489
+ return join(realpathSync.native(cursor), ...tail)
5490
+ } catch {
5491
+ // 继续向上。
5492
+ }
5493
+ }
5494
+ return undefined
5495
+ }
5496
+
5400
5497
  function canonicalPath(session: any, value: any) {
5401
5498
  if (typeof value !== 'string' || value.trim() === '') return undefined
5402
5499
  if (isAbsolute(value)) return resolve(value)
@@ -5404,6 +5501,12 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5404
5501
  return typeof cwd === 'string' && cwd ? resolve(cwd, value) : undefined
5405
5502
  }
5406
5503
 
5504
+ function identityPath(session: any, value: any) {
5505
+ const canonical = canonicalPath(session, value)
5506
+ if (canonical === undefined) return undefined
5507
+ return realPathIdentity(canonical) ?? canonical
5508
+ }
5509
+
5407
5510
  function presentedEntries(session: any) {
5408
5511
  if (typeof session?.eventAt !== 'function' || !(Number(session.seq) >= 0)) return []
5409
5512
  const cache = presentedPaths.get(session.id)
@@ -5428,7 +5531,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5428
5531
  const planIds = [...seen]
5429
5532
  for (const file of event.data?.files ?? []) {
5430
5533
  if (typeof file?.path !== 'string' || file.path.trim() === '') continue
5431
- entries.push({ raw: file.path, canonical: canonicalPath(session, file.path), planIds })
5534
+ entries.push({ raw: file.path, canonical: identityPath(session, file.path), planIds })
5432
5535
  }
5433
5536
  }
5434
5537
  presentedPaths.set(session.id, {
@@ -5447,15 +5550,22 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5447
5550
 
5448
5551
  function presentedWriteDenialReason(agent: any, args: any) {
5449
5552
  const session = agent?.session
5450
- if (!session || !isRootSession(session)) return undefined
5553
+ if (!session) return undefined
5451
5554
  if (isPlanModeActive(ctx, session)) return undefined
5452
5555
  const entries = presentedEntries(session)
5453
5556
  if (entries.length === 0) return undefined
5454
5557
  const requested = args?.file_path ?? args?.path
5455
5558
  if (typeof requested !== 'string' || requested.trim() === '') return undefined
5456
- const canonical = canonicalPath(session, requested)
5559
+ // [1.12.2] G3: compare by real file identity (symlinks resolved).
5560
+ const canonical = identityPath(session, requested)
5561
+ /*
5562
+ * [1.12.2] G3: compare like-for-like. The entry now holds the real identity
5563
+ * of the presented path, so a link delivered earlier and a write through
5564
+ * the real path (or vice versa) resolve to the same string.
5565
+ */
5457
5566
  const matched = entries.filter((entry: any) =>
5458
5567
  entry.raw === requested
5568
+ || (entry.raw !== undefined && identityPath(session, entry.raw) === canonical)
5459
5569
  || (canonical !== undefined && entry.canonical !== undefined && entry.canonical === canonical))
5460
5570
  if (matched.length === 0) return undefined
5461
5571
  const planIds = new Set<string>()
@@ -5475,6 +5585,28 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5475
5585
  + '(present 之后新建的计划不受此限制。)'
5476
5586
  }
5477
5587
 
5588
+ /**
5589
+ * [1.12.2] G2: every path a single write call can touch.
5590
+ * apply_patch carries many files in one string; parsing the directives here
5591
+ * lets the guard deny the whole call instead of letting an unrelated path
5592
+ * in the arguments form a blind spot.
5593
+ */
5594
+ function writeTargets(_agent: any, args: any): string[] {
5595
+ const targets: string[] = []
5596
+ const single = args?.file_path ?? args?.path
5597
+ if (typeof single === 'string' && single.trim() !== '') targets.push(single)
5598
+ const patch = typeof args?.input === 'string' ? args.input : (typeof args?.patch === 'string' ? args.patch : '')
5599
+ if (patch) {
5600
+ const directive = /^\*\*\* (?:Update File|Add File|Delete File|Move to): (.+)$/gm
5601
+ let match
5602
+ while ((match = directive.exec(patch)) !== null) {
5603
+ const path = match[1].trim()
5604
+ if (path !== '') targets.push(path)
5605
+ }
5606
+ }
5607
+ return targets
5608
+ }
5609
+
5478
5610
  function plansPayload(sessionId: any) {
5479
5611
  /*
5480
5612
  * [1.8.15] The feed must carry build identity too.
@@ -5567,6 +5699,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5567
5699
  presentDenialVerdict,
5568
5700
  supersededDenialVerdict,
5569
5701
  presentedWriteDenialReason,
5702
+ writeTargets,
5570
5703
  updateStatus,
5571
5704
  cancelPlan,
5572
5705
  dispatchTool,
@@ -5583,6 +5716,15 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5583
5716
  }
5584
5717
  }
5585
5718
 
5719
+ /**
5720
+ * [1.12.3] 澄清闸门的退出口。默认开启;只有显式设成 0/false/off 才回到旧行为
5721
+ * (信息不足也照做计划、照派发)。
5722
+ */
5723
+ function clarifyGateDisabled() {
5724
+ const raw = String(process.env.DSH_WORKPLAN_CLARIFY_GATE ?? '').trim().toLowerCase()
5725
+ return raw === '0' || raw === 'false' || raw === 'off'
5726
+ }
5727
+
5586
5728
  function resolveModelSelection(ctx: any, payload: any) {
5587
5729
  const direct = payload.modelSelection
5588
5730
  if (direct?.provider && direct?.model) {
@@ -5720,6 +5862,39 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
5720
5862
  }
5721
5863
  return downstream
5722
5864
  }
5865
+ /*
5866
+ * [1.12.3] 信息不足就不做计划、不派发——只问一句。
5867
+ *
5868
+ * 用户在 2026-11-04 拍板:自动派发改成「只在信息不足这一类上拦截」,其余照旧。
5869
+ * 因此拦截点放在规划之前,而不是关掉自动派发:缺信息时连计划都不生成,
5870
+ * 免得部门 Agent 对着一个猜出来的目标开工。
5871
+ * 关闭方式:DSH_WORKPLAN_CLARIFY_GATE=0(保留给需要旧行为的自动化)。
5872
+ */
5873
+ if (!clarifyGateDisabled()) {
5874
+ const clarify = auditClarifyNeed(taskText, conversationContext)
5875
+ if (clarify.needed) {
5876
+ const createdAt = Date.now()
5877
+ state.records.set(session.id, {
5878
+ planId: null,
5879
+ plan: null,
5880
+ title: '任务信息不足(先澄清)',
5881
+ degraded: false,
5882
+ clarify: true,
5883
+ error: clarify.reason,
5884
+ statuses: [],
5885
+ phase: 'clarify',
5886
+ errors: [truncate(clarify.reason, 1000)],
5887
+ createdAt,
5888
+ updatedAt: createdAt,
5889
+ createdTurn: payload.turn,
5890
+ })
5891
+ return enterDecision(downstream, [buildClarifyMessage({
5892
+ rule: clarify.rule,
5893
+ reason: clarify.reason,
5894
+ question: clarify.question,
5895
+ })])
5896
+ }
5897
+ }
5723
5898
  const modelSelection = resolveModelSelection(ctx, payload)
5724
5899
  if (!modelSelection?.provider || !modelSelection?.model) {
5725
5900
  const message = buildDegradedMessage({
@@ -118,12 +118,13 @@ export interface TaskReference {
118
118
  token: string
119
119
  /**
120
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.
121
+ * conversation and quoted in `antecedent`; `task-text` = the referent was
122
+ * named in the user's own task text (the pronoun's sentence, or the sentence
123
+ * right before it); `inline-noun` = e.g. 「这个插件」; `none` = still ambiguous.
123
124
  */
124
- resolvedBy: 'context' | 'inline-noun' | 'none'
125
+ resolvedBy: 'context' | 'task-text' | 'inline-noun' | 'none'
125
126
  resolved: boolean
126
- /** The noun phrase taken from the conversation that this token points at. */
127
+ /** The noun phrase (from the conversation or the task text) the token points at. */
127
128
  antecedent?: string
128
129
  evidence: string
129
130
  }
@@ -559,6 +560,238 @@ export function resolvePronounAntecedent(token: string, conversationContext: str
559
560
  return null
560
561
  }
561
562
 
563
+ /**
564
+ * [T3] Resolve a pronoun from the task text itself, in the sentence that holds
565
+ * it or the sentence immediately before it.
566
+ *
567
+ * MS2 T05-08 read 「…159667工业母机ETF国泰,下月全月…?准确预判后…告诉我,它每天…」
568
+ * — the name sits in the PREVIOUS sentence while the pronoun's own sentence is
569
+ * pure prose, so conversation-only resolution rejected the task as "no
570
+ * antecedent". A name the user wrote in the task is the strongest possible
571
+ * antecedent, so the task text is searched too:
572
+ *
573
+ * 1. the current sentence, before the pronoun;
574
+ * 2. only if that has no referent, the sentence right before it.
575
+ *
576
+ * Only explicit referents qualify: a quoted name, or an identifier-like span
577
+ * (「159667工业母机ETF国泰」/「159667」/「dsh-workplan」) — the boundaries a reader
578
+ * would use. Ordinary prose never qualifies, so a pronoun with no real referent
579
+ * still blocks (`needs-context`) instead of being resolved to filler.
580
+ *
581
+ * The scope is deliberately narrow: reaching further produced wrong antecedents
582
+ * in replay ("…昨天涨了" taken as a name). A blocked plan is recoverable; a plan
583
+ * dispatched on a guessed referent is not.
584
+ */
585
+ const INLINE_SENTENCE_BOUNDARY = /[。!?!?\n]/
586
+ const INLINE_NAME_CHAR = /[\u4e00-\u9fffA-Za-z0-9._-]/
587
+ const INLINE_ENTITY_STOP = new Set('的是了在有我你他她它们这那吗呢吧啊呀就都也还又很太更最把被让给从到与和及或而但却则其该此每各么怎如何走涨跌买卖加减看好'.split(''))
588
+ const LEADING_REQUEST = /^(?:看一下|看下|看看|帮我|帮忙|麻烦|给我|我们|必须|需要|想要|关注|推荐|分析|预判|预测|研究|介绍|说说|告诉|查一下|查查|对比|比较|关于|针对|请|我|你|想|要|把|将|对)\s*/
589
+
590
+ function isInlineSentenceBoundary(char: string | undefined): boolean {
591
+ return !!char && INLINE_SENTENCE_BOUNDARY.test(char)
592
+ }
593
+
594
+ function isInlineNameChar(char: string | undefined): boolean {
595
+ return !!char && INLINE_NAME_CHAR.test(char)
596
+ }
597
+
598
+ /** Drop request lead-ins so "我关注159667…" reads as the name, not the sentence. */
599
+ function stripRequestPrefixes(fragment: string): string {
600
+ let value = fragment
601
+ for (let round = 0; round < 3; round += 1) {
602
+ const next = value.replace(LEADING_REQUEST, '')
603
+ if (next === value) break
604
+ value = next
605
+ }
606
+ return value.trim()
607
+ }
608
+
609
+ /**
610
+ * Is this span an explicit referent rather than a piece of prose?
611
+ *
612
+ * An explicit referent carries an identifier signal (a 4+ digit code such as
613
+ * 159667, or a Latin run such as ETF / dsh-workplan) and contains no function
614
+ * word. That keeps 「159667工业母机ETF国泰」 and drops 「是我重点关注的基金」.
615
+ * Dates (「11月」/「2026年」) and bare numbers are not referents.
616
+ */
617
+ function isExplicitEntityToken(value: string): boolean {
618
+ const token = value.trim()
619
+ if (token.length < 2 || token.length > 24) return false
620
+ if (/^(?:它|他|她|其)(?:们)?$/.test(token)) return false
621
+ if (/^\d{1,4}(?:年|月|日|号)/.test(token)) return false
622
+ if (/^\d{1,2}$/.test(token)) return false
623
+ // A bare instrument category names a class, not one instrument.
624
+ if (/^(?:ETF|LOF|QDII|A股|港股|美股)$/.test(token)) return false
625
+ const hasCode = /\d{4,}/.test(token)
626
+ const hasLatin = /[A-Za-z]{2,}/.test(token)
627
+ const mixedSignal = /[A-Za-z]\d|\d[A-Za-z]/.test(token)
628
+ if (!hasCode && !hasLatin && !mixedSignal) return false
629
+ for (const char of token) {
630
+ if (INLINE_ENTITY_STOP.has(char)) return false
631
+ }
632
+ return !FUNCTION_WORD_ONLY.test(token)
633
+ }
634
+
635
+ /**
636
+ * Take the explicit referent out of one punctuation/space-delimited fragment.
637
+ *
638
+ * A clean fragment is kept whole; otherwise the identifier and the name
639
+ * characters attached to it are cut out, stopping at the first function word
640
+ * or verb ("159667工业母机ETF国泰是我重点…" -> "159667工业母机ETF国泰").
641
+ */
642
+ function inlineEntityCore(fragment: string): string | null {
643
+ const raw = stripRequestPrefixes(fragment).replace(/[。!?!?…]+$/, '').trim()
644
+ if (!raw) return null
645
+ if (isExplicitEntityToken(raw)) return raw
646
+ const anchor = /\d{2,}|[A-Za-z]{2,}/.exec(raw)
647
+ if (!anchor) return null
648
+ let start = anchor.index
649
+ while (start > 0 && isInlineNameChar(raw[start - 1]) && !INLINE_ENTITY_STOP.has(raw[start - 1])) start -= 1
650
+ let end = anchor.index + anchor[0].length
651
+ while (end < raw.length && isInlineNameChar(raw[end]) && !INLINE_ENTITY_STOP.has(raw[end])) end += 1
652
+ const value = raw.slice(start, end).replace(/[.\-_]+$/, '').trim()
653
+ return isExplicitEntityToken(value) ? value : null
654
+ }
655
+
656
+ /** Find the last explicit referent inside one sentence span. */
657
+ function findExplicitEntity(span: string): AntecedentResult | null {
658
+ const text = span.trim()
659
+ if (!text) return null
660
+ const quoted = [...text.matchAll(/[「『“"《]([^」』”"》\n]{2,24})[」』”"》]/g)]
661
+ for (let i = quoted.length - 1; i >= 0; i -= 1) {
662
+ const value = quoted[i][1].trim()
663
+ if (isExplicitEntityToken(value)) return { antecedent: value, source: text.slice(-80) }
664
+ }
665
+ const fragments = text.split(/[,,、;;::\s]+/)
666
+ for (let i = fragments.length - 1; i >= 0; i -= 1) {
667
+ const value = inlineEntityCore(fragments[i])
668
+ if (value) return { antecedent: value, source: text.slice(-80) }
669
+ }
670
+ return null
671
+ }
672
+
673
+ /** Bounds of the sentence around `index`, plus the sentence immediately before. */
674
+ function inlineSentenceBounds(text: string, index: number): { start: number; prevStart: number; prevEnd: number } {
675
+ let start = 0
676
+ for (let i = index - 1; i >= 0; i -= 1) {
677
+ if (isInlineSentenceBoundary(text[i])) {
678
+ start = i + 1
679
+ break
680
+ }
681
+ }
682
+ let prevEnd = start
683
+ while (prevEnd > 0 && isInlineSentenceBoundary(text[prevEnd - 1])) prevEnd -= 1
684
+ let prevStart = 0
685
+ for (let i = prevEnd - 1; i >= 0; i -= 1) {
686
+ if (isInlineSentenceBoundary(text[i])) {
687
+ prevStart = i + 1
688
+ break
689
+ }
690
+ }
691
+ return { start, prevStart, prevEnd }
692
+ }
693
+
694
+ /** 「其它」 is a word, not a pronoun: skip it and use the real occurrence. */
695
+ function lastInlineReferenceIndex(text: string, token: string): number {
696
+ let index = text.lastIndexOf(token)
697
+ while (index > 0 && token === '它' && text[index - 1] === '其') {
698
+ index = text.lastIndexOf(token, index - 1)
699
+ }
700
+ return index
701
+ }
702
+
703
+ export function resolvePronounAntecedentInline(token: string, taskText: string): AntecedentResult | null {
704
+ const text = String(taskText ?? '')
705
+ if (!text || text.length > MAX_TASK_ANCHOR_CHARS) return null
706
+ const index = lastInlineReferenceIndex(text, token)
707
+ if (index <= 0) return null
708
+ const bounds = inlineSentenceBounds(text, index)
709
+ const current = findExplicitEntity(text.slice(bounds.start, index))
710
+ if (current) return current
711
+ if (bounds.prevEnd > bounds.prevStart) {
712
+ const previous = findExplicitEntity(text.slice(bounds.prevStart, bounds.prevEnd))
713
+ if (previous) return previous
714
+ }
715
+ return null
716
+ }
717
+
718
+ /**
719
+ * [P0-2c] Decide whether a task is missing information the user must supply.
720
+ *
721
+ * MS2's four clarify cases (T05-04/09/13/20) were planned and dispatched anyway.
722
+ * Each failed for a *checkable* reason, so each gets a deterministic rule instead
723
+ * of a vibe:
724
+ *
725
+ * C1 bare agreement — the text is an answer to a question the model never saw
726
+ * (「同意移入」) and carries an identifier it never defines (R-W5-01).
727
+ * C2 dangling artifact — an internal reference (T4 草稿, W5) that is not defined
728
+ * in the task and not present in the conversation.
729
+ * C3 missing target — a forecast/trend request with no identifiable subject
730
+ * (「准确预测11月全月详细、具体走势」: which instrument? which year?).
731
+ * C4 missing UI object — a display change (折叠/展开/按钮…) that names no surface
732
+ * (左侧栏/截图/插件…), so any implementation would be a guess.
733
+ */
734
+ export function auditClarifyNeed(
735
+ taskText: unknown,
736
+ conversationContext = '',
737
+ ): { needed: boolean; rule: string; reason: string; question: string } {
738
+ const text = String(taskText ?? '').trim()
739
+ const conversation = String(conversationContext ?? '')
740
+ if (!text) return { needed: false, rule: '', reason: '', question: '' }
741
+ const both = text + '\n' + conversation
742
+
743
+ const AGREEMENT = /(?:^|[。;;!!\n])\s*(?:同意|赞成|可以|好的|没问题|就按|按你说的|确认)/
744
+ // No trailing \b: a CJK char is a non-word char, so 「T4 草稿」 has no word
745
+ // boundary after 稿 and the id would silently never match.
746
+ const DANGLING_ID = /(?:R-[A-Z]{1,4}-\d{1,4}|W\d{1,3}\b|T\d{1,3}\s*草稿)/
747
+ if (AGREEMENT.test(text) && (DANGLING_ID.test(text) || text.length <= 24) && !DANGLING_ID.test(conversation)) {
748
+ return {
749
+ needed: true,
750
+ rule: 'C1',
751
+ reason: '任务只是对上文问题的表态,且引用了任务里没有定义的编号,缺上文',
752
+ question: '你这句话是在回答哪个问题?请把上文的问题、或你要「同意/移入」的具体对象说清楚。',
753
+ }
754
+ }
755
+ const dangling = text.match(DANGLING_ID)
756
+ if (dangling && !conversation.includes(dangling[0])) {
757
+ return {
758
+ needed: true,
759
+ rule: 'C2',
760
+ reason: '任务引用了「' + dangling[0] + '」这一内部编号/草稿,但任务原文没有定义它,也找不到上文',
761
+ question: '「' + dangling[0] + '」指的是什么?请给出文件路径、链接或把内容贴进来。',
762
+ }
763
+ }
764
+ const FORECAST = /(预测|预判|走势|涨跌|行情)/
765
+ const SUBJECT = /(?:\d{6}|[A-Z]{2,}\d+|[「『“"《][^」』”"》]{2,20}[」』”"》])/
766
+ // The missing subject may already be named in the conversation (「它走势如何」 after
767
+ // the user quoted a ticker). Only the task's own words make it a forecast request.
768
+ if (FORECAST.test(text) && !SUBJECT.test(both)) {
769
+ return {
770
+ needed: true,
771
+ rule: 'C3',
772
+ reason: '要求预测走势,但任务里没有可识别标的(股票代码/名称),也没有年份,缺关键输入',
773
+ question: '要预测哪只标的(股票代码或名称)?看哪个时间段?',
774
+ }
775
+ }
776
+ const UI_VERB = /(折叠|展开|按钮|显示|布局|样式|颜色|排序|置顶|收起)/
777
+ // 红圈/红框/圈出 name a surface the same way 截图 does: the user has pointed at
778
+ // something concrete. Without them 「把红圈处改为默认收起」 was C4-blocked even
779
+ // though the sentence is unambiguous (caught by department-fit.test.ts).
780
+ const UI_OBJECT = /(左侧栏|右侧栏|侧边栏|侧栏|面板|对话框|弹窗|菜单|工具栏|页面|截图|画圈|红圈|红框|圈出|插件|顶栏|底栏|任务进度)/
781
+ // Same rule as C3: 「把它改成默认收起」 is not missing a surface when the previous
782
+ // turn said 「截图红圈处的分步进度」. The verb must be in the task, the object may
783
+ // come from either side (plan-anchor.test.ts 'strict mode blocks…' covers this).
784
+ if (UI_VERB.test(text) && !UI_OBJECT.test(both)) {
785
+ return {
786
+ needed: true,
787
+ rule: 'C4',
788
+ reason: '要求改动界面显示,但没有说明改哪个界面/哪个板块,缺指代对象',
789
+ question: '要改的是哪个界面/哪个板块?(例如左侧栏、任务进度面板、某个按钮;有截图更好)',
790
+ }
791
+ }
792
+ return { needed: false, rule: '', reason: '', question: '' }
793
+ }
794
+
562
795
  /**
563
796
  * Split one clause into candidate noun phrases.
564
797
  *
@@ -1010,13 +1243,22 @@ export function auditTaskUnderstanding(plan: any, context: PlanAuditContext = {}
1010
1243
  const conversation = typeof context.conversationContext === 'string' ? context.conversationContext : ''
1011
1244
  const resolvedByContext = extracted.references.map((reference) => {
1012
1245
  if (reference.resolved) return reference
1013
- const found = resolvePronounAntecedent(reference.token, conversation)
1246
+ const fromConversation = resolvePronounAntecedent(reference.token, conversation)
1247
+ const found = fromConversation ?? resolvePronounAntecedentInline(reference.token, taskText)
1014
1248
  if (!found) return reference
1015
1249
  // Option letters are resolved only when the conversation lists that option
1016
1250
  // as a listed choice ("A 方案" / "B 选项"), not a bare letter in a word.
1251
+ // Task-text entities never satisfy this rule on their own: the option must
1252
+ // be defined where the user chose it, i.e. in the conversation.
1017
1253
  const listedOption = new RegExp('(?:^|[^A-Za-z])' + reference.token + '\\s*(?:方案|选项)')
1018
1254
  if (/^[A-D]$/.test(reference.token) && !listedOption.test(conversation)) return reference
1019
- return { ...reference, resolved: true, resolvedBy: 'context' as const, antecedent: found.antecedent }
1255
+ /*
1256
+ * [T3] Record where the referent came from. Reusing 'context' for an
1257
+ * antecedent found inside the task text would misreport an empty
1258
+ * conversation as the source, so the audit keeps the two apart.
1259
+ */
1260
+ const resolvedBy: TaskReference['resolvedBy'] = fromConversation ? 'context' : 'task-text'
1261
+ return { ...reference, resolved: true, resolvedBy, antecedent: found.antecedent }
1020
1262
  })
1021
1263
  const unresolved = resolvedByContext.filter((reference) => !reference.resolved)
1022
1264
 
@@ -1110,6 +1352,14 @@ export function validatePlanContext(plan: any, context: PlanAuditContext = {}):
1110
1352
  if (audit.stage3.verdict === 'needs-clarification') {
1111
1353
  errors.push(`CLARIFY: ${audit.stage3.reasons.find((reason) => reason.includes('自相矛盾')) ?? '用户要求存在矛盾,必须先向用户确认'}`)
1112
1354
  }
1355
+ /*
1356
+ * [P0-2c] Missing inputs must stop the plan before any department agent runs:
1357
+ * MS2 T05-04/09/13/20 were all planned and dispatched with the key input absent.
1358
+ */
1359
+ const clarify = auditClarifyNeed(context.taskText ?? audit.anchor?.text ?? '', context.conversationContext ?? '')
1360
+ if (clarify.needed) {
1361
+ errors.push('CLARIFY: ' + clarify.reason + '(规则 ' + clarify.rule + ')')
1362
+ }
1113
1363
  if (audit.stage3.verdict === 'needs-context') {
1114
1364
  errors.push(`CONTEXT: ${audit.stage3.reasons.find((reason) => reason.includes('指代')) ?? '任务含指代但在最近对话中找不到先行词,必须先向用户确认'}`)
1115
1365
  }