dsh-chief 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/runtime-hooks.js CHANGED
@@ -10,8 +10,13 @@ import { renderDigest } from './digest.js'
10
10
  import { appendMemory, captureTurn } from './memory.js'
11
11
  import {
12
12
  buildNotice,
13
+ buildMidTurnSpinNotice,
13
14
  clearCallTrail,
15
+ clearMidTurnSpin,
16
+ detectMidTurnSpin,
14
17
  isPlanWrite,
18
+ markMidTurnSpinActed,
19
+ noteCallResult,
15
20
  noteCallTrail,
16
21
  noteIntervention,
17
22
  notePlanWrite,
@@ -36,11 +41,15 @@ import {
36
41
  upsertTaskLedgerOnWs,
37
42
  normalizeSuggestion,
38
43
  ensureWorkspace,
44
+ recordWorkspaceAlertEvent,
39
45
  SUGGESTIONS_CAP,
46
+ CHAT_CAP,
47
+ nextId,
48
+ clamp,
40
49
  } from './chief-state.js'
41
50
  import { createAutoContinueEngine } from './auto-continue.js'
42
51
  import { bootstrapArchivesFromSharedBoard } from './archives.js'
43
- import { normalizePermissionMode, evaluatePreExecuteDefense, evaluateSafetyGuardHardRules, listGuardWalls } from './chief-executor.js'
52
+ import { normalizePermissionMode, buildCapabilityScope, evaluatePreExecuteDefense, evaluateSafetyGuardHardRules, listGuardWalls } from './chief-executor.js'
44
53
  import {
45
54
  newId,
46
55
  nowMs,
@@ -172,12 +181,23 @@ export function createRuntimeHooks(deps) {
172
181
  pushLog,
173
182
  })
174
183
 
184
+ const isExplicitStopped = (rootKey, sid) => {
185
+ try {
186
+ const st = loadChiefState()
187
+ const rk = resolveRootSessionId(rootKey || sid) || rootKey || sid
188
+ const cfg = resolveWorkspaceConfig(st, rk)
189
+ return Boolean(cfg.stopped || cfg.paceMode === 'stopped')
190
+ } catch {
191
+ return false
192
+ }
193
+ }
194
+
175
195
  const isRootStopped = (rootKey, sid) => {
176
196
  try {
177
197
  const st = loadChiefState()
178
198
  const rk = resolveRootSessionId(rootKey || sid) || rootKey || sid
179
199
  const cfg = resolveWorkspaceConfig(st, rk)
180
- return Boolean(cfg.stopped || cfg.paceMode === 'stopped' || cfg.runMode === 'off')
200
+ return Boolean(cfg.stopped || cfg.paceMode === 'stopped' || (cfg.runMode === 'off' && !(cfg.tacticalModes && cfg.tacticalModes.intervention)))
181
201
  } catch {
182
202
  return false
183
203
  }
@@ -208,8 +228,9 @@ export function createRuntimeHooks(deps) {
208
228
  const ws = state && state.workspaces && state.workspaces[key] ? state.workspaces[key] : null
209
229
  const effCfg = resolveWorkspaceConfig(state, key)
210
230
  const runMode = effCfg && effCfg.runMode ? effCfg.runMode : 'off'
211
- if ((effCfg && effCfg.stopped) || (runMode !== 'patrol' && runMode !== 'managed')) {
212
- return { allowed: false, skipped: 'run-mode-off', logMessage: '参谋处于「⏸ 关停」模式,仅 patrol/managed 模式允许 Auto continue 唤醒' }
231
+ const interventionOn = Boolean(effCfg && effCfg.tacticalModes && effCfg.tacticalModes.intervention)
232
+ if ((effCfg && effCfg.stopped) || (runMode !== 'patrol' && runMode !== 'managed' && !interventionOn)) {
233
+ return { allowed: false, skipped: 'run-mode-off', logMessage: '参谋处于「⏸ 关停」模式,仅 patrol/managed 或强介入激活时允许 Auto continue 唤醒' }
213
234
  }
214
235
 
215
236
  // Check forbidden bounds and active guard walls BEFORE continuing
@@ -337,6 +358,15 @@ export function createRuntimeHooks(deps) {
337
358
  pushLog(board, `🔄 断线续跑:${msg}`, 'chief', sid)
338
359
  saveBoard(board, file)
339
360
  })
361
+ if (String(msg || '').includes('断线续跑已触发')) {
362
+ recordWorkspaceAlertEvent(rootId, {
363
+ kind: 'auto_continue_rescue',
364
+ level: 'info',
365
+ title: '🔄 断流救活已触发续跑',
366
+ body: String(msg).slice(0, 180),
367
+ dedupeKey: `rescue:${rootId}:${Math.floor(Date.now() / 5_000)}`,
368
+ })
369
+ }
340
370
  } catch {}
341
371
  },
342
372
  })
@@ -489,6 +519,128 @@ export function createRuntimeHooks(deps) {
489
519
  } catch {}
490
520
  }), 'dsh-chief: deliver pending transfer')
491
521
 
522
+ function handleMidTurnSpinCheck(id, rootId) {
523
+ try {
524
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
525
+ const liveAgent = agents && typeof agents.get === 'function' ? agents.get(id) : null
526
+ if (!liveAgent || liveAgent.status !== 'running') return
527
+
528
+ const st = loadChiefState()
529
+ const effCfg = resolveWorkspaceConfig(st, rootId)
530
+ if (effCfg.stopped || effCfg.paceMode === 'stopped') return
531
+
532
+ const strongIntervention = Boolean(effCfg.tacticalModes && effCfg.tacticalModes.intervention)
533
+ const shared = loadBoard(boardFile())
534
+ const board = boardForSession(boardFileFor(id))
535
+ const settings = { ...(board.settings || {}), ...(shared.settings || {}) }
536
+ const guardIdleEnabled = settings.guardIdle !== false
537
+ if (!strongIntervention && !guardIdleEnabled) return
538
+
539
+ const spin = detectMidTurnSpin(id, { strongIntervention })
540
+ if (!spin) return
541
+
542
+ const canSteer = typeof liveAgent.steer === 'function'
543
+ const logLine = guardLogText({ kind: 'mid-turn-spin', spin }, 0, 0)
544
+ const ident = resolveAgentIdentity(runtime, id, liveAgent)
545
+ const targetHandle = (ident && ident.isChild && ident.self) ? ident.self : 'lead'
546
+
547
+ if (spin.kind === 'exact-loop' && guardIdleEnabled) {
548
+ if (!canSteer) return
549
+ liveAgent.steer(buildMidTurnSpinNotice(spin, board))
550
+ markMidTurnSpinActed(id)
551
+ const bFile = boardFileFor(id)
552
+ withBoardLock(bFile, () => {
553
+ const b = loadBoard(bFile)
554
+ pushLog(b, logLine, 'guard', id)
555
+ saveBoard(b, bFile)
556
+ })
557
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent: liveAgent, sessionId: id, abnormalTrigger: 'mid_turn_spin' })
558
+ return
559
+ }
560
+
561
+ if (!strongIntervention) return
562
+ const wsSnap = st.workspaces && st.workspaces[rootId] ? st.workspaces[rootId] : null
563
+ const permMode = normalizePermissionMode(effCfg.permissionMode, {
564
+ requireAck: true,
565
+ hasChiefRiskAck: hasValidChiefRiskAck(wsSnap),
566
+ })
567
+ const spinSummary = `${spin.name || 'tool'}${spin.preview ? ' (' + String(spin.preview).slice(0, 60) + ')' : ''}`
568
+
569
+ if (permMode === 'chief' && canSteer) {
570
+ liveAgent.steer(buildMidTurnSpinNotice(spin, board))
571
+ markMidTurnSpinActed(id)
572
+ mutateChiefState((s) => {
573
+ const ws = ensureWorkspace(s, rootId)
574
+ ws.chat.push({
575
+ id: nextId('chat'),
576
+ role: 'chief',
577
+ kind: 'receipt',
578
+ text: `- 【⚡ 强介入 · 运行中空转急刹】已当场插话制止 \`@${targetHandle}\` 原地空转/连续报错(${spin.kind} ×${spin.count}:${clamp(spinSummary, 140)})。`,
579
+ actions: [`⚡ 急刹 ×${spin.count}`],
580
+ at: Date.now(),
581
+ })
582
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
583
+ })
584
+ appendChiefAuditLog(rootId, {
585
+ mode: permMode,
586
+ stage: 'executor',
587
+ rule: 'mid_turn_spin_brake',
588
+ decision: 'executed',
589
+ operation: '强介入运行中空转急刹',
590
+ target: id,
591
+ reason: `${spin.kind} ×${spin.count}: ${clamp(spinSummary, 120)}`,
592
+ outcome: 'ok',
593
+ by: 'chief',
594
+ })
595
+ } else if (permMode === 'strategist') {
596
+ markMidTurnSpinActed(id)
597
+ const noticeObj = buildMidTurnSpinNotice(spin, board)
598
+ const noticeTxt = (noticeObj.content && noticeObj.content[0] && noticeObj.content[0].text) || ''
599
+ queueChiefApproval(rootId, {
600
+ category: 'main_workflow',
601
+ operationLabel: '强介入 · 运行中空转急刹插话',
602
+ targetLabel: targetHandle === 'lead' ? '主对话 (@lead)' : `@${targetHandle}`,
603
+ reason: `检测到运行中连续空转/报错(${spin.kind} ×${spin.count}),L2 参谋模式需您授权后插话急刹`,
604
+ impact: '允许后立即向运行中的目标插入纠偏通知',
605
+ preview: clamp(spinSummary, 200),
606
+ dedupeKey: `midspin:${rootId}:${spin.kind}:${spin.name}`,
607
+ kind: 'relay',
608
+ capabilityScope: buildCapabilityScope({ kind: 'relay', tool: 'relay', target: targetHandle }),
609
+ payload: {
610
+ fromSession: rootId,
611
+ fromLabel: 'DSH 参谋 (运行中空转急刹)',
612
+ target: targetHandle,
613
+ subject: '运行中空转急刹',
614
+ text: noticeTxt,
615
+ mode: 'steer',
616
+ },
617
+ by: 'chief',
618
+ })
619
+ } else {
620
+ markMidTurnSpinActed(id)
621
+ mutateChiefState((s) => {
622
+ const ws = ensureWorkspace(s, rootId)
623
+ ws.chat.push({
624
+ id: nextId('chat'),
625
+ role: 'chief',
626
+ kind: 'receipt',
627
+ text: `- 【👁 运行中空转告警 (${permMode === 'assistant' ? 'L1' : 'L0'})】检测到 \`@${targetHandle}\` 正在连续空转/报错(${spin.kind} ×${spin.count}:${clamp(spinSummary, 140)}),当前权限不自动插话。`,
628
+ actions: ['⚠️ 运行空转告警'],
629
+ at: Date.now(),
630
+ })
631
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
632
+ })
633
+ }
634
+ const bFile = boardFileFor(id)
635
+ withBoardLock(bFile, () => {
636
+ const b = loadBoard(bFile)
637
+ pushLog(b, logLine, 'guard', id)
638
+ saveBoard(b, bFile)
639
+ })
640
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent: liveAgent, sessionId: id, abnormalTrigger: 'mid_turn_spin' })
641
+ } catch {}
642
+ }
643
+
492
644
  // 2c) Incremental record of what each turn actually did + Auto-Continue detection
493
645
  // on interruptions / transient failures / empty outputs (unless Chief is stopped).
494
646
  ctx.effect(() => ctx.on('session/event', (session, event) => {
@@ -499,11 +651,17 @@ export function createRuntimeHooks(deps) {
499
651
  if (event.type === 'turn/start' || event.type === 'message/user' || event.type === 'tool/call' || event.type === 'turn/end') {
500
652
  touchWorkspaceActivity(rootIdForAct)
501
653
  }
502
- if (event.type === 'tool/call' && event.data) {
654
+ if (event.type === 'turn/start') {
655
+ clearMidTurnSpin(id)
656
+ } else if (event.type === 'tool/call' && event.data) {
503
657
  const turn = event.data.turn
504
658
  noteToolCall(id, turn)
505
659
  if (isPlanWrite(event.data.name, event.data.arguments)) notePlanWrite(id, turn)
506
660
  noteCallTrail(id, event.data.name, event.data.arguments)
661
+ handleMidTurnSpinCheck(id, rootIdForAct)
662
+ } else if (event.type === 'tool/result' && event.data) {
663
+ noteCallResult(id, event.data)
664
+ handleMidTurnSpinCheck(id, rootIdForAct)
507
665
  }
508
666
  autoContinue.onSessionEvent(session, event)
509
667
 
@@ -519,8 +677,11 @@ export function createRuntimeHooks(deps) {
519
677
  const steerKey = `${id}:${turnNum}`
520
678
  const steeredAt = deps.hostState.autoSteeredTurns.get(steerKey) || 0
521
679
  if (steeredAt) deps.hostState.autoSteeredTurns.delete(steerKey)
522
- if (!isStoppedByUserOrPolicy && !(steeredAt && Date.now() - steeredAt < 30_000)) {
523
- const rootId = resolveRootSessionId(id) || id
680
+ const stNow = loadChiefState()
681
+ const rootId = resolveRootSessionId(id) || id
682
+ const cfgNow = resolveWorkspaceConfig(stNow, rootId)
683
+ const strongIntervention = Boolean(cfgNow.tacticalModes && cfgNow.tacticalModes.intervention)
684
+ if (!isStoppedByUserOrPolicy && (strongIntervention || !(steeredAt && Date.now() - steeredAt < 30_000))) {
524
685
  if (!isRootStopped(rootId, id) || abnormalTrig) {
525
686
  const agents = runtime && runtime.get ? runtime.get('agents') : null
526
687
  const liveAgent = agents && typeof agents.get === 'function' ? agents.get(id) : null
@@ -607,7 +768,12 @@ export function createRuntimeHooks(deps) {
607
768
  }
608
769
  task.updatedAt = nowMs()
609
770
  settledCount += 1
610
- pushLog(board, '✅ 子代理 ' + identity.self + ' 完成任务 #' + task.id + '「' + task.title.slice(0, 36) + '」', identity.self, id)
771
+ const returnStepId = task.targetPlanStepId || task.planStepId
772
+ const returnStepIdx = returnStepId && Array.isArray(board.plan)
773
+ ? board.plan.findIndex(s => s && s.id === returnStepId)
774
+ : -1
775
+ const returnTag = returnStepIdx >= 0 ? '(已回指步骤 ' + (returnStepIdx + 1) + ')' : ''
776
+ pushLog(board, '✅ 子代理 ' + identity.self + ' 完成任务 #' + task.id + '「' + task.title.slice(0, 36) + '」' + returnTag, identity.self, id)
611
777
  }
612
778
  }
613
779
  if (settledCount > 0) {
@@ -622,7 +788,7 @@ export function createRuntimeHooks(deps) {
622
788
  }
623
789
 
624
790
  const rootId = resolveRootSessionId(id, agent) || id
625
- if (isRootStopped(rootId, id)) {
791
+ if (isExplicitStopped(rootId, id)) {
626
792
  saveBoard(board, file)
627
793
  return
628
794
  }
@@ -631,7 +797,18 @@ export function createRuntimeHooks(deps) {
631
797
  // same rule so one switch turns the guard off everywhere.
632
798
  const shared = loadBoard(boardFile())
633
799
  const settings = { ...(board.settings || {}), ...(shared.settings || {}) }
634
- const verdict = shouldGuard({ board, session: agent && agent.session, sessionId: id, turn, settings })
800
+ const effCfg = resolveWorkspaceConfig(loadChiefState(), rootId)
801
+ const strongIntervention = Boolean(effCfg.tacticalModes && effCfg.tacticalModes.intervention)
802
+ const maxInterventionTurns = Number(effCfg.tacticalModes && effCfg.tacticalModes.maxInterventionTurns) || 0
803
+ const verdict = shouldGuard({
804
+ board,
805
+ session: agent && agent.session,
806
+ sessionId: id,
807
+ turn,
808
+ settings,
809
+ strongIntervention,
810
+ maxInterventionTurns,
811
+ })
635
812
  if (!verdict) {
636
813
  saveBoard(board, file)
637
814
  scheduleChiefTurnReview(makeChiefDeps(runtime), { agent, sessionId: id, turn })
@@ -658,7 +835,8 @@ export function createRuntimeHooks(deps) {
658
835
  // Clear the trail only once the steer landed: a loop that survived a
659
836
  // failed steer deserves the next nudge, not a silent reset.
660
837
  if (verdict.kind === 'loop') clearCallTrail(id)
661
- pushLog(board, guardLogText(verdict, turn, remainingInterventions(id, settings)), 'guard', id)
838
+ const remAfter = remainingInterventions(id, settings, { strongIntervention, maxInterventionTurns })
839
+ pushLog(board, guardLogText(verdict, turn, remAfter), 'guard', id)
662
840
 
663
841
  // Auto-handoff: when the guard has spent its last intervention and the
664
842
  // session still has open work, the turn is not idle — it is stuck in a
@@ -666,7 +844,7 @@ export function createRuntimeHooks(deps) {
666
844
  // handover packet right now so the next Session (or a manual reopen)
667
845
  // inherits it instead of a blank board. The steer already fired above
668
846
  // tells the model to wrap up; this packet is what the next one reads.
669
- if (remainingInterventions(id, settings) === 0) {
847
+ if (remAfter === 0) {
670
848
  try {
671
849
  const packet = resolveEffectiveHandoff(runtime, id, board).text
672
850
  const pendingFile_ = pendingFile()
@@ -742,6 +920,13 @@ export function createRuntimeHooks(deps) {
742
920
  outcome: 'blocked',
743
921
  by: actorName,
744
922
  })
923
+ recordWorkspaceAlertEvent(rootId, {
924
+ kind: 'guard_wall_blocked',
925
+ level: 'danger',
926
+ title: '🧱 物理驻墙已拦截越界调用',
927
+ body: `@${actorName} 调用 ${exec.name}:${String(verdict.reason || '').slice(0, 140)}`,
928
+ dedupeKey: `wall:${rootId}:${exec.name}:${verdict.wallId || verdict.rule || ''}`,
929
+ })
745
930
  try {
746
931
  const bFile = rootId !== 'global' ? boardFileFor(rootId) : boardFile()
747
932
  withBoardLock(bFile, () => {
@@ -830,6 +1015,56 @@ export function createRuntimeHooks(deps) {
830
1015
  )
831
1016
  if (hasNeedReconcile) mutateChiefState(() => {})
832
1017
  } catch {}
1018
+
1019
+ // Idle watchdog for Strong Intervention: catch already-stalled lead sessions cleanly without extra turns
1020
+ const lastWatchdogByRoot = new Map()
1021
+ const watchdogTimer = setInterval(() => {
1022
+ try {
1023
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
1024
+ const allAgents = agents && typeof agents.list === 'function' ? (agents.list() || []) : []
1025
+ if (!allAgents.length) return
1026
+ const state = loadChiefState()
1027
+ const now = Date.now()
1028
+ for (const ag of allAgents) {
1029
+ const agId = String((ag && ag.id) || '').trim()
1030
+ if (!agId) continue
1031
+ const rootId = resolveRootSessionId(agId, ag) || agId
1032
+ if (rootId !== agId) continue
1033
+ const effCfg = resolveWorkspaceConfig(state, rootId)
1034
+ if (effCfg.stopped || effCfg.paceMode === 'stopped') continue
1035
+ if (!(effCfg.tacticalModes && effCfg.tacticalModes.intervention)) continue
1036
+ if (ag.status === 'running') continue
1037
+
1038
+ const hasRunningChild = allAgents.some(c => {
1039
+ const cId = String((c && c.id) || '').trim()
1040
+ if (!cId || cId === rootId) return false
1041
+ if ((resolveRootSessionId(cId, c) || cId) !== rootId) return false
1042
+ if (/^mnemon-(?:review|run)/i.test(String((c && c.name) || cId))) return false
1043
+ return c && c.status === 'running'
1044
+ })
1045
+ if (hasRunningChild) continue
1046
+
1047
+ const ws = state.workspaces && state.workspaces[rootId] ? state.workspaces[rootId] : null
1048
+ const rg = (ws && ws.runtimeGuard) || {}
1049
+ if (rg.circuitBroken || rg.hazardAlert) continue
1050
+ const hasPendingApr = Array.isArray(ws && ws.pendingApprovals) && ws.pendingApprovals.some(a => a && a.status === 'pending')
1051
+ if (hasPendingApr || (ws && ws.pendingElevation)) continue
1052
+ const hasPendingGoalSug = Array.isArray(ws && ws.suggestions) && ws.suggestions.some(s => s && s.status === 'pending' && s.kind === 'goal_approval')
1053
+ if (hasPendingGoalSug) continue
1054
+
1055
+ const refAt = Math.max(Number(rg.lastActivityAt) || 0, Number(lastWatchdogByRoot.get(rootId)) || 0)
1056
+ if (now - refAt < 22_000) continue
1057
+ lastWatchdogByRoot.set(rootId, now)
1058
+ scheduleChiefTurnReview(makeChiefDeps(runtime), {
1059
+ agent: ag,
1060
+ sessionId: rootId,
1061
+ abnormalTrigger: 'idle_watchdog',
1062
+ })
1063
+ }
1064
+ } catch {}
1065
+ }, 25_000)
1066
+ watchdogTimer.unref?.()
1067
+ ctx.effect(() => () => clearInterval(watchdogTimer), 'dsh-chief: strong intervention watchdog cleanup')
833
1068
  }
834
1069
 
835
1070
  return {
@@ -24,7 +24,8 @@ export const HARD_GUARD_RULE_IDS = Object.freeze([
24
24
  const DESTRUCTIVE_COMMAND_PATTERNS = [
25
25
  /\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/])|~|\*|\.\.)/i,
26
26
  /\bgit\s+(?:reset\s+--hard|clean\s+-[a-z]*f[a-z]*d|push\s+(?:--force|-f)\b)/i,
27
- /\b(?:format|diskpart|cipher\s+\/w|bcdedit)\b/i,
27
+ /\b(?:diskpart|cipher\s+\/w|bcdedit)\b/i,
28
+ /(?:^|[;&|]\s*|(?:cmd(?:\.exe)?\s+\/c|powershell(?:\.exe)?\s+-[a-z]*c\w*|pwsh(?:\.exe)?\s+-[a-z]*c\w*)\s+["']?)\bformat(?:\.com)?\s+(?:[a-z]:|\/(?:fs|q|v|x|p|y)\b)/i,
28
29
  /\bdel\s+\/[fqs][^\n]*[a-z]:\\/i,
29
30
  /\bRemove-Item\b[^\n]*-Recurse[^\n]*-Force[^\n]*(?:[a-z]:\\|\*)/i,
30
31
  /\b(?:shutdown(?:\.exe)?|restart-computer|stop-computer|mkfs|dd\s+if=.*of=\/dev\/)\b/i,
@@ -26,6 +26,7 @@ import {
26
26
  CAP_TASK_INTENT,
27
27
  asBool,
28
28
  normalizeTask,
29
+ resolveActivePlanStepId,
29
30
  pushLog,
30
31
  safe,
31
32
  } from './board-schema.js'
@@ -514,6 +515,17 @@ export function createSubagentRuntime(deps) {
514
515
  '- **任务标题**: ' + task.title,
515
516
  ]
516
517
  if (board.objective) lines.push('- **全局目标**: ' + board.objective.slice(0, 400))
518
+ const planSteps = Array.isArray(board && board.plan) ? board.plan : []
519
+ const stepIdx = task.planStepId ? planSteps.findIndex(s => s && s.id === task.planStepId) : -1
520
+ if (stepIdx >= 0) {
521
+ const targetIdx = task.targetPlanStepId && task.targetPlanStepId !== task.planStepId
522
+ ? planSteps.findIndex(s => s && s.id === task.targetPlanStepId)
523
+ : -1
524
+ const returnHint = targetIdx >= 0
525
+ ? ';完成后成果回指第 ' + (targetIdx + 1) + ' 步「' + planSteps[targetIdx].text + '」'
526
+ : ''
527
+ lines.push('- **所属推进步骤**: 第 ' + (stepIdx + 1) + ' 步「' + planSteps[stepIdx].text + '」' + returnHint)
528
+ }
517
529
  if (task.intent) lines.push('- **任务意图 (Intent)**: ' + task.intent)
518
530
  if (task.evidence) lines.push('- **验收标准 (Expected Evidence)**: ' + task.evidence)
519
531
  if (task.note) lines.push('- **补充说明 (Note)**: ' + task.note)
@@ -1287,7 +1299,16 @@ export function createSubagentRuntime(deps) {
1287
1299
  }
1288
1300
 
1289
1301
  const requestedTarget = str(args.agent || args.subagent || args.target || targetTask.subagent || targetTask.owner, '').trim()
1290
- const brief = buildTaskDispatchBrief(boardSnapshot, targetTask, args.prompt || args.message || args.text)
1302
+ const explicitPlanStepId = typeof args.planStepId === 'string' ? args.planStepId.trim().slice(0, 120) : ''
1303
+ const explicitTargetStepId = typeof args.targetPlanStepId === 'string' ? args.targetPlanStepId.trim().slice(0, 120) : ''
1304
+ const effectivePlanStepId = explicitPlanStepId || targetTask.planStepId || resolveActivePlanStepId(boardSnapshot)
1305
+ const effectiveTargetStepId = explicitTargetStepId || targetTask.targetPlanStepId || ''
1306
+ const briefTask = {
1307
+ ...targetTask,
1308
+ planStepId: effectivePlanStepId,
1309
+ targetPlanStepId: effectiveTargetStepId,
1310
+ }
1311
+ const brief = buildTaskDispatchBrief(boardSnapshot, briefTask, args.prompt || args.message || args.text)
1291
1312
  let dispatchedName = requestedTarget
1292
1313
  let childSessionId = ''
1293
1314
  let dispatchMode = 'assigned'
@@ -1404,6 +1425,12 @@ export function createSubagentRuntime(deps) {
1404
1425
  task.subagent = dispatchedName
1405
1426
  if (childSessionId) task.session = childSessionId
1406
1427
  if (args.preset) task.preset = str(args.preset, '').slice(0, 80)
1428
+ if (explicitPlanStepId) task.planStepId = explicitPlanStepId
1429
+ else if (!task.planStepId) {
1430
+ const autoStep = resolveActivePlanStepId(board)
1431
+ if (autoStep) task.planStepId = autoStep
1432
+ }
1433
+ if (explicitTargetStepId) task.targetPlanStepId = explicitTargetStepId
1407
1434
  task.dispatchedAt = nowMs()
1408
1435
  task.updatedAt = nowMs()
1409
1436
  board.cursor = {