dsh-chief 1.3.0 → 1.4.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/chief-commands.js CHANGED
@@ -26,6 +26,8 @@ import {
26
26
  getToolOpClass,
27
27
  evaluateSafetyGuardHardRules,
28
28
  evaluateChiefPermissionGate,
29
+ buildCapabilityScope,
30
+ validateGuardWallInput,
29
31
  CHIEF_TOOLS_PROMPT_GUIDE,
30
32
  runChiefAgenticLoop,
31
33
  stripToolCallMarkup,
@@ -51,7 +53,8 @@ import {
51
53
  appendChiefAuditLog,
52
54
  queueChiefApproval,
53
55
  requestChiefElevation,
54
- upsertResumeTaskOnWs,
56
+ upsertTaskLedgerOnWs,
57
+ enqueueChiefInquiryOnWs,
55
58
  loadChiefState,
56
59
  mutateChiefState,
57
60
  getLinkedCluster,
@@ -63,9 +66,18 @@ import {
63
66
  isInternalCheckpointNoise,
64
67
  updateWorkspaceFlippedIds,
65
68
  extractJsonObject,
69
+ resolveSessionWorkspaceCwd,
70
+ CHIEF_INQUIRY_SOURCE,
71
+ beginChiefActiveWork,
72
+ endChiefActiveWork,
66
73
  } from './chief-state.js'
67
74
  import { callChiefLlm } from './chief-models.js'
68
- import { collectClusterPeerProgress, listPeerDirectory, deliverCrossMessage } from './chief-network.js'
75
+ import {
76
+ collectClusterPeerProgress,
77
+ listPeerDirectory,
78
+ deliverCrossMessage,
79
+ registerChiefDirectRequestHook,
80
+ } from './chief-network.js'
69
81
  import {
70
82
  sanitizeConciseBriefText,
71
83
  buildConciseSixLineReport,
@@ -94,7 +106,20 @@ const ASK_CHIEF_SYSTEM = [
94
106
  ' "requestedActionSummary": "拟执行的核心动作简述"',
95
107
  ' },',
96
108
  ' "relays": [',
97
- ' { "target": "成员 key 或名字(如 lead / 子代理名 / session-xxx / all)", "mode": "steer|followup|silent", "subject": "简短事由", "text": "替用户转化好的清晰可执行指令" }',
109
+ ' { "target": "成员 key 或名字(如 lead / 子代理名 / session-xxx / all)", "mode": "steer|followup|silent", "subject": "简短事由", "text": "替用户转化好的清晰可执行执行请求" }',
110
+ ' ],',
111
+ ' "inquiries": [',
112
+ ' { "target": "lead", "question": "缺情报时向主对话提出的优先问询(禁止凭空瞎猜)", "context": "简短问询背景" }',
113
+ ' ],',
114
+ ' "wallProposals": [',
115
+ ' {',
116
+ ' "title": "物理驻墙名称",',
117
+ ' "scope": "global|workspace",',
118
+ ' "ruleType": "forbid_path|restrict_write|forbid_cmd|require_approval_cmd|deny_tool",',
119
+ ' "patterns": ["被锁路径前缀/目录名 或 禁跑命令正则"],',
120
+ ' "writeOnly": false,',
121
+ ' "reason": "手搓这堵物理墙的原因"',
122
+ ' }',
98
123
  ' ],',
99
124
  ' "memoryChanges": [',
100
125
  ' { "op": "add", "category": "discipline|architecture|progress|preference|team", "text": "一句独立完整的持久事实或规矩(不超过200字,绝不存密钥密码)" },',
@@ -136,7 +161,9 @@ const ASK_CHIEF_SYSTEM = [
136
161
  '}',
137
162
  '',
138
163
  '宰相参谋与行事准则:',
139
- '- 【实权执行优先(禁止退化为纯传话筒)】:当用户要求你直接查文件、检查代码、修改补丁、跑测试/命令、直接派发/纠偏/中断子代理、记入档案或立即压缩时,务必先用 `toolCalls` 亲自执行并拿回真实结果后再汇报!只有用户明确要求转告 `@lead` / 其他窗口,或明确属主对话长程编码任务时,才使用 `relays` 递话。',
164
+ '- 【懒介入与主会话优先铁律(严禁抢活越俎代庖)】:即使你已拥有高权限,也必须遏制亲自写代码或跑项目命令的冲动!凡是修改项目源码、跑构建测试、长程勘探排障,只要主对话在线可用且用户没有明确指定“参谋长你亲自来做/别找主对话”,一律优先放在 `"relays"` 中以正式执行请求形式交由 `@lead` 动手执行!只有用户点名直办、纯参谋内务(看板/档案/记忆/边界/物理墙草案)或主对话失联卡死时才亲自调工具。',
165
+ '- 【优先问询渠道(缺信息就问主对话,严禁瞎猜)】:无论是在自主调配还是回答用户问题时,只要缺乏代码细节或实时状态确认,请输出 `"inquiries"` 向 `@lead` 发出优先问询,主对话会在不打断手头动作的情况下原路快答。',
166
+ '- 【手搓动态物理墙】:当用户让你“筑一堵物理墙/锁死某个目录或仓库/禁跑某个高危命令”时,直接将大白话诉求编译成 `"wallProposals"`(跨会话常驻设 `"scope": "global"`),呈交用户一键确认落锁(只准帮用户筑墙,绝无权私拆已有物理墙)。',
140
167
  '- 【许愿框全权自治】:无论整理/分类/提炼档案入全局、上下桌面、设定/覆盖/清空边界、重设/重编任务(`task.reset`/`graph.plan`),还是连接/断开独立窗口协同网络(`networkOps`),只要用户开口许愿且符合当前权限,直接输出对应 JSON ops 执行到位(严禁越级让本局档案直接跳级沉淀,必须遵循 `本局 -> 全局 -> 沉淀` 梯度),绝不推辞让用户自己去点按钮!',
141
168
  '- 【严守当前权限与禁止红线】:绝不越过当前权限等级上限,也绝不执行触发 `禁止红线 (forbidden)` 的写操作或高危命令。',
142
169
  '- 【问进展 / 问步骤 / 问卡点 / 求建议】:当用户询问“现在在做什么 / 处于什么步骤 / 目前进度如何 / 卡在哪里”等态势问题时,你面前的上下文已经完整包含「实时对话流快照」+「小任务板 (Plan)」+「任务图」+「断点游标」!直接用简明人话分点作答并放进 JSON 的 `reply` 字段,**严禁退化成纯工具 XML/DSML 标签输出,更严禁盲目运行 `run_command` / `list_dir` 扫盘**!只有用户明确要求去核查具体源码文件/跑命令实测时,才在 JSON `toolCalls` 里调工具。',
@@ -159,8 +186,41 @@ const CONCISE_BRIEF_ASK_EXTRA = [
159
186
  ' - 【🧰 需要什么】一句话说明还需什么条件或验证',
160
187
  ' - 【🙋 用户需要提供什么】一句话说明需用户提供/拍板的内容(或“暂无需您额外提供”)',
161
188
  ' - 【💡 参谋长建议】一句话给出明确建议',
189
+ '- ⚠️ JSON 顶层结构铁律:上述六句话战报只能作为顶层合法 JSON 对象内 `"reply"` 字段的字符串值!绝不允许直接裸输出 Markdown!若用户要求手搓物理驻墙或提炼/总结工作边界(或你在回复中提出了要补充/禁用的红线或边界),必须同步将完整条目填入 `"wallProposals"` 与 `"boundProposals"` 数组(JSON 字符串内的正则反斜杠须写双反斜杠 `\\\\`)。',
162
190
  ].join('\n')
163
191
 
192
+ function extractFallbackBoundProposalsFromText(rawText = '', userInput = '') {
193
+ const txt = String(rawText || '')
194
+ if (!txt.trim()) return []
195
+ const wantBounds = /boundProposals|提炼.*边界|总结.*边界|边界注入/i.test(String(userInput || ''))
196
+ || /(?:提案\s*\d+|boundProposals)/i.test(txt)
197
+ if (!wantBounds) return []
198
+ const out = []
199
+ const seen = new Set()
200
+ for (const line of txt.split(/\r?\n/)) {
201
+ const clean = line.trim()
202
+ const m = clean.match(/^[-*•]?\s*【(?:提案\s*\d*[·::\s]*)?(红线|禁止红线|禁止|必做事项|必做|允许|注意事项|注意)[^】]*】\s*(.+)$/)
203
+ if (!m) continue
204
+ const kindWord = m[1]
205
+ const field = /必做|允许/.test(kindWord) ? 'allowed' : (/注意/.test(kindWord) ? 'notes' : 'forbidden')
206
+ const rawItem = m[2]
207
+ .replace(/[((]\s*(?:📌\s*)?(?:全局|本任务)[^))]*[))]\s*$/g, '')
208
+ .replace(/\s+/g, ' ')
209
+ .trim()
210
+ const item = clamp(rawItem, 220)
211
+ if (!item || seen.has(item)) continue
212
+ seen.add(item)
213
+ out.push({
214
+ field,
215
+ item,
216
+ pinGlobal: /📌|全局/.test(clean),
217
+ reason: '从参谋长提炼建议自动提取入审,请用户拍板确认。',
218
+ })
219
+ if (out.length >= 4) break
220
+ }
221
+ return out
222
+ }
223
+
164
224
  const CONSOLIDATE_BOUNDS_SYSTEM = [
165
225
  '你是「DSH 参谋长」(宰相级边界治理中枢)。用户的边界列表中积累了多条零散、重复或同一主题的规则。',
166
226
  '请将给定的多条零散边界**浓缩合并成唯一 1 条**高信息密度、表述清晰、可直接执行的精炼总则(不超过 180 字)。',
@@ -345,6 +405,7 @@ export function applyBoardOps(deps, rootId, boardOps, opts = {}) {
345
405
  if (!Array.isArray(boardOps) || !boardOps.length || !deps || typeof deps.runAction !== 'function') return executed
346
406
  const forceSessionOnly = Boolean(opts && opts.forceSessionOnly)
347
407
  const allowLockedObjectiveWrite = Boolean(opts && opts.allowLockedObjectiveWrite)
408
+ const callerOrigin = String((opts && opts.callerOrigin) || 'chief_llm')
348
409
  const effCfg = resolveWorkspaceConfig(loadChiefState(), rootId)
349
410
  const objectiveLocked = Boolean(effCfg && effCfg.tacticalModes && effCfg.tacticalModes.intervention) && !allowLockedObjectiveWrite
350
411
 
@@ -441,8 +502,9 @@ export function applyBoardOps(deps, rootId, boardOps, opts = {}) {
441
502
  const col = ['forbidden', 'allowed', 'notes'].includes(normField) ? normField : ''
442
503
  if (col && Array.isArray(opItem.items)) {
443
504
  const items = opItem.items.map(x => clamp(x, 220)).filter(Boolean)
444
- const res = deps.runAction({ action: 'bounds.set', field: col, items, session: rootId, by: 'chief' })
505
+ const res = deps.runAction({ action: 'bounds.set', field: col, items, session: rootId, by: 'chief', _callerOrigin: callerOrigin })
445
506
  if (res && res.ok) executed.push(`覆写边界(${col})共 ${items.length} 条`)
507
+ else if (res && res.blockedBySafetyGuard) executed.push(`🛡️ 已拦截覆写红线(${col})`)
446
508
  } else if (Array.isArray(opItem.allowed) || Array.isArray(opItem.must) || Array.isArray(opItem.forbidden) || Array.isArray(opItem.notes)) {
447
509
  const allowList = Array.isArray(opItem.allowed) ? opItem.allowed : opItem.must
448
510
  const res = deps.runAction({
@@ -452,8 +514,10 @@ export function applyBoardOps(deps, rootId, boardOps, opts = {}) {
452
514
  ...(Array.isArray(opItem.notes) ? { notes: opItem.notes.map(x => clamp(x, 220)).filter(Boolean) } : {}),
453
515
  session: rootId,
454
516
  by: 'chief',
517
+ _callerOrigin: callerOrigin,
455
518
  })
456
519
  if (res && res.ok) executed.push('重置边界列表')
520
+ else if (res && res.blockedBySafetyGuard) executed.push('🛡️ 已拦截批量覆写边界')
457
521
  }
458
522
  } else if ((op === 'bounds.forbid' || op === 'bounds.allow' || op === 'bounds.must' || op === 'bounds.note') && opItem.item) {
459
523
  const field = op === 'bounds.forbid' ? 'forbidden' : (op === 'bounds.note' ? 'notes' : 'allowed')
@@ -468,9 +532,12 @@ export function applyBoardOps(deps, rootId, boardOps, opts = {}) {
468
532
  pinned,
469
533
  session: rootId,
470
534
  by: 'chief',
535
+ _callerOrigin: callerOrigin,
471
536
  })
472
537
  if (res && res.ok) {
473
538
  executed.push(`${pinned ? '📌全局' : '本任务'}${label}:${clamp(val, 30)}`)
539
+ } else if (res && res.blockedBySafetyGuard) {
540
+ executed.push(`🛡️ 已拦截写入边界(${field})`)
474
541
  }
475
542
  }
476
543
  } else if (op === 'bounds.remove' && opItem.item) {
@@ -485,9 +552,12 @@ export function applyBoardOps(deps, rootId, boardOps, opts = {}) {
485
552
  pinned,
486
553
  session: rootId,
487
554
  by: 'chief',
555
+ _callerOrigin: callerOrigin,
488
556
  })
489
557
  if (res && res.ok) {
490
558
  executed.push(`移除边界:${clamp(val, 30)}`)
559
+ } else if (res && res.blockedBySafetyGuard) {
560
+ executed.push(`🛡️ 已拦截移除红线(${field})`)
491
561
  }
492
562
  }
493
563
  }
@@ -994,79 +1064,89 @@ export async function consolidateBoundsWithChief(deps, {
994
1064
  }
995
1065
  }
996
1066
 
997
- const createdProposals = []
998
- for (const { col, sourceItems } of targetCols) {
999
- const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
1000
- const hadPinned = sourceItems.some(x => (pinnedBounds[col] || []).includes(x))
1001
- const prompt = [
1002
- `目标边界分栏:【${colLabel}】(${col})`,
1003
- instruction ? `用户额外要求:${clamp(instruction, 200)}` : '',
1004
- `待浓缩合并的 ${sourceItems.length} 条零散边界:`,
1005
- ...sourceItems.map((it, idx) => `${idx + 1}. ${(pinnedBounds[col] || []).includes(it) ? '[📌全局定住] ' : ''}${it}`),
1006
- '',
1007
- '请将以上零散规则浓缩合并为唯一 1 条高密度总则(保留具体命令、路径与硬红线),只输出 JSON:',
1008
- ].filter(Boolean).join('\n')
1009
-
1010
- const llmRes = await callChiefLlm(deps, {
1011
- sessionId: rootId,
1012
- system: CONSOLIDATE_BOUNDS_SYSTEM,
1013
- prompt,
1014
- maxTokens: SUMMARY_MAX_TOKENS,
1015
- })
1067
+ const consWorkId = beginChiefActiveWork(rootId, {
1068
+ tone: 'bounds',
1069
+ tab: 'boundaries',
1070
+ boundSubTab: 'rules',
1071
+ label: '参谋长正在浓缩边界中...',
1072
+ })
1073
+ try {
1074
+ const createdProposals = []
1075
+ for (const { col, sourceItems } of targetCols) {
1076
+ const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
1077
+ const hadPinned = sourceItems.some(x => (pinnedBounds[col] || []).includes(x))
1078
+ const prompt = [
1079
+ `目标边界分栏:【${colLabel}】(${col})`,
1080
+ instruction ? `用户额外要求:${clamp(instruction, 200)}` : '',
1081
+ `待浓缩合并的 ${sourceItems.length} 条零散边界:`,
1082
+ ...sourceItems.map((it, idx) => `${idx + 1}. ${(pinnedBounds[col] || []).includes(it) ? '[📌全局定住] ' : ''}${it}`),
1083
+ '',
1084
+ '请将以上零散规则浓缩合并为唯一 1 条高密度总则(保留具体命令、路径与硬红线),只输出 JSON:',
1085
+ ].filter(Boolean).join('\n')
1086
+
1087
+ const llmRes = await callChiefLlm(deps, {
1088
+ sessionId: rootId,
1089
+ system: CONSOLIDATE_BOUNDS_SYSTEM,
1090
+ prompt,
1091
+ maxTokens: SUMMARY_MAX_TOKENS,
1092
+ })
1016
1093
 
1017
- const parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
1018
- const mergedText = clamp(
1019
- (parsed && (parsed.item || parsed.draftText || parsed.text)) || deterministicConsolidateClauses(sourceItems),
1020
- 220,
1021
- )
1022
- const mergedReason = clamp(
1023
- (parsed && parsed.reason) || `已将【${colLabel}】下 ${sourceItems.length} 条零散边界浓缩合成为 1 条总则,批准后自动替换原零散条目。`,
1024
- 180,
1025
- )
1094
+ const parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
1095
+ const mergedText = clamp(
1096
+ (parsed && (parsed.item || parsed.draftText || parsed.text)) || deterministicConsolidateClauses(sourceItems),
1097
+ 220,
1098
+ )
1099
+ const mergedReason = clamp(
1100
+ (parsed && parsed.reason) || `已将【${colLabel}】下 ${sourceItems.length} 条零散边界浓缩合成为 1 条总则,批准后自动替换原零散条目。`,
1101
+ 180,
1102
+ )
1026
1103
 
1027
- if (!mergedText || secretLike(mergedText)) continue
1104
+ if (!mergedText || secretLike(mergedText)) continue
1028
1105
 
1029
- mutateChiefState((s) => {
1030
- const ws = ensureWorkspace(s, rootId)
1031
- // Dismiss older pending consolidation proposals for the exact same column to avoid clutter
1032
- for (const existing of ws.suggestions) {
1033
- if (existing.status === 'pending' && existing.kind === 'bound' && existing.boundField === col && Array.isArray(existing.replaces) && existing.replaces.length > 0) {
1034
- existing.status = 'dismissed'
1106
+ mutateChiefState((s) => {
1107
+ const ws = ensureWorkspace(s, rootId)
1108
+ // Dismiss older pending consolidation proposals for the exact same column to avoid clutter
1109
+ for (const existing of ws.suggestions) {
1110
+ if (existing.status === 'pending' && existing.kind === 'bound' && existing.boundField === col && Array.isArray(existing.replaces) && existing.replaces.length > 0) {
1111
+ existing.status = 'dismissed'
1112
+ }
1113
+ }
1114
+ const sug = normalizeSuggestion({
1115
+ kind: 'bound',
1116
+ boundField: col,
1117
+ fromAgent: '✦ 参谋长浓缩',
1118
+ title: `${colLabel} ${sourceItems.length} 合 1:${clamp(mergedText, 26)}`,
1119
+ reason: mergedReason,
1120
+ target: 'bounds',
1121
+ targetLabel: colLabel,
1122
+ mode: 'silent',
1123
+ draftText: mergedText,
1124
+ replaces: sourceItems,
1125
+ pinGlobal: hadPinned,
1126
+ })
1127
+ if (sug) {
1128
+ ws.suggestions.push(sug)
1129
+ createdProposals.push(sug)
1035
1130
  }
1036
- }
1037
- const sug = normalizeSuggestion({
1038
- kind: 'bound',
1039
- boundField: col,
1040
- fromAgent: '✦ 参谋长浓缩',
1041
- title: `${colLabel} ${sourceItems.length} 合 1:${clamp(mergedText, 26)}`,
1042
- reason: mergedReason,
1043
- target: 'bounds',
1044
- targetLabel: colLabel,
1045
- mode: 'silent',
1046
- draftText: mergedText,
1047
- replaces: sourceItems,
1048
- pinGlobal: hadPinned,
1049
1131
  })
1050
- if (sug) {
1051
- ws.suggestions.push(sug)
1052
- createdProposals.push(sug)
1053
- }
1054
- })
1055
- }
1132
+ }
1056
1133
 
1057
- if (!createdProposals.length) {
1058
- return { ok: false, error: '未能生成浓缩边界,请稍后重试。' }
1059
- }
1134
+ if (!createdProposals.length) {
1135
+ return { ok: false, error: '未能生成浓缩边界,请稍后重试。' }
1136
+ }
1060
1137
 
1061
- const replyLines = createdProposals.map(p =>
1062
- `- 【${p.targetLabel} · ${p.replaces.length} 合 1】${p.draftText}(可在上方请示卡片选「📌 定住全局」或「仅本任务」一键替换)`,
1063
- )
1138
+ const replyLines = createdProposals.map(p =>
1139
+ `- 【${p.targetLabel} · ${p.replaces.length} 合 1】${p.draftText}(可在上方请示卡片选「📌 定住全局」或「仅本任务」一键替换)`,
1140
+ )
1064
1141
 
1065
- return {
1066
- ok: true,
1067
- proposals: createdProposals,
1068
- reply: replyLines.join('\n'),
1069
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
1142
+ return {
1143
+ ok: true,
1144
+ proposals: createdProposals,
1145
+ reply: replyLines.join('\n'),
1146
+ view: await getChiefView(deps, rootId, { autoSummarize: false }),
1147
+ }
1148
+ } finally {
1149
+ endChiefActiveWork(rootId, consWorkId)
1070
1150
  }
1071
1151
  }
1072
1152
 
@@ -1077,6 +1157,7 @@ export async function askOrCommandChief(deps, {
1077
1157
  forcedMode = 'steer',
1078
1158
  images = [],
1079
1159
  _resumeCtx = null,
1160
+ _fromLeadRequest = false,
1080
1161
  }) {
1081
1162
  const rawInput = cleanMultiline(text, 2000)
1082
1163
  const rawImages = Array.isArray(images) ? images : []
@@ -1114,6 +1195,7 @@ export async function askOrCommandChief(deps, {
1114
1195
  const board = deps.boardForSession(deps.boardFileFor(rootId))
1115
1196
  const state = loadChiefState()
1116
1197
  const effCfg = resolveWorkspaceConfig(state, rootId)
1198
+ const policyPlugins = Array.isArray(effCfg.policyPlugins) ? effCfg.policyPlugins : []
1117
1199
  const ownWs = ensureWorkspace(state, rootId)
1118
1200
  const hasChiefRiskAck = hasValidChiefRiskAck(ownWs)
1119
1201
  const permissionMode = normalizePermissionMode(effCfg.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE, {
@@ -1137,11 +1219,11 @@ export async function askOrCommandChief(deps, {
1137
1219
  forceReceipt = false,
1138
1220
  }) => {
1139
1221
  const cleanActions = Array.isArray(actions) ? actions.filter(Boolean) : []
1140
- const isReceipt = Boolean(isResumeTurn || forceReceipt || elevationObj || pendingApprovalList.length > 0 || cleanActions.length > 0)
1222
+ const isReceipt = Boolean(isResumeTurn || _fromLeadRequest || forceReceipt || elevationObj || pendingApprovalList.length > 0 || cleanActions.length > 0)
1141
1223
  const finalActions = isResumeTurn
1142
1224
  ? [...new Set(['⚡ 授权自动续跑', ...cleanActions])].slice(0, 8)
1143
1225
  : cleanActions.slice(0, 8)
1144
- if (!isResumeTurn) {
1226
+ if (!isResumeTurn && !_fromLeadRequest) {
1145
1227
  ws.chat.push({
1146
1228
  id: nextId('chat'),
1147
1229
  role: 'user',
@@ -1155,13 +1237,24 @@ export async function askOrCommandChief(deps, {
1155
1237
  let attachedTaskId = resumeTaskId
1156
1238
  if (canAttachResume && (elevationObj || pendingApprovalList.length > 0)) {
1157
1239
  const aprIds = pendingApprovalList.map(a => a && a.id).filter(Boolean)
1158
- const task = upsertResumeTaskOnWs(ws, {
1159
- ...(resumeTaskId ? { id: resumeTaskId } : {}),
1240
+ const primaryApr = pendingApprovalList.find(Boolean) || null
1241
+ const task = upsertTaskLedgerOnWs(ws, {
1242
+ ...(resumeTaskId ? { id: resumeTaskId, taskId: resumeTaskId } : {}),
1243
+ kind: aprIds.length > 0 ? 'approval_resume' : 'elevation_resume',
1160
1244
  status: aprIds.length > 0 ? 'awaiting_approval' : 'awaiting_elevation',
1245
+ capabilityScope: primaryApr && primaryApr.capabilityScope ? primaryApr.capabilityScope : null,
1246
+ payloadHash: primaryApr && primaryApr.payloadHash ? primaryApr.payloadHash : '',
1247
+ resumeSpec: {
1248
+ originalText: input,
1249
+ forcedTarget,
1250
+ forcedMode,
1251
+ savedImagePaths,
1252
+ },
1161
1253
  originalText: input,
1162
1254
  forcedTarget,
1163
1255
  forcedMode,
1164
1256
  savedImagePaths,
1257
+ retryCount: resumeDepth,
1165
1258
  resumeDepth,
1166
1259
  elevationId: elevationObj ? elevationObj.id : '',
1167
1260
  pendingApprovalIds: aprIds,
@@ -1170,9 +1263,11 @@ export async function askOrCommandChief(deps, {
1170
1263
  if (task) {
1171
1264
  attachedTaskId = task.id
1172
1265
  if (elevationObj) {
1266
+ elevationObj.taskId = task.id
1173
1267
  elevationObj.resumeTaskId = task.id
1174
1268
  if (task.expiresAt) elevationObj.expiresAt = task.expiresAt
1175
1269
  if (ws.pendingElevation && ws.pendingElevation.id === elevationObj.id) {
1270
+ ws.pendingElevation.taskId = task.id
1176
1271
  ws.pendingElevation.resumeTaskId = task.id
1177
1272
  if (task.expiresAt) ws.pendingElevation.expiresAt = task.expiresAt
1178
1273
  }
@@ -1183,6 +1278,7 @@ export async function askOrCommandChief(deps, {
1183
1278
  if (!Array.isArray(listRef)) continue
1184
1279
  for (const apr of listRef) {
1185
1280
  if (apr && idSet.has(apr.id)) {
1281
+ apr.taskId = task.id
1186
1282
  apr.resumeTaskId = task.id
1187
1283
  if (task.expiresAt && !apr.expiresAt) apr.expiresAt = task.expiresAt
1188
1284
  }
@@ -1277,7 +1373,7 @@ export async function askOrCommandChief(deps, {
1277
1373
  savedImagePaths,
1278
1374
  memoryChanges: [],
1279
1375
  boardOps: [],
1280
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
1376
+ view: await getChiefView(deps, rootId, { autoSummarize: false, chatTriggered: !_fromLeadRequest }),
1281
1377
  }
1282
1378
  }
1283
1379
 
@@ -1500,6 +1596,22 @@ export async function askOrCommandChief(deps, {
1500
1596
  const resolvedCwd = deps && typeof deps.getSessionCwd === 'function' ? deps.getSessionCwd(rootId) : ''
1501
1597
  const explicitCompactReq = !imageBlocks.length && isExplicitCompactCommand(input)
1502
1598
  const statusOnlyInquiry = !imageBlocks.length && !explicitCompactReq && isPureStatusInquiry(input)
1599
+ const userExplicitDirect = /(?:参谋长.*?(?:亲自|自己|直接|别找主)|你自己(?:动手|改|跑|查|写)|别派发|勿转主对话)/.test(input)
1600
+ const hasLiveLead = Boolean(
1601
+ deps
1602
+ && deps.runtime
1603
+ && typeof deps.runtime.get === 'function'
1604
+ && deps.runtime.get('agents')
1605
+ && typeof deps.runtime.get('agents').get === 'function'
1606
+ && deps.runtime.get('agents').get(rootId),
1607
+ )
1608
+ const lazyDeferWorkspaceWritesToLead = Boolean(
1609
+ !isResumeTurn
1610
+ && !_fromLeadRequest
1611
+ && !userExplicitDirect
1612
+ && hasLiveLead
1613
+ && permissionMode === 'chief',
1614
+ )
1503
1615
 
1504
1616
  const effectiveSystem = [
1505
1617
  ASK_CHIEF_SYSTEM,
@@ -1507,10 +1619,12 @@ export async function askOrCommandChief(deps, {
1507
1619
  ...(isBlankContext
1508
1620
  ? [
1509
1621
  '',
1510
- '🌱 【当前处于空白新上下文(主对话尚未开聊)】:',
1622
+ '🌱 【当前处于空白新上下文(主对话尚未开聊 · 首轮勘探与计划立项策略)】:',
1511
1623
  resolvedCwd ? `- 当前已解析工作区根目录:${resolvedCwd}` : '',
1512
- '- 若用户让你查找/分析/修改当前工作区项目文件,请依据当前 permissionMode 直接调用你的真实 JSON `toolCalls` 工具(如 `list_dir` / `search_files` / `read_file` / `edit_file` / `run_command`)处理并如实汇报;绝对禁止直接向用户输出 `<|DSML|calls>` 等原始工具调用标签!',
1513
- '- 若尚无主对话历史,除非用户明确命令且会话已存在,不要无故调用 `session_compact`;若用户明确想把任务留给主对话开场接手,可放进 `relays`(`target: "lead"`)由系统自动暂存待领交接包。',
1624
+ !userExplicitDirect
1625
+ ? '- 默认开场铁律:首轮优先通过 `"relays"`(`target: "lead"`, `mode: "followup"`)向主对话 @lead 下发开场执行请求,要求主对话:① 先只读勘探代码库与目录结构;② 调用 `chief_board({ action: "graph.plan" })` / 计划工具进入计划模式立项拆解;③ 得出明确结论后调用 `chief_board({ action: "chief.request", subject: "勘探与计划回报", text: "..." })` 回报给参谋长。若当前为 L0/L1 权限不足以投递工作流指令,请同时填写 `"elevationRequest": { "targetMode": "strategist", "reason": "空白新对话首轮需授权向主对话下发勘探与计划立项指令" }`,并将完整勘探请求放进 `"relays"` 或建议备妥(绝对禁止向用户输出 `<|DSML|calls>` 等原始工具标签)。'
1626
+ : '- 用户已明确点名由你亲自排查/处理工作区,请依据当前 `permissionMode` 调用真实 JSON `toolCalls` 工具(`list_dir` / `search_files` / `read_file` / `edit_file` / `run_command`)处理并如实汇报;绝对禁止向用户输出 `<|DSML|calls>` 等原始工具调用标签!',
1627
+ '- 若尚无主对话历史,除非用户明确命令且会话已存在,不要无故调用 `session_compact`。',
1514
1628
  ].filter(Boolean)
1515
1629
  : []),
1516
1630
  ...(statusOnlyInquiry
@@ -1537,10 +1651,12 @@ export async function askOrCommandChief(deps, {
1537
1651
  allowTextFallbackOnVisionMiss: savedImagePaths.length > 0,
1538
1652
  permissionMode,
1539
1653
  hasChiefRiskAck,
1654
+ policyPlugins,
1540
1655
  board,
1541
1656
  maxSteps: statusOnlyInquiry ? 1 : 4,
1542
1657
  readOnlyToolsOnly: false,
1543
1658
  disableTools: statusOnlyInquiry,
1659
+ lazyDeferWorkspaceWritesToLead,
1544
1660
  callLlmFn: (callOpts) => callChiefLlm(deps, { ...callOpts, maxTokens: SUMMARY_MAX_TOKENS }),
1545
1661
  extractJsonFn: extractJsonObject,
1546
1662
  upsertArchiveFn,
@@ -1575,12 +1691,12 @@ export async function askOrCommandChief(deps, {
1575
1691
  loopBadges.push(compactGuard.badge || '🛡️ 卫兵拦截压缩')
1576
1692
  appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'safety_guard', decision: 'blocked', operation: '压缩主对话', target: 'current', reason: compactGuard.reason, outcome: 'blocked', by: 'chief' })
1577
1693
  } else {
1578
- const compactGate = evaluateChiefPermissionGate({ permissionMode, hasChiefRiskAck, opClass: 'workflow', tool: 'session_compact' })
1579
- if (compactGate.decision === 'deny_mode' || compactGate.decision === 'deny_unacknowledged_l3') {
1580
- workflowBlockedNeedsElevation = true
1694
+ const compactGate = evaluateChiefPermissionGate({ permissionMode, hasChiefRiskAck, policyPlugins, opClass: 'workflow', tool: 'session_compact' })
1695
+ if (compactGate.decision === 'deny_mode' || compactGate.decision === 'deny_unacknowledged_l3' || compactGate.decision === 'deny_policy_plugin') {
1696
+ workflowBlockedNeedsElevation = compactGate.decision !== 'deny_policy_plugin'
1581
1697
  forcedCompactOut = { ok: false, deniedByMode: true, error: compactGate.error }
1582
1698
  loopBadges.push(compactGate.badge || '🔒 权限禁压')
1583
- appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'permission_gate', decision: compactGate.decision, operation: '压缩主对话', target: 'current', reason: compactGate.error, outcome: 'denied', by: 'chief' })
1699
+ appendChiefAuditLog(rootId, { mode: permissionMode, stage: compactGate.decision === 'deny_policy_plugin' ? 'policy_plugin' : 'permission_gate', rule: compactGate.rule || compactGate.decision, decision: compactGate.decision, operation: '压缩主对话', target: 'current', reason: compactGate.error, outcome: 'denied', by: 'chief' })
1584
1700
  } else if (compactGate.decision === 'require_approval') {
1585
1701
  const apr = queueChiefApproval(rootId, {
1586
1702
  category: 'main_workflow',
@@ -1589,6 +1705,7 @@ export async function askOrCommandChief(deps, {
1589
1705
  reason: clamp(input, 140),
1590
1706
  impact: '会触发主会话历史压缩,先抢救细节入本会话档案柜再压缩裁剪历史上下文',
1591
1707
  kind: 'compact',
1708
+ capabilityScope: buildCapabilityScope({ kind: 'compact', tool: 'session_compact' }),
1592
1709
  payload: { reason: `用户指令触发:${input}` },
1593
1710
  by: 'chief',
1594
1711
  })
@@ -1654,7 +1771,7 @@ export async function askOrCommandChief(deps, {
1654
1771
  savedImagePaths,
1655
1772
  memoryChanges: [],
1656
1773
  boardOps: [],
1657
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
1774
+ view: await getChiefView(deps, rootId, { autoSummarize: false, chatTriggered: !_fromLeadRequest }),
1658
1775
  }
1659
1776
  }
1660
1777
 
@@ -1745,7 +1862,7 @@ export async function askOrCommandChief(deps, {
1745
1862
  memoryChanges: [],
1746
1863
  boardOps: ['重设任务看板'],
1747
1864
  board: resetRes.board,
1748
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
1865
+ view: await getChiefView(deps, rootId, { autoSummarize: false, chatTriggered: !_fromLeadRequest }),
1749
1866
  }
1750
1867
  }
1751
1868
  }
@@ -1783,7 +1900,7 @@ export async function askOrCommandChief(deps, {
1783
1900
  memoryChanges: [],
1784
1901
  boardOps: [],
1785
1902
  networkOps: badges,
1786
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
1903
+ view: await getChiefView(deps, rootId, { autoSummarize: false, chatTriggered: !_fromLeadRequest }),
1787
1904
  }
1788
1905
  }
1789
1906
  }
@@ -1830,7 +1947,7 @@ export async function askOrCommandChief(deps, {
1830
1947
  toolRecords: loopToolRecords,
1831
1948
  pendingApprovals: queuedApprovals,
1832
1949
  ...(autoElevOut ? { elevationRequested: autoElevOut } : {}),
1833
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
1950
+ view: await getChiefView(deps, rootId, { autoSummarize: false, chatTriggered: !_fromLeadRequest }),
1834
1951
  }
1835
1952
  }
1836
1953
 
@@ -1848,7 +1965,7 @@ export async function askOrCommandChief(deps, {
1848
1965
  }
1849
1966
  const strippedPlain = llmRes.ok && llmRes.text ? stripToolCallMarkup(llmRes.text).trim() : ''
1850
1967
  const usablePlainLlm = strippedPlain && !strippedPlain.startsWith('{') && strippedPlain.length >= 6
1851
- ? cleanMultiline(strippedPlain, 900)
1968
+ ? cleanMultiline(strippedPlain, 2200)
1852
1969
  : ''
1853
1970
  const archiveFallback = onDemandArchiveLines.length > 1
1854
1971
  ? ['- 【已从沉淀档案柜按需检索到以下卷宗】', ...onDemandArchiveLines.slice(2)].join('\n')
@@ -1863,14 +1980,44 @@ export async function askOrCommandChief(deps, {
1863
1980
  conciseBrief: isConciseBrief,
1864
1981
  })
1865
1982
  const replyText = isConciseBrief ? sanitizeConciseBriefText(rawFallbackReply) : rawFallbackReply
1983
+ const fallbackBounds = permRank >= 1 ? extractFallbackBoundProposalsFromText(rawFallbackReply, input) : []
1984
+ const createdFallbackBounds = []
1985
+ const BOUND_COL_LABEL_FB = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
1866
1986
 
1867
1987
  mutateChiefState((s) => {
1868
1988
  const ws = ensureWorkspace(s, rootId)
1989
+ const existingFb = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
1990
+ for (const fb of fallbackBounds) {
1991
+ const col = ['forbidden', 'allowed', 'notes'].includes(fb.field) ? fb.field : 'forbidden'
1992
+ const colList = Array.isArray(existingFb[col]) ? existingFb[col] : []
1993
+ if (colList.some(x => String(x).trim() === fb.item)) continue
1994
+ if (ws.suggestions.some(ex => ex && ex.status === 'pending' && ex.kind === 'bound' && ex.draftText === fb.item)) continue
1995
+ const colLabel = BOUND_COL_LABEL_FB[col] || '禁止红线'
1996
+ const sug = normalizeSuggestion({
1997
+ kind: 'bound',
1998
+ boundField: col,
1999
+ fromAgent: '✦ 参谋长提炼',
2000
+ title: `拟入${colLabel}:${clamp(fb.item, 30)}`,
2001
+ reason: fb.reason,
2002
+ target: 'bounds',
2003
+ targetLabel: colLabel,
2004
+ mode: 'silent',
2005
+ draftText: fb.item,
2006
+ pinGlobal: Boolean(fb.pinGlobal),
2007
+ })
2008
+ if (sug) {
2009
+ ws.suggestions.push(sug)
2010
+ if (ws.suggestions.length > SUGGESTIONS_CAP) ws.suggestions = ws.suggestions.slice(-SUGGESTIONS_CAP)
2011
+ createdFallbackBounds.push(sug)
2012
+ loopBadges.push(`呈批${colLabel}:${clamp(fb.item, 18)}`)
2013
+ }
2014
+ }
1869
2015
  persistTurnChatAndResume(ws, {
1870
2016
  chiefText: replyText,
1871
2017
  actions: loopBadges,
1872
2018
  elevationObj: fallbackElev,
1873
2019
  pendingApprovalList: queuedApprovals,
2020
+ forceReceipt: createdFallbackBounds.length > 0,
1874
2021
  })
1875
2022
  })
1876
2023
  return {
@@ -1879,11 +2026,12 @@ export async function askOrCommandChief(deps, {
1879
2026
  relays: [],
1880
2027
  memoryChanges: [],
1881
2028
  boardOps: [],
2029
+ boundProposals: createdFallbackBounds,
1882
2030
  actionBadges: loopBadges,
1883
2031
  toolRecords: loopToolRecords,
1884
2032
  pendingApprovals: queuedApprovals,
1885
2033
  ...(fallbackElev ? { elevationRequested: fallbackElev } : {}),
1886
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
2034
+ view: await getChiefView(deps, rootId, { autoSummarize: false, chatTriggered: !_fromLeadRequest }),
1887
2035
  }
1888
2036
  }
1889
2037
 
@@ -1893,6 +2041,7 @@ export async function askOrCommandChief(deps, {
1893
2041
  const relayGate = evaluateChiefPermissionGate({
1894
2042
  permissionMode,
1895
2043
  hasChiefRiskAck,
2044
+ policyPlugins,
1896
2045
  opClass: 'workflow',
1897
2046
  tool: 'relay',
1898
2047
  })
@@ -1907,15 +2056,15 @@ export async function askOrCommandChief(deps, {
1907
2056
  if (relayGuard.blocked) {
1908
2057
  actionBadges.push(relayGuard.badge || '🛡️ 卫兵拦递话')
1909
2058
  relayResults.push({ ok: false, target: targetName, blockedBySafetyGuard: true, error: relayGuard.reason })
1910
- appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'safety_guard', decision: 'blocked', operation: '工作流递话', target: String(targetName), reason: relayGuard.reason, outcome: 'blocked', by: 'chief' })
2059
+ appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'safety_guard', rule: relayGuard.rule || 'hard_guard', decision: 'blocked', operation: '工作流递话', target: String(targetName), reason: relayGuard.reason, outcome: 'blocked', by: 'chief' })
1911
2060
  continue
1912
2061
  }
1913
2062
 
1914
- if (relayGate.decision === 'deny_mode' || relayGate.decision === 'deny_unacknowledged_l3') {
1915
- workflowBlockedNeedsElevation = true
2063
+ if (relayGate.decision === 'deny_mode' || relayGate.decision === 'deny_unacknowledged_l3' || relayGate.decision === 'deny_policy_plugin') {
2064
+ if (relayGate.decision !== 'deny_policy_plugin') workflowBlockedNeedsElevation = true
1916
2065
  actionBadges.push(relayGate.badge || '🔒 权限禁调工作流')
1917
2066
  relayResults.push({ ok: false, target: targetName, deniedByMode: true, error: relayGate.error })
1918
- appendChiefAuditLog(rootId, { mode: permissionMode, stage: 'permission_gate', decision: relayGate.decision, operation: isLeadTarget ? '调整主对话工作流' : '调整子代理工作流', target: String(targetName), reason: relayGate.error, outcome: 'denied', by: 'chief' })
2067
+ appendChiefAuditLog(rootId, { mode: permissionMode, stage: relayGate.decision === 'deny_policy_plugin' ? 'policy_plugin' : 'permission_gate', rule: relayGate.rule || relayGate.decision, decision: relayGate.decision, operation: isLeadTarget ? '调整主对话工作流' : '调整子代理工作流', target: String(targetName), reason: relayGate.error, outcome: 'denied', by: 'chief' })
1919
2068
  continue
1920
2069
  }
1921
2070
 
@@ -1928,13 +2077,16 @@ export async function askOrCommandChief(deps, {
1928
2077
  impact: isLeadTarget ? '将向主对话注入工作流指令并触发继续推进' : '将唤醒或引导子代理执行新任务指令',
1929
2078
  preview: clamp(r.text, 240),
1930
2079
  kind: 'relay',
2080
+ capabilityScope: buildCapabilityScope({ kind: 'relay', tool: 'relay', target: targetName }),
1931
2081
  payload: {
1932
2082
  fromSession: rootId,
1933
- fromLabel: 'DSH 参谋 (逐项授权)',
2083
+ fromLabel: 'DSH 参谋 (执行请求 · 逐项授权)',
1934
2084
  target: targetName,
1935
2085
  subject: r.subject || '',
1936
2086
  text: r.text,
1937
2087
  mode: relayMode,
2088
+ envelopeKind: 'execution_request',
2089
+ taskId: r.taskId || '',
1938
2090
  imageBlocks,
1939
2091
  savedImagePaths,
1940
2092
  isBlankContext,
@@ -1948,14 +2100,16 @@ export async function askOrCommandChief(deps, {
1948
2100
  continue
1949
2101
  }
1950
2102
 
1951
- // L3 Chief mode: execute directly
2103
+ // L3 Chief mode: execute via explicit execution_request envelope (never impersonate user)
1952
2104
  const deliv = await deliverCrossMessage(deps, {
1953
2105
  fromSession: rootId,
1954
- fromLabel: 'DSH 参谋长 (代用户传达)',
2106
+ fromLabel: 'DSH 参谋长 (执行请求)',
1955
2107
  target: targetName,
1956
2108
  subject: r.subject || '',
1957
2109
  text: r.text,
1958
2110
  mode: relayMode,
2111
+ envelopeKind: 'execution_request',
2112
+ taskId: r.taskId || '',
1959
2113
  imageBlocks,
1960
2114
  savedImagePaths,
1961
2115
  })
@@ -1978,16 +2132,28 @@ export async function askOrCommandChief(deps, {
1978
2132
  }
1979
2133
 
1980
2134
  // Execute Chief-system ops (L1 Assistant+ required; strictly denied in L0 Advisor)
2135
+ const rawInquiries = Array.isArray(parsed.inquiries) ? parsed.inquiries.slice(0, 3) : []
2136
+ const rawWallListSrc = Array.isArray(parsed.wallProposals)
2137
+ ? parsed.wallProposals
2138
+ : (Array.isArray(parsed.guardWalls) ? parsed.guardWalls : [])
2139
+ const rawWallProposals = rawWallListSrc.slice(0, 4)
2140
+ const rawBoundListSrc = Array.isArray(parsed.boundProposals) && parsed.boundProposals.length > 0
2141
+ ? parsed.boundProposals
2142
+ : (Array.isArray(parsed.boundaryProposals) && parsed.boundaryProposals.length > 0
2143
+ ? parsed.boundaryProposals
2144
+ : extractFallbackBoundProposalsFromText(parsed.reply || '', input))
1981
2145
  const hasSystemOps = Boolean(
1982
2146
  (Array.isArray(parsed.boardOps) && parsed.boardOps.length > 0)
1983
2147
  || (Array.isArray(parsed.archiveOps) && parsed.archiveOps.length > 0)
1984
2148
  || (Array.isArray(parsed.networkOps) && parsed.networkOps.length > 0)
1985
2149
  || (Array.isArray(parsed.memoryChanges) && parsed.memoryChanges.length > 0)
1986
- || (Array.isArray(parsed.boundProposals) && parsed.boundProposals.length > 0),
2150
+ || rawBoundListSrc.length > 0
2151
+ || rawWallProposals.length > 0,
1987
2152
  )
1988
2153
  const systemGate = evaluateChiefPermissionGate({
1989
2154
  permissionMode,
1990
2155
  hasChiefRiskAck,
2156
+ policyPlugins,
1991
2157
  opClass: 'chief_system',
1992
2158
  tool: 'chief_system',
1993
2159
  })
@@ -1998,15 +2164,16 @@ export async function askOrCommandChief(deps, {
1998
2164
  let appliedFacts = []
1999
2165
  const proposedBounds = []
2000
2166
  const existingBounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
2001
- const rawBoundProposals = Array.isArray(parsed.boundProposals) ? parsed.boundProposals.slice(0, 4) : []
2167
+ const rawBoundProposals = rawBoundListSrc.slice(0, 4)
2002
2168
 
2003
- if (hasSystemOps && systemGate.decision === 'deny_mode') {
2004
- chiefSystemBlockedNeedsElevation = true
2169
+ if (hasSystemOps && systemGate.decision !== 'allow' && systemGate.decision !== 'allow_approved') {
2170
+ chiefSystemBlockedNeedsElevation = systemGate.decision === 'deny_mode'
2005
2171
  actionBadges.push(systemGate.badge || '🔒 L0禁改参谋系统')
2006
2172
  appendChiefAuditLog(rootId, {
2007
2173
  mode: permissionMode,
2008
- stage: 'permission_gate',
2009
- decision: 'deny_mode',
2174
+ stage: systemGate.decision === 'deny_policy_plugin' ? 'policy_plugin' : 'permission_gate',
2175
+ rule: systemGate.rule || systemGate.decision,
2176
+ decision: systemGate.decision,
2010
2177
  operation: '修改参谋系统(看板/记忆/档案)',
2011
2178
  target: 'chief_system',
2012
2179
  reason: systemGate.error,
@@ -2014,7 +2181,7 @@ export async function askOrCommandChief(deps, {
2014
2181
  by: 'chief',
2015
2182
  })
2016
2183
  } else if (hasSystemOps) {
2017
- executedBoardOps = applyBoardOps(deps, rootId, parsed.boardOps)
2184
+ executedBoardOps = applyBoardOps(deps, rootId, parsed.boardOps, { callerOrigin: 'chief_llm' })
2018
2185
  for (const b of executedBoardOps) actionBadges.push(b)
2019
2186
 
2020
2187
  const archiveExec = await applyArchiveOps(deps, rootId, parsed.archiveOps, { input })
@@ -2102,14 +2269,50 @@ export async function askOrCommandChief(deps, {
2102
2269
  baseParsedReply,
2103
2270
  ...permissionStatusNotes,
2104
2271
  ].filter(Boolean).join('\n')
2105
- const rawReplyText = cleanMultiline(combinedParsedReply, 1100)
2272
+ const rawReplyText = cleanMultiline(combinedParsedReply, 1800)
2106
2273
  const replyText = isConciseBrief ? sanitizeConciseBriefText(rawReplyText) : rawReplyText
2107
2274
 
2108
2275
  const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
2276
+ const createdInquiries = []
2277
+ const proposedWalls = []
2278
+ const cwdForWall = resolveSessionWorkspaceCwd(deps, rootId)
2109
2279
 
2110
2280
  mutateChiefState((s) => {
2111
2281
  const ws = ensureWorkspace(s, rootId)
2112
- if (systemGate.decision === 'allow') {
2282
+ for (const rawInq of rawInquiries) {
2283
+ if (!rawInq || typeof rawInq !== 'object') continue
2284
+ const qText = cleanMultiline(rawInq.question || rawInq.text || '', 500)
2285
+ if (!qText || secretLike(qText)) continue
2286
+ const inqTarget = clamp(rawInq.target || 'lead', 48) || 'lead'
2287
+ const inqTask = upsertTaskLedgerOnWs(ws, {
2288
+ kind: 'inquiry',
2289
+ status: 'awaiting_inquiry',
2290
+ originalText: `问询 @${inqTarget}:${qText}`,
2291
+ forcedTarget: inqTarget,
2292
+ })
2293
+ const inqItem = enqueueChiefInquiryOnWs(ws, {
2294
+ target: inqTarget,
2295
+ question: qText,
2296
+ context: cleanMultiline(rawInq.context || '', 240),
2297
+ taskId: inqTask ? inqTask.taskId : '',
2298
+ })
2299
+ if (inqItem) {
2300
+ createdInquiries.push(inqItem)
2301
+ if (inqTask) {
2302
+ upsertTaskLedgerOnWs(ws, {
2303
+ id: inqTask.taskId,
2304
+ taskId: inqTask.taskId,
2305
+ kind: 'inquiry',
2306
+ status: 'awaiting_inquiry',
2307
+ originalText: inqTask.originalText,
2308
+ inquiryId: inqItem.inquiryId,
2309
+ })
2310
+ }
2311
+ actionBadges.push(`⚡ 问询 @${inqItem.target} #${inqItem.inquiryId}`)
2312
+ }
2313
+ }
2314
+
2315
+ if (systemGate.decision === 'allow' || systemGate.decision === 'allow_approved') {
2113
2316
  const activeCluster = getLinkedCluster(s, rootId)
2114
2317
  appliedFacts = applyFactChanges(ws, numberedFacts, parsed.memoryChanges, 'user', {
2115
2318
  originRootId: rootId,
@@ -2119,12 +2322,56 @@ export async function askOrCommandChief(deps, {
2119
2322
  actionBadges.push((f.op === 'add' ? '记入:' : f.op === 'edit' ? '修订:' : '移除:') + clamp(f.text, 24))
2120
2323
  }
2121
2324
 
2122
- for (const bp of rawBoundProposals) {
2325
+ for (const rawWp of rawWallProposals) {
2326
+ if (!rawWp || typeof rawWp !== 'object') continue
2327
+ const mappedRuleType = rawWp.ruleType || rawWp.type
2328
+ || (rawWp.field === 'path' ? 'forbid_path' : (rawWp.field === 'command' ? 'forbid_cmd' : undefined))
2329
+ const wp = {
2330
+ ...rawWp,
2331
+ title: rawWp.title || rawWp.name || '',
2332
+ ...(mappedRuleType ? { ruleType: mappedRuleType } : {}),
2333
+ patterns: rawWp.patterns || rawWp.pattern || rawWp.rules,
2334
+ }
2335
+ const val = validateGuardWallInput(wp, { cwd: cwdForWall })
2336
+ if (!val || !val.ok || !val.wall) continue
2337
+ if (secretLike(val.wall.title) || val.wall.patterns.some(p => secretLike(p))) continue
2338
+ const dupPendingWall = ws.suggestions.some(
2339
+ existing => existing
2340
+ && existing.status === 'pending'
2341
+ && existing.kind === 'guard_wall'
2342
+ && existing.wallSpec
2343
+ && existing.wallSpec.title === val.wall.title,
2344
+ )
2345
+ if (dupPendingWall) continue
2346
+ const sug = normalizeSuggestion({
2347
+ kind: 'guard_wall',
2348
+ fromAgent: '🧱 参谋长筑墙提案',
2349
+ title: `拟筑物理墙:${clamp(val.wall.title, 30)}`,
2350
+ reason: clamp(val.wall.reason || '事前硬拦截高危命令或敏感路径,确认后写入 guard-walls 持久落锁。', 180),
2351
+ target: 'guard_walls',
2352
+ targetLabel: val.wall.scope === 'workspace' ? '📁 本工程驻墙' : '🌐 全局随身驻墙',
2353
+ mode: 'silent',
2354
+ draftText: `[${val.wall.ruleType}] ${val.wall.patterns.join(', ')}`,
2355
+ wallSpec: val.wall,
2356
+ })
2357
+ if (sug) {
2358
+ ws.suggestions.push(sug)
2359
+ if (ws.suggestions.length > SUGGESTIONS_CAP) ws.suggestions = ws.suggestions.slice(-SUGGESTIONS_CAP)
2360
+ proposedWalls.push(sug)
2361
+ actionBadges.push(`🧱 呈批驻墙:${clamp(val.wall.title, 18)}`)
2362
+ }
2363
+ }
2364
+
2365
+ for (const rawBp of rawBoundProposals) {
2366
+ if (!rawBp) continue
2367
+ const bp = typeof rawBp === 'string'
2368
+ ? { field: 'forbidden', item: rawBp, reason: '根据会话上下文提炼的工作边界,请拍板注入。' }
2369
+ : rawBp
2123
2370
  if (!bp || typeof bp !== 'object') continue
2124
2371
  const rawBpField = String(bp.field || '').trim().toLowerCase()
2125
2372
  const normBpField = rawBpField === 'must' ? 'allowed' : rawBpField
2126
2373
  const col = ['forbidden', 'allowed', 'notes'].includes(normBpField) ? normBpField : 'forbidden'
2127
- const itemText = clamp(bp.item || bp.draftText || bp.text || '', 220)
2374
+ const itemText = clamp(bp.item || bp.rule || bp.content || bp.draftText || bp.text || '', 220)
2128
2375
  if (!itemText || secretLike(itemText)) continue
2129
2376
  const replaces = Array.isArray(bp.replaces)
2130
2377
  ? bp.replaces.filter(x => typeof x === 'string' && x.trim()).map(x => x.trim().slice(0, 240)).slice(0, 20)
@@ -2172,6 +2419,8 @@ export async function askOrCommandChief(deps, {
2172
2419
  pendingApprovalList: queuedApprovals,
2173
2420
  forceReceipt: Boolean(
2174
2421
  relayResults.length > 0
2422
+ || createdInquiries.length > 0
2423
+ || proposedWalls.length > 0
2175
2424
  || appliedFacts.length > 0
2176
2425
  || executedBoardOps.length > 0
2177
2426
  || executedArchiveOps.length > 0
@@ -2184,12 +2433,49 @@ export async function askOrCommandChief(deps, {
2184
2433
  })
2185
2434
  })
2186
2435
 
2187
- // Refresh narrative summary in background if facts, board, archives, or network changed
2436
+ // Gently wake idle lead/peer for queued inquiries (if currently running, agent/pre-step picks them up without interruption)
2437
+ if (createdInquiries.length > 0 && deps && deps.runtime && typeof deps.runtime.get === 'function') {
2438
+ const agentsSvc = deps.runtime.get('agents')
2439
+ const leadAgent = agentsSvc && typeof agentsSvc.get === 'function' ? agentsSvc.get(rootId) : null
2440
+ if (leadAgent && leadAgent.status && leadAgent.status !== 'running') {
2441
+ for (const inqItem of createdInquiries) {
2442
+ if (!/^(?:lead|主对话)$/i.test(inqItem.target || 'lead')) continue
2443
+ try {
2444
+ const nudgeRes = await deliverCrossMessage(deps, {
2445
+ fromSession: rootId,
2446
+ fromLabel: 'DSH 参谋长 (优先问询)',
2447
+ target: inqItem.target || 'lead',
2448
+ subject: `#${inqItem.inquiryId}`,
2449
+ text: `${inqItem.question}${inqItem.context ? `\n背景:${inqItem.context}` : ''}\n请调用 chief_board({ action: "inquiry.reply", inquiryId: "${inqItem.inquiryId}", text: "..." }) 原路回传,无需中断原计划。`,
2450
+ mode: 'followup',
2451
+ envelopeKind: 'inquiry',
2452
+ taskId: inqItem.inquiryId,
2453
+ recordBoardLog: false,
2454
+ })
2455
+ if (nudgeRes && nudgeRes.deliveredPhysical) {
2456
+ mutateChiefState((s) => {
2457
+ const ws = ensureWorkspace(s, rootId)
2458
+ const rec = Array.isArray(ws.inquiries) && ws.inquiries.find(q => q && q.inquiryId === inqItem.inquiryId)
2459
+ if (rec && rec.status === 'pending') {
2460
+ rec.status = 'delivered'
2461
+ rec.deliveredAt = Date.now()
2462
+ }
2463
+ })
2464
+ }
2465
+ } catch {}
2466
+ }
2467
+ }
2468
+ }
2469
+
2470
+ // Refresh narrative summary in background if facts, board, archives, or network changed (plus 60s debounced opportunistic refresh on user chat)
2188
2471
  const shouldRefreshNarrative = appliedFacts.length > 0
2189
2472
  || executedBoardOps.length > 0
2190
2473
  || executedArchiveOps.length > 0
2191
2474
  || executedNetworkOps.length > 0
2192
- const freshView = await getChiefView(deps, rootId, { autoSummarize: shouldRefreshNarrative })
2475
+ const freshView = await getChiefView(deps, rootId, {
2476
+ autoSummarize: shouldRefreshNarrative,
2477
+ chatTriggered: !_fromLeadRequest,
2478
+ })
2193
2479
  const freshBoard = executedBoardOps.length > 0 && deps.boardForSession && deps.boardFileFor
2194
2480
  ? deps.boardForSession(deps.boardFileFor(rootId))
2195
2481
  : undefined
@@ -2207,6 +2493,8 @@ export async function askOrCommandChief(deps, {
2207
2493
  ok: true,
2208
2494
  reply: replyText,
2209
2495
  relays: relayResults,
2496
+ inquiries: createdInquiries,
2497
+ wallProposals: proposedWalls,
2210
2498
  actionBadges,
2211
2499
  memoryChanges: appliedFacts,
2212
2500
  boardOps: executedBoardOps,
@@ -2511,3 +2799,222 @@ export async function suggestCoreObjectiveWithChief(deps, {
2511
2799
  llmUsed,
2512
2800
  }
2513
2801
  }
2802
+
2803
+ /**
2804
+ * Lead-to-Chief direct communication handler (`chief.request` / `mail.send({ target: 'chief' })`).
2805
+ * Applies L0–L3 permission-tiered handling so Lead requests either queue advice + elevation (L0/L1),
2806
+ * queue one-click user approval (L2), or execute & reply directly via Chief (L3).
2807
+ */
2808
+ export async function handleLeadDirectRequestToChief(deps, {
2809
+ fromSession = '',
2810
+ fromLabel = '主对话 (@lead)',
2811
+ subject = '',
2812
+ text = '',
2813
+ } = {}) {
2814
+ const cleanBody = cleanMultiline(text, 2400)
2815
+ if (!cleanBody) return { ok: false, error: '传话给参谋长的内容不能为空' }
2816
+ const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(fromSession) : '') || String(fromSession || 'global')
2817
+ const state = loadChiefState()
2818
+ const ownWs = ensureWorkspace(state, rootId)
2819
+ const effCfg = resolveWorkspaceConfig(state, rootId)
2820
+ const hasChiefRiskAck = hasValidChiefRiskAck(ownWs)
2821
+ const permissionMode = normalizePermissionMode(effCfg.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE, {
2822
+ requireAck: true,
2823
+ hasChiefRiskAck,
2824
+ })
2825
+ const permRank = permissionRank(permissionMode)
2826
+ const summaryTitle = clamp(subject || cleanBody, 48)
2827
+ let ledgerTaskId = ''
2828
+
2829
+ mutateChiefState((s) => {
2830
+ const ws = ensureWorkspace(s, rootId)
2831
+ const entry = upsertTaskLedgerOnWs(ws, {
2832
+ kind: permRank < 2 ? 'elevation_resume' : (permRank === 2 ? 'approval_resume' : 'tool_execution'),
2833
+ status: permRank < 2 ? 'awaiting_elevation' : (permRank === 2 ? 'awaiting_approval' : 'running'),
2834
+ originalText: `[主对话直传求助 · ${fromLabel}] ${subject ? subject + ':' : ''}${cleanBody}`,
2835
+ forcedTarget: 'lead',
2836
+ lastReceipt: `收到 ${fromLabel} 直传协同请求,按 ${permissionMode} 权限处置中`,
2837
+ })
2838
+ if (entry) ledgerTaskId = entry.taskId
2839
+ })
2840
+
2841
+ // L0 (advisor) / L1 (assistant): queue readable advice + optional elevation request (never mutate workspace directly)
2842
+ if (permRank < 2) {
2843
+ const elv = requestChiefElevation(rootId, {
2844
+ fromMode: permissionMode,
2845
+ targetMode: 'strategist',
2846
+ reason: `主对话(${fromLabel})请求参谋长协同处置:${clamp(subject || cleanBody, 90)}`,
2847
+ requestedActionSummary: clamp(cleanBody, 160),
2848
+ by: 'chief',
2849
+ })
2850
+ mutateChiefState((s) => {
2851
+ const ws = ensureWorkspace(s, rootId)
2852
+ const sug = normalizeSuggestion({
2853
+ kind: 'advice',
2854
+ fromAgent: '📨 主对话直传求助',
2855
+ title: `参谋建议 · 响应主对话:${clamp(summaryTitle, 32)}`,
2856
+ reason: `主对话主动发起协同请示(当前 ${CHIEF_PERMISSION_META[permissionMode]?.level || permissionMode} 只读/参谋档),请您拍板或批准升档执行。`,
2857
+ target: 'lead',
2858
+ targetLabel: '主对话 (@lead)',
2859
+ mode: 'followup',
2860
+ draftText: clamp(`关于「${subject || '协同请求'}」的参谋建议:请先评估影响范围与验证方案;如已批准升档,我可进一步协调执行。原请求:${cleanBody}`, 420),
2861
+ })
2862
+ if (sug) {
2863
+ ws.suggestions.push(sug)
2864
+ if (ws.suggestions.length > SUGGESTIONS_CAP) ws.suggestions = ws.suggestions.slice(-SUGGESTIONS_CAP)
2865
+ }
2866
+ if (ledgerTaskId) {
2867
+ upsertTaskLedgerOnWs(ws, {
2868
+ id: ledgerTaskId,
2869
+ taskId: ledgerTaskId,
2870
+ kind: 'elevation_resume',
2871
+ status: 'awaiting_elevation',
2872
+ originalText: `[主对话直传求助 · ${fromLabel}] ${cleanBody}`,
2873
+ elevationId: elv ? elv.id : '',
2874
+ lastReceipt: `已生成参谋建议${elv ? '并发起 L2 提权请示' : ''}`,
2875
+ })
2876
+ }
2877
+ ws.chat.push({
2878
+ id: nextId('chat'),
2879
+ role: 'chief',
2880
+ kind: 'receipt',
2881
+ text: [
2882
+ `- 【📨 收到主对话直传请求(当前 ${CHIEF_PERMISSION_META[permissionMode]?.level || permissionMode})】来自 ${fromLabel}${subject ? ` · ${subject}` : ''}`,
2883
+ `- 【请求摘要】${clamp(cleanBody, 220)}`,
2884
+ `- 【处置结果】已生成参谋建议并${elv ? '向您发起「🔐 升至 L2 · 参谋模式」提权请示' : '记入建议栏'};您拍板或提权后即可向主对话投递执行批复。`,
2885
+ ].join('\n'),
2886
+ actions: ['主对话直传求助', ...(elv ? ['🔐 请示提权 L2'] : ['💡 已呈报建议'])],
2887
+ at: Date.now(),
2888
+ })
2889
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
2890
+ })
2891
+ return {
2892
+ ok: true,
2893
+ mode: permissionMode,
2894
+ actionTaken: 'suggested_or_elevation_requested',
2895
+ taskId: ledgerTaskId,
2896
+ ...(elv ? { elevationRequested: elv } : {}),
2897
+ }
2898
+ }
2899
+
2900
+ // L2 (strategist): queue actionable approval & suggestion for one-click human confirmation
2901
+ if (permRank === 2) {
2902
+ const replyDraft = `已核准来自主对话的协同请求(${subject || '协同处理'}):请按约定继续推进,并在完成后提交验证证据。`
2903
+ const apr = queueChiefApproval(rootId, {
2904
+ category: 'main_workflow',
2905
+ operationLabel: '响应主对话直接协同请求',
2906
+ targetLabel: '主对话 (@lead)',
2907
+ reason: clamp(subject || '主对话请求参谋长协同处置', 140),
2908
+ impact: '点击「允许本次操作」后,将向主对话投递参谋协同批复执行请求',
2909
+ preview: clamp(cleanBody, 240),
2910
+ kind: 'relay',
2911
+ capabilityScope: buildCapabilityScope({ kind: 'relay', tool: 'relay', target: 'lead' }),
2912
+ payload: {
2913
+ fromSession: rootId,
2914
+ fromLabel: 'DSH 参谋 (获批响应主对话)',
2915
+ target: 'lead',
2916
+ subject: subject || '参谋协同批复',
2917
+ text: replyDraft,
2918
+ mode: 'steer',
2919
+ envelopeKind: 'execution_request',
2920
+ taskId: ledgerTaskId,
2921
+ },
2922
+ by: 'chief',
2923
+ })
2924
+ mutateChiefState((s) => {
2925
+ const ws = ensureWorkspace(s, rootId)
2926
+ const sug = normalizeSuggestion({
2927
+ kind: 'relay',
2928
+ fromAgent: '📨 主对话直传求助',
2929
+ title: `批复主对话:${clamp(summaryTitle, 32)}`,
2930
+ reason: 'L2 参谋模式下已挂入逐项授权弹窗,也可直接点击上方「执行建议」批准投递。',
2931
+ target: 'lead',
2932
+ targetLabel: '主对话 (@lead)',
2933
+ mode: 'steer',
2934
+ draftText: replyDraft,
2935
+ })
2936
+ if (sug) {
2937
+ ws.suggestions.push(sug)
2938
+ if (ws.suggestions.length > SUGGESTIONS_CAP) ws.suggestions = ws.suggestions.slice(-SUGGESTIONS_CAP)
2939
+ }
2940
+ if (ledgerTaskId) {
2941
+ upsertTaskLedgerOnWs(ws, {
2942
+ id: ledgerTaskId,
2943
+ taskId: ledgerTaskId,
2944
+ kind: 'approval_resume',
2945
+ status: 'awaiting_approval',
2946
+ originalText: `[主对话直传求助 · ${fromLabel}] ${cleanBody}`,
2947
+ pendingApprovalIds: apr ? [apr.id] : [],
2948
+ lastReceipt: '已挂入 L2 待确认审批与参谋建议',
2949
+ })
2950
+ }
2951
+ ws.chat.push({
2952
+ id: nextId('chat'),
2953
+ role: 'chief',
2954
+ kind: 'receipt',
2955
+ text: [
2956
+ `- 【📨 收到主对话直传请求(L2 · 参谋逐项授权)】来自 ${fromLabel}${subject ? ` · ${subject}` : ''}`,
2957
+ `- 【请求摘要】${clamp(cleanBody, 220)}`,
2958
+ `- 【处置结果】已生成待确认动作${apr ? `(#${apr.id})` : ''}并弹出授权提示,您确认后将立刻投递给主对话。`,
2959
+ ].join('\n'),
2960
+ actions: ['主对话直传求助', '🛡️ 待逐项确认'],
2961
+ at: Date.now(),
2962
+ })
2963
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
2964
+ })
2965
+ return {
2966
+ ok: true,
2967
+ mode: 'strategist',
2968
+ actionTaken: 'queued_for_approval',
2969
+ taskId: ledgerTaskId,
2970
+ approval: apr,
2971
+ }
2972
+ }
2973
+
2974
+ // L3 (chief): directly run Chief handling & reply back to @lead via execution_request
2975
+ const execRes = await askOrCommandChief(deps, {
2976
+ sessionId: rootId,
2977
+ text: `[来自 ${fromLabel} 的直接协同请求${subject ? ` · ${subject}` : ''}]\n${cleanBody}`,
2978
+ _fromLeadRequest: true,
2979
+ })
2980
+ const alreadyRelayed = Boolean(execRes && Array.isArray(execRes.relays) && execRes.relays.some(r => r && r.ok))
2981
+ if (!alreadyRelayed && execRes && execRes.reply) {
2982
+ try {
2983
+ await deliverCrossMessage(deps, {
2984
+ fromSession: rootId,
2985
+ fromLabel: 'DSH 参谋长 (L3 协同批复)',
2986
+ target: 'lead',
2987
+ subject: subject || '参谋长协同批复',
2988
+ text: execRes.reply,
2989
+ mode: 'steer',
2990
+ envelopeKind: 'execution_request',
2991
+ taskId: ledgerTaskId,
2992
+ })
2993
+ } catch {}
2994
+ }
2995
+ mutateChiefState((s) => {
2996
+ const ws = ensureWorkspace(s, rootId)
2997
+ if (ledgerTaskId) {
2998
+ upsertTaskLedgerOnWs(ws, {
2999
+ id: ledgerTaskId,
3000
+ taskId: ledgerTaskId,
3001
+ kind: 'tool_execution',
3002
+ status: execRes && execRes.ok === false ? 'failed' : 'completed',
3003
+ originalText: `[主对话直传求助 · ${fromLabel}] ${cleanBody}`,
3004
+ lastReceipt: clamp((execRes && (execRes.reply || execRes.error)) || 'L3 参谋长已完成处置', 220),
3005
+ resolvedAt: Date.now(),
3006
+ })
3007
+ }
3008
+ })
3009
+ return {
3010
+ ok: Boolean(execRes && execRes.ok !== false),
3011
+ mode: 'chief',
3012
+ actionTaken: 'executed_directly',
3013
+ taskId: ledgerTaskId,
3014
+ reply: (execRes && execRes.reply) || '',
3015
+ ...(execRes && execRes.view ? { view: execRes.view } : {}),
3016
+ }
3017
+ }
3018
+
3019
+ registerChiefDirectRequestHook(handleLeadDirectRequestToChief)
3020
+