dsh-chief 1.0.0 → 1.1.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.js CHANGED
@@ -19,12 +19,18 @@ import os from 'node:os'
19
19
  import crypto from 'node:crypto'
20
20
  import {
21
21
  DEFAULT_ARCHIVE_FOLDERS,
22
+ resolveProjectKey,
22
23
  loadArchiveStore,
23
24
  listArchiveHeaders,
24
25
  getArchiveDetail,
25
26
  searchArchives,
26
27
  smartParseNoteToDossier,
28
+ mutateArchive,
27
29
  applyChiefArchiveCurations,
30
+ getFlippedOutPrecipitatedForSession,
31
+ listPrecipitatedHeaders,
32
+ savePrecipitatedEntry,
33
+ mutatePrecipitated,
28
34
  } from './archives.js'
29
35
 
30
36
  const STATE_VERSION = 1
@@ -57,6 +63,144 @@ async function loadDshLlm() {
57
63
  return dshLlmModulePromise
58
64
  }
59
65
 
66
+ let dshAttachmentModulePromise = null
67
+ async function loadDshAttachment() {
68
+ if (!dshAttachmentModulePromise) {
69
+ dshAttachmentModulePromise = import('@deepseek-ai/dsh-attachment').catch(() => null)
70
+ }
71
+ return dshAttachmentModulePromise
72
+ }
73
+
74
+ const CHIEF_MAX_IMAGES = 4
75
+ const CHIEF_IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
76
+
77
+ function normalizeUploadedImage(raw, idx = 0) {
78
+ if (!raw || typeof raw !== 'object') return null
79
+ let mediaType = String(raw.mediaType || raw.mimeType || raw.type || '').trim().toLowerCase()
80
+ let data = String(raw.data || raw.base64 || '').trim()
81
+ const dataUrlMatch = data.match(/^data:([^;]+);base64,(.+)$/is)
82
+ if (dataUrlMatch) {
83
+ if (!mediaType) mediaType = dataUrlMatch[1].trim().toLowerCase()
84
+ data = dataUrlMatch[2].trim()
85
+ }
86
+ if (mediaType === 'image/jpg') mediaType = 'image/jpeg'
87
+ data = data.replace(/\s+/g, '')
88
+ if (!CHIEF_IMAGE_MEDIA_TYPES.has(mediaType) || !data) return null
89
+ const ext = mediaType === 'image/jpeg' ? 'jpg' : (mediaType.split('/')[1] || 'png')
90
+ const name = typeof raw.name === 'string' && raw.name.trim()
91
+ ? clamp(raw.name.trim(), 80)
92
+ : `chief-image-${idx + 1}.${ext}`
93
+ return { name, mediaType, data }
94
+ }
95
+
96
+ function resolveSessionWorkspaceCwd(deps, sessionId) {
97
+ const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || sessionId
98
+ try {
99
+ if (deps && typeof deps.getSessionCwd === 'function') {
100
+ const c = deps.getSessionCwd(rootId) || deps.getSessionCwd(sessionId)
101
+ if (c && fs.existsSync(c)) return c
102
+ }
103
+ if (deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function') {
104
+ const b = deps.boardForSession(deps.boardFileFor(rootId))
105
+ const sess = b && b.sessions && (b.sessions[rootId] || b.sessions[sessionId])
106
+ if (sess && sess.cwd && fs.existsSync(sess.cwd)) return sess.cwd
107
+ }
108
+ } catch {}
109
+ return process.cwd()
110
+ }
111
+
112
+ function archiveTargetForRoot(deps, rootId, cabinetId = '') {
113
+ const sharedFile = deps && (typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile)
114
+ const cwd = resolveSessionWorkspaceCwd(deps, rootId)
115
+ return {
116
+ customSharedBoardFile: sharedFile || '',
117
+ cwd,
118
+ ...(cabinetId ? { cabinetId: String(cabinetId).trim() } : {}),
119
+ }
120
+ }
121
+
122
+ /** Persist raw uploaded images onto local workspace `.dsh-chief/uploads/` so any agent can inspect raw files even when LLM vision is unavailable. */
123
+ export function persistChiefImagesToWorkspace(deps, sessionId, rawImages) {
124
+ const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
125
+ if (!list.length) return []
126
+ const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
127
+ if (!normalized.length) return []
128
+
129
+ const cwd = resolveSessionWorkspaceCwd(deps, sessionId)
130
+ const uploadDir = path.join(cwd, '.dsh-chief', 'uploads')
131
+ fs.mkdirSync(uploadDir, { recursive: true })
132
+
133
+ const d = new Date()
134
+ const stamp = [
135
+ d.getFullYear(),
136
+ String(d.getMonth() + 1).padStart(2, '0'),
137
+ String(d.getDate()).padStart(2, '0'),
138
+ ].join('') + '-' + [
139
+ String(d.getHours()).padStart(2, '0'),
140
+ String(d.getMinutes()).padStart(2, '0'),
141
+ String(d.getSeconds()).padStart(2, '0'),
142
+ ].join('')
143
+
144
+ const saved = []
145
+ for (let idx = 0; idx < normalized.length; idx += 1) {
146
+ const img = normalized[idx]
147
+ const ext = img.mediaType === 'image/jpeg' ? 'jpg' : (img.mediaType.split('/')[1] || 'png')
148
+ const baseRaw = path.basename(String(img.name || `image-${idx + 1}`), path.extname(String(img.name || '')))
149
+ const safeName = baseRaw.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || `image-${idx + 1}`
150
+ const fileName = `${stamp}-${idx + 1}-${safeName}.${ext}`
151
+ const absPath = path.join(uploadDir, fileName)
152
+ const buf = Buffer.from(img.data, 'base64')
153
+ fs.writeFileSync(absPath, buf)
154
+ saved.push({
155
+ index: idx + 1,
156
+ path: absPath,
157
+ name: img.name || fileName,
158
+ mediaType: img.mediaType,
159
+ bytes: buf.length,
160
+ })
161
+ }
162
+ return saved
163
+ }
164
+
165
+ export async function admitChiefImages(deps, rawImages) {
166
+ const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
167
+ if (!list.length) return []
168
+ const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
169
+ if (!normalized.length) {
170
+ throw new Error('上传的图片格式不受支持(仅支持 PNG / JPEG / WebP / GIF Base64)')
171
+ }
172
+
173
+ if (deps && typeof deps.admitImagesOverride === 'function') {
174
+ const refs = await deps.admitImagesOverride(normalized)
175
+ return (Array.isArray(refs) ? refs : []).filter(Boolean).map(attachment => ({ type: 'image', attachment }))
176
+ }
177
+
178
+ const attachmentsSvc = deps && typeof deps.getAttachments === 'function'
179
+ ? deps.getAttachments()
180
+ : (deps && deps.runtime && typeof deps.runtime.get === 'function' ? deps.runtime.get('attachments') : null)
181
+ if (!attachmentsSvc) {
182
+ throw new Error('当前 DSH 运行环境未挂载 attachments 图片服务,无法处理图片上传')
183
+ }
184
+
185
+ const attMod = await loadDshAttachment()
186
+ if (attMod && typeof attMod.admitEncodedImages === 'function') {
187
+ const refs = await attMod.admitEncodedImages(attachmentsSvc, normalized)
188
+ return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
189
+ }
190
+
191
+ if (typeof attachmentsSvc.saveImages === 'function') {
192
+ const payload = normalized.map(img => ({
193
+ data: Uint8Array.from(Buffer.from(img.data, 'base64')),
194
+ mediaType: img.mediaType,
195
+ name: img.name,
196
+ }))
197
+ const refs = await attachmentsSvc.saveImages(payload)
198
+ return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
199
+ }
200
+
201
+ throw new Error('attachments 服务缺少 saveImages / admitEncodedImages 接口')
202
+ }
203
+
60
204
  let idSeq = 0
61
205
  function nextId(prefix) {
62
206
  idSeq = (idSeq + 1) % 1000000
@@ -90,6 +234,7 @@ function stateFilePath() {
90
234
 
91
235
  function emptyWorkspace() {
92
236
  return {
237
+ config: null,
93
238
  facts: [],
94
239
  narrative: { hash: '', text: '', at: 0, byModel: '' },
95
240
  suggestions: [],
@@ -98,6 +243,17 @@ function emptyWorkspace() {
98
243
  seenMailAt: {},
99
244
  seenFactsAt: {},
100
245
  reviewCursors: {},
246
+ runtimeGuard: {
247
+ lastCompactedSeq: 0,
248
+ lastCompactedAt: 0,
249
+ interventionTurns: 0,
250
+ lastDigestHash: '',
251
+ unchangedCount: 0,
252
+ cooldownUntil: 0,
253
+ circuitBroken: false,
254
+ circuitReason: '',
255
+ },
256
+ flippedPrecipitatedIds: [],
101
257
  }
102
258
  }
103
259
 
@@ -123,7 +279,7 @@ function normalizeSuggestion(raw) {
123
279
  if (!raw || typeof raw !== 'object') return null
124
280
  const title = clamp(raw.title, 90)
125
281
  if (!title) return null
126
- const kind = raw.kind === 'bound' ? 'bound' : raw.kind === 'board' ? 'board' : 'relay'
282
+ const kind = ['bound', 'board', 'goal_approval', 'relay'].includes(raw.kind) ? raw.kind : 'relay'
127
283
  const boundField = ['forbidden', 'allowed', 'notes'].includes(raw.boundField) ? raw.boundField : 'forbidden'
128
284
  const replaces = Array.isArray(raw.replaces)
129
285
  ? raw.replaces.map(x => String(x || '').trim()).filter(Boolean).slice(0, 20)
@@ -137,10 +293,12 @@ function normalizeSuggestion(raw) {
137
293
  fromAgent: clamp(raw.fromAgent || '', 48),
138
294
  title,
139
295
  reason: clamp(raw.reason || '', 220),
140
- target: clamp(raw.target || (kind === 'bound' ? 'bounds' : 'lead'), 64),
141
- targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : '主对话'), 40),
296
+ target: clamp(raw.target || (kind === 'bound' ? 'bounds' : kind === 'goal_approval' ? 'board' : 'lead'), 64),
297
+ targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : kind === 'goal_approval' ? '目标结项批示' : '主对话'), 40),
142
298
  mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : 'steer',
143
299
  draftText: cleanMultiline(raw.draftText || '', 600),
300
+ evidence: cleanMultiline(raw.evidence || '', 600),
301
+ missing: clamp(raw.missing || '', 300),
144
302
  boardOp: raw.boardOp && typeof raw.boardOp === 'object' ? raw.boardOp : null,
145
303
  status: ['pending', 'applied', 'dismissed'].includes(raw.status) ? raw.status : 'pending',
146
304
  createdAt: Number(raw.createdAt) || Date.now(),
@@ -149,7 +307,8 @@ function normalizeSuggestion(raw) {
149
307
 
150
308
  function normalizeMail(raw) {
151
309
  if (!raw || typeof raw !== 'object') return null
152
- const text = cleanMultiline(raw.text, 1500)
310
+ const imageCount = Math.max(0, Math.round(Number(raw.imageCount) || 0))
311
+ const text = cleanMultiline(raw.text, 1500) || (imageCount > 0 ? `[附图 ×${imageCount}]` : '')
153
312
  if (!text) return null
154
313
  return {
155
314
  id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('mail'),
@@ -159,6 +318,7 @@ function normalizeMail(raw) {
159
318
  toSession: String(raw.toSession || ''),
160
319
  subject: clamp(raw.subject || '', 80),
161
320
  text,
321
+ ...(imageCount > 0 ? { imageCount } : {}),
162
322
  mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : 'steer',
163
323
  deliveredPhysical: Boolean(raw.deliveredPhysical),
164
324
  readBy: Array.isArray(raw.readBy) ? raw.readBy.map(String).slice(0, 32) : [],
@@ -185,21 +345,102 @@ function normalizeWorkspace(raw) {
185
345
  base.chat = (Array.isArray(src.chat) ? src.chat : [])
186
346
  .filter(item => item && typeof item === 'object' && typeof item.text === 'string')
187
347
  .slice(-CHAT_CAP)
188
- .map(item => ({
189
- id: String(item.id || nextId('chat')),
190
- role: item.role === 'user' ? 'user' : 'chief',
191
- text: cleanMultiline(item.text, 2000),
192
- target: item.target ? String(item.target) : '',
193
- actions: Array.isArray(item.actions) ? item.actions.slice(0, 8) : [],
194
- at: Number(item.at) || Date.now(),
195
- }))
348
+ .map(item => {
349
+ const imageCount = Math.max(0, Math.round(Number(item.imageCount) || 0))
350
+ return {
351
+ id: String(item.id || nextId('chat')),
352
+ role: item.role === 'user' ? 'user' : 'chief',
353
+ text: cleanMultiline(item.text, 2000),
354
+ target: item.target ? String(item.target) : '',
355
+ ...(imageCount > 0 ? { imageCount } : {}),
356
+ actions: Array.isArray(item.actions) ? item.actions.slice(0, 8) : [],
357
+ at: Number(item.at) || Date.now(),
358
+ }
359
+ })
196
360
  base.mailbox = (Array.isArray(src.mailbox) ? src.mailbox : []).map(normalizeMail).filter(Boolean).slice(-MAIL_CAP)
197
361
  base.seenMailAt = src.seenMailAt && typeof src.seenMailAt === 'object' ? { ...src.seenMailAt } : {}
198
362
  base.seenFactsAt = src.seenFactsAt && typeof src.seenFactsAt === 'object' ? { ...src.seenFactsAt } : {}
199
363
  base.reviewCursors = src.reviewCursors && typeof src.reviewCursors === 'object' ? { ...src.reviewCursors } : {}
364
+ const rg = src.runtimeGuard && typeof src.runtimeGuard === 'object' ? src.runtimeGuard : {}
365
+ base.runtimeGuard = {
366
+ lastCompactedSeq: Math.max(0, Math.round(Number(rg.lastCompactedSeq) || 0)),
367
+ lastCompactedAt: Math.max(0, Number(rg.lastCompactedAt) || 0),
368
+ interventionTurns: Math.max(0, Math.round(Number(rg.interventionTurns) || 0)),
369
+ lastDigestHash: String(rg.lastDigestHash || ''),
370
+ unchangedCount: Math.max(0, Math.round(Number(rg.unchangedCount) || 0)),
371
+ cooldownUntil: Math.max(0, Number(rg.cooldownUntil) || 0),
372
+ circuitBroken: Boolean(rg.circuitBroken),
373
+ circuitReason: String(rg.circuitReason || ''),
374
+ }
375
+ if (src.config && typeof src.config === 'object') {
376
+ const validPaces = ['manual', 'smart', 'auto']
377
+ const pm = validPaces.includes(src.config.paceMode) ? src.config.paceMode : undefined
378
+ base.config = {
379
+ ...(typeof src.config.modelRef === 'string' ? { modelRef: src.config.modelRef.trim() } : {}),
380
+ ...(pm ? { paceMode: pm, autoPilot: pm === 'auto', autoReview: pm !== 'manual' } : {}),
381
+ ...(src.config.tacticalModes && typeof src.config.tacticalModes === 'object'
382
+ ? { tacticalModes: normalizeTacticalModes(src.config.tacticalModes) }
383
+ : {}),
384
+ }
385
+ }
386
+ base.flippedPrecipitatedIds = Array.isArray(src.flippedPrecipitatedIds)
387
+ ? [...new Set(src.flippedPrecipitatedIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 20)
388
+ : []
200
389
  return base
201
390
  }
202
391
 
392
+ /** Resolve effective Chief config for a specific root session (isolates `intervention` per session). */
393
+ export function resolveWorkspaceConfig(state, sessionId = '') {
394
+ const safeState = state && typeof state === 'object' ? state : {}
395
+ const base = safeState.config && typeof safeState.config === 'object' ? safeState.config : {}
396
+ const baseTactical = normalizeTacticalModes(base.tacticalModes)
397
+ const sid = String(sessionId || '').trim()
398
+ const ws = sid && safeState.workspaces && safeState.workspaces[sid] ? safeState.workspaces[sid] : null
399
+ const wsCfg = ws && ws.config && typeof ws.config === 'object' ? ws.config : null
400
+ const validPaces = ['manual', 'smart', 'auto']
401
+ const paceMode = wsCfg && validPaces.includes(wsCfg.paceMode)
402
+ ? wsCfg.paceMode
403
+ : (validPaces.includes(base.paceMode) ? base.paceMode : 'manual')
404
+ const modelRef = wsCfg && typeof wsCfg.modelRef === 'string'
405
+ ? wsCfg.modelRef.trim()
406
+ : (typeof base.modelRef === 'string' ? base.modelRef.trim() : '')
407
+ const mergedTactical = wsCfg && wsCfg.tacticalModes
408
+ ? normalizeTacticalModes({ ...baseTactical, ...wsCfg.tacticalModes })
409
+ : { ...baseTactical, ...(sid ? { intervention: false } : {}) }
410
+ return {
411
+ modelRef,
412
+ paceMode,
413
+ autoPilot: paceMode === 'auto',
414
+ autoReview: paceMode !== 'manual',
415
+ tacticalModes: mergedTactical,
416
+ }
417
+ }
418
+
419
+ const DEFAULT_TACTICAL_MODES = {
420
+ intervention: false,
421
+ autoCompact: false,
422
+ compactThresholdPct: 80,
423
+ strictVerify: false,
424
+ redlineSentinel: false,
425
+ conciseBrief: false,
426
+ maxInterventionTurns: 10,
427
+ }
428
+
429
+ function normalizeTacticalModes(raw) {
430
+ const src = raw && typeof raw === 'object' ? raw : {}
431
+ const pct = Math.round(Number(src.compactThresholdPct) || DEFAULT_TACTICAL_MODES.compactThresholdPct)
432
+ const maxTurns = Math.round(Number(src.maxInterventionTurns) || DEFAULT_TACTICAL_MODES.maxInterventionTurns)
433
+ return {
434
+ intervention: Boolean(src.intervention),
435
+ autoCompact: Boolean(src.autoCompact),
436
+ compactThresholdPct: Math.min(95, Math.max(50, pct)),
437
+ strictVerify: Boolean(src.strictVerify),
438
+ redlineSentinel: Boolean(src.redlineSentinel),
439
+ conciseBrief: Boolean(src.conciseBrief),
440
+ maxInterventionTurns: Math.min(30, Math.max(1, maxTurns)),
441
+ }
442
+ }
443
+
203
444
  function normalizeState(raw) {
204
445
  const src = raw && typeof raw === 'object' ? raw : {}
205
446
  const cfg = src.config && typeof src.config === 'object' ? src.config : {}
@@ -228,6 +469,7 @@ function normalizeState(raw) {
228
469
  paceMode,
229
470
  autoPilot: paceMode === 'auto',
230
471
  autoReview: paceMode !== 'manual',
472
+ tacticalModes: normalizeTacticalModes(cfg.tacticalModes),
231
473
  },
232
474
  links,
233
475
  workspaces,
@@ -530,7 +772,9 @@ export async function listChiefModels(deps, fresh = false, sessionId = '') {
530
772
  const llm = deps.getLlm ? deps.getLlm() : null
531
773
  const runtime = deps.runtime
532
774
  const state = loadChiefState()
533
- let selectedRef = state.config.modelRef || ''
775
+ const rootSid = (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sessionId) : '') || String(sessionId || '').trim()
776
+ const effCfg = resolveWorkspaceConfig(state, rootSid)
777
+ let selectedRef = effCfg.modelRef || ''
534
778
 
535
779
  const leadRef = sessionModelRef(deps, sessionId)
536
780
  const profileDefaultRef = profileDefaultModelRef(runtime)
@@ -741,7 +985,7 @@ function pickRouteFromItems(items, selectedRef, followRef, deps, sessionId, regi
741
985
  return queue[0] || null
742
986
  }
743
987
 
744
- async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MAX_TOKENS, sessionId = '') {
988
+ async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MAX_TOKENS, sessionId = '', imageBlocks = []) {
745
989
  let effort
746
990
  let modelDefaultMaxTokens
747
991
  try {
@@ -761,15 +1005,17 @@ async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MA
761
1005
  const firstBudget = modelDefaultMaxTokens ? Math.min(modelDefaultMaxTokens, targetBudget) : targetBudget
762
1006
  const retryBudget = firstBudget < targetBudget ? targetBudget : SUMMARY_RETRY_MAX_TOKENS
763
1007
  const budgets = retryBudget > firstBudget ? [firstBudget, retryBudget] : [firstBudget]
1008
+ const safeImages = Array.isArray(imageBlocks) ? imageBlocks : []
764
1009
 
765
1010
  const runOnce = async (budget) => {
1011
+ const userContent = [...safeImages, { type: 'text', text: userText || '请查看附图并回答。' }]
766
1012
  const request = {
767
1013
  provider: route.provider,
768
1014
  model: route.model,
769
1015
  ...(sessionId ? { sessionId } : {}),
770
1016
  ...(effort !== undefined ? { reasoningEffort: effort } : {}),
771
1017
  system,
772
- messages: [{ role: 'user', content: [{ type: 'text', text: userText }] }],
1018
+ messages: [{ role: 'user', content: userContent }],
773
1019
  maxTokens: budget,
774
1020
  signal: AbortSignal.timeout(MODEL_TIMEOUT_MS),
775
1021
  }
@@ -828,9 +1074,39 @@ async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MA
828
1074
  return { text: lastRes.text, modelRef: lastRes.modelRef }
829
1075
  }
830
1076
 
831
- export async function callChiefLlm(deps, { sessionId = '', system, prompt, maxTokens = SUMMARY_MAX_TOKENS }) {
1077
+ async function filterVisionRoutes(llm, queue) {
1078
+ const visionRoutes = []
1079
+ const unknownRoutes = []
1080
+ for (const route of queue) {
1081
+ let info = null
1082
+ try {
1083
+ if (typeof llm.resolveModelInfo === 'function') {
1084
+ info = await Promise.resolve(llm.resolveModelInfo(route.provider, route.model))
1085
+ }
1086
+ } catch {}
1087
+ const mods = Array.isArray(info?.inputModalities)
1088
+ ? info.inputModalities
1089
+ : (Array.isArray(route.inputModalities) ? route.inputModalities : null)
1090
+ if (mods) {
1091
+ if (mods.includes('image')) visionRoutes.push(route)
1092
+ } else {
1093
+ unknownRoutes.push(route)
1094
+ }
1095
+ }
1096
+ return [...visionRoutes, ...unknownRoutes]
1097
+ }
1098
+
1099
+ export async function callChiefLlm(deps, {
1100
+ sessionId = '',
1101
+ system,
1102
+ prompt,
1103
+ maxTokens = SUMMARY_MAX_TOKENS,
1104
+ imageBlocks = [],
1105
+ allowTextFallbackOnVisionMiss = false,
1106
+ }) {
1107
+ const safeImages = Array.isArray(imageBlocks) ? imageBlocks : []
832
1108
  if (deps && typeof deps.callLlmOverride === 'function') {
833
- return deps.callLlmOverride({ sessionId, system, prompt, maxTokens })
1109
+ return deps.callLlmOverride({ sessionId, system, prompt, maxTokens, imageBlocks: safeImages, allowTextFallbackOnVisionMiss })
834
1110
  }
835
1111
  const llm = deps.getLlm ? deps.getLlm() : null
836
1112
  if (!llm || typeof llm.stream !== 'function') {
@@ -840,33 +1116,60 @@ export async function callChiefLlm(deps, { sessionId = '', system, prompt, maxTo
840
1116
  const regSet = typeof llm.listProviders === 'function'
841
1117
  ? new Set((llm.listProviders() || []).filter(p => p && p.id && !String(p.id).startsWith('local-agent')).map(p => String(p.id)))
842
1118
  : null
843
- const queue = buildRouteQueue(catalog.models, catalog.selectedRef, catalog.followRef || catalog.defaultRef, deps, sessionId, regSet)
844
- if (!queue.length) {
1119
+ const baseQueue = buildRouteQueue(catalog.models, catalog.selectedRef, catalog.followRef || catalog.defaultRef, deps, sessionId, regSet)
1120
+ if (!baseQueue.length) {
845
1121
  return { ok: false, error: '未找到可用的参谋长模型,请在 DSH 设置中配置模型供应商' }
846
1122
  }
847
1123
 
1124
+ let queue = baseQueue
1125
+ let sendImages = safeImages
1126
+ let degradedToTextOnly = false
1127
+ if (safeImages.length > 0) {
1128
+ const visionQueue = await filterVisionRoutes(llm, baseQueue)
1129
+ if (visionQueue.length > 0) {
1130
+ queue = visionQueue
1131
+ } else if (allowTextFallbackOnVisionMiss) {
1132
+ queue = baseQueue
1133
+ sendImages = []
1134
+ degradedToTextOnly = true
1135
+ } else {
1136
+ return {
1137
+ ok: false,
1138
+ error: '当前参谋长及备选模型均不支持图片输入(仅纯文本),请在右上角切换支持视觉的多模态模型(如 Gemini / Claude / GPT-4o / Qwen-VL 等)后再试。',
1139
+ }
1140
+ }
1141
+ }
1142
+
848
1143
  let lastError = '模型返回内容为空'
849
1144
  for (const route of queue.slice(0, 4)) {
850
1145
  try {
851
- const res = await callOneRoute(llm, route, system, prompt, maxTokens, sessionId)
852
- if (res.text) return { ok: true, text: res.text, modelRef: res.modelRef }
1146
+ const res = await callOneRoute(llm, route, system, prompt, maxTokens, sessionId, sendImages)
1147
+ if (res.text) return { ok: true, text: res.text, modelRef: res.modelRef, degradedToTextOnly }
853
1148
  lastError = `${route.ref} 返回内容为空`
854
1149
  markRouteFailure(route, new Error(lastError))
855
1150
  } catch (err) {
856
1151
  lastError = String(err && err.message ? err.message : err)
1152
+ if (sendImages.length > 0 && allowTextFallbackOnVisionMiss) {
1153
+ try {
1154
+ const textRes = await callOneRoute(llm, route, system, prompt, maxTokens, sessionId, [])
1155
+ if (textRes.text) return { ok: true, text: textRes.text, modelRef: textRes.modelRef, degradedToTextOnly: true }
1156
+ } catch {}
1157
+ }
857
1158
  markRouteFailure(route, err)
858
1159
  }
859
1160
  }
860
- return { ok: false, error: lastError }
1161
+ return { ok: false, error: lastError, degradedToTextOnly }
861
1162
  }
862
1163
 
863
1164
  /* -------------------------------------------------------------------------- */
864
1165
  /* Peer Discovery & Cross-Conversation Delivery ("递话 / 插话") */
865
1166
  /* -------------------------------------------------------------------------- */
866
1167
 
867
- export async function buildMessageEnvelope(text, sourceKind = CHIEF_RELAY_SOURCE, extraSource = {}) {
1168
+ export async function buildMessageEnvelope(text, sourceKind = CHIEF_RELAY_SOURCE, extraSource = {}, imageBlocks = []) {
868
1169
  const dshLlm = await loadDshLlm()
869
- const content = [{ type: 'text', text }]
1170
+ const safeImages = Array.isArray(imageBlocks) ? imageBlocks : []
1171
+ const content = [...safeImages, ...(text ? [{ type: 'text', text }] : [])]
1172
+ if (!content.length) content.push({ type: 'text', text: '' })
870
1173
  const source = { kind: sourceKind, ...extraSource }
871
1174
  if (dshLlm && typeof dshLlm.createUserMessage === 'function') {
872
1175
  try {
@@ -992,6 +1295,17 @@ function matchTargetPeer(targets, rawTarget) {
992
1295
  * - 'followup': queue for next turn / wake idle session without cutting running step.
993
1296
  * - 'silent': record in chief mailbox so the recipient sees it cleanly at its next pre-step without waking an idle session.
994
1297
  */
1298
+ function buildSavedImageNotice(savedImagePaths) {
1299
+ const list = Array.isArray(savedImagePaths) ? savedImagePaths.filter(item => item && item.path) : []
1300
+ if (!list.length) return ''
1301
+ return [
1302
+ '',
1303
+ '🖼️ [用户原图已落盘至工作区路径]:',
1304
+ ...list.map(item => `- ${item.path}${item.name ? ` (${item.name})` : ''}`),
1305
+ '⚠️ 请直接查阅附带图片或使用读图/文件工具读取上述原始路径后再动手,严禁只凭参谋长转述文本猜测或编造未确认的图内信息!',
1306
+ ].join('\n')
1307
+ }
1308
+
995
1309
  export async function deliverCrossMessage(deps, {
996
1310
  fromSession = '',
997
1311
  fromLabel = 'DSH 参谋长',
@@ -999,10 +1313,40 @@ export async function deliverCrossMessage(deps, {
999
1313
  text = '',
1000
1314
  subject = '',
1001
1315
  mode = 'steer',
1316
+ images = [],
1317
+ imageBlocks: preAdmittedBlocks = null,
1318
+ savedImagePaths: preSavedPaths = null,
1002
1319
  recordBoardLog = true,
1003
1320
  }) {
1004
1321
  const cleanBody = cleanMultiline(text, 2400)
1005
- if (!cleanBody) return { ok: false, error: '递话内容不能为空' }
1322
+ const rawImages = Array.isArray(images) ? images : []
1323
+ const hasPreAdmitted = Array.isArray(preAdmittedBlocks) && preAdmittedBlocks.length > 0
1324
+ let savedPaths = Array.isArray(preSavedPaths) ? preSavedPaths : []
1325
+ if (!savedPaths.length && rawImages.length > 0) {
1326
+ try {
1327
+ savedPaths = persistChiefImagesToWorkspace(deps, fromSession, rawImages)
1328
+ } catch {}
1329
+ }
1330
+
1331
+ if (!cleanBody && !rawImages.length && !hasPreAdmitted && !savedPaths.length) {
1332
+ return { ok: false, error: '递话内容不能为空' }
1333
+ }
1334
+
1335
+ let admittedBlocks = hasPreAdmitted ? preAdmittedBlocks : []
1336
+ if (!hasPreAdmitted && rawImages.length > 0) {
1337
+ try {
1338
+ admittedBlocks = await admitChiefImages(deps, rawImages)
1339
+ } catch (err) {
1340
+ if (!savedPaths.length) {
1341
+ return { ok: false, error: String(err && err.message ? err.message : err) }
1342
+ }
1343
+ // Degrade cleanly to path-based image delivery if host attachments service is unavailable
1344
+ admittedBlocks = []
1345
+ }
1346
+ }
1347
+ const effectiveText = cleanBody || (admittedBlocks.length || savedPaths.length ? '请查看随信附带的图片与落盘路径。' : '')
1348
+ const totalImgCount = Math.max(admittedBlocks.length, savedPaths.length)
1349
+ const imgTag = totalImgCount > 0 ? ` [附图 ×${totalImgCount}]` : ''
1006
1350
 
1007
1351
  const rootId = deps.resolveRootSessionId(fromSession) || String(fromSession || '')
1008
1352
  const directory = await listPeerDirectory(deps, rootId || fromSession)
@@ -1016,17 +1360,19 @@ export async function deliverCrossMessage(deps, {
1016
1360
  const res = await deliverSinglePeer(deps, directory, peer, {
1017
1361
  fromSession,
1018
1362
  fromLabel,
1019
- text: cleanBody,
1363
+ text: effectiveText,
1020
1364
  subject,
1021
1365
  mode,
1366
+ imageBlocks: admittedBlocks,
1367
+ savedImagePaths: savedPaths,
1022
1368
  recordBoardLog: false,
1023
1369
  })
1024
1370
  deliveries.push({ target: peer.handle, ok: res.ok, mode: res.deliveryMode })
1025
1371
  }
1026
1372
  if (recordBoardLog && rootId) {
1027
- deps.appendBoardLog(rootId, `📡 ${fromLabel} 向全体成员广播递话(${deliveries.filter(d => d.ok).length} 个目标):${clamp(cleanBody, 56)}`, fromLabel)
1373
+ deps.appendBoardLog(rootId, `📡 ${fromLabel} 向全体成员广播递话(${deliveries.filter(d => d.ok).length} 个目标):${clamp(effectiveText, 56)}${imgTag}`, fromLabel)
1028
1374
  }
1029
- return { ok: true, broadcast: true, deliveries }
1375
+ return { ok: true, broadcast: true, deliveries, savedImagePaths: savedPaths }
1030
1376
  }
1031
1377
 
1032
1378
  const peer = matchTargetPeer(directory.targets, rawTarget)
@@ -1040,21 +1386,38 @@ export async function deliverCrossMessage(deps, {
1040
1386
  return deliverSinglePeer(deps, directory, peer, {
1041
1387
  fromSession,
1042
1388
  fromLabel,
1043
- text: cleanBody,
1389
+ text: effectiveText,
1044
1390
  subject,
1045
1391
  mode,
1392
+ imageBlocks: admittedBlocks,
1393
+ savedImagePaths: savedPaths,
1046
1394
  recordBoardLog,
1047
1395
  })
1048
1396
  }
1049
1397
 
1050
- async function deliverSinglePeer(deps, directory, peer, { fromSession, fromLabel, text, subject, mode, recordBoardLog }) {
1398
+ async function deliverSinglePeer(deps, directory, peer, {
1399
+ fromSession,
1400
+ fromLabel,
1401
+ text,
1402
+ subject,
1403
+ mode,
1404
+ imageBlocks = [],
1405
+ savedImagePaths = [],
1406
+ recordBoardLog,
1407
+ }) {
1051
1408
  const runtime = deps.runtime
1052
1409
  const agentsSvc = runtime ? runtime.get('agents') : null
1053
1410
  const subagentsSvc = runtime ? runtime.get('subagents') : null
1411
+ const safeBlocks = Array.isArray(imageBlocks) ? imageBlocks : []
1412
+ const safePaths = Array.isArray(savedImagePaths) ? savedImagePaths : []
1413
+ const imgCount = Math.max(safeBlocks.length, safePaths.length)
1414
+ const imgSuffix = imgCount > 0 ? ` [附图 ×${imgCount}]` : ''
1415
+ const imgNoticeBlock = buildSavedImageNotice(safePaths)
1416
+ const textWithImagePaths = imgNoticeBlock ? `${text}\n${imgNoticeBlock}` : text
1054
1417
  const headerTag = mode === 'steer'
1055
1418
  ? `[DSH 参谋长插话 · 来自 ${fromLabel}]`
1056
1419
  : `[DSH 参谋长递话 · 来自 ${fromLabel}]`
1057
- const formatted = `${headerTag}${subject ? ' ' + subject : ''}\n${text}\n\n(如需回信或同步进展,可调用参谋看板 chief_board({ action: "mail.send", target: "${fromLabel === 'DSH 参谋长' ? 'lead' : fromLabel}", text: "…" }))`
1420
+ const formatted = `${headerTag}${subject ? ' ' + subject : ''}\n${textWithImagePaths}\n\n(如需回信或同步进展,可调用参谋看板 chief_board({ action: "mail.send", target: "${fromLabel === 'DSH 参谋长' ? 'lead' : fromLabel}", text: "…" }))`
1058
1421
 
1059
1422
  let deliveredPhysical = false
1060
1423
  let deliveryMode = 'mailbox-queued'
@@ -1071,7 +1434,7 @@ async function deliverSinglePeer(deps, directory, peer, { fromSession, fromLabel
1071
1434
  targetChildId = await subagentsSvc.resolveName(caller, peer.name, AbortSignal.timeout(5000))
1072
1435
  }
1073
1436
  if (targetChildId) {
1074
- await subagentsSvc.sendMessage(caller, targetChildId, [{ type: 'text', text: formatted }], {
1437
+ await subagentsSvc.sendMessage(caller, targetChildId, [...safeBlocks, { type: 'text', text: formatted }], {
1075
1438
  signal: AbortSignal.timeout(10_000),
1076
1439
  })
1077
1440
  deliveredPhysical = true
@@ -1100,7 +1463,7 @@ async function deliverSinglePeer(deps, directory, peer, { fromSession, fromLabel
1100
1463
  senderName: fromLabel,
1101
1464
  senderSessionId: fromSession || undefined,
1102
1465
  role: mode === 'steer' ? 'steer' : 'relay',
1103
- })
1466
+ }, safeBlocks)
1104
1467
  try {
1105
1468
  if (mode === 'steer' && targetAgent.status === 'running' && typeof targetAgent.steer === 'function') {
1106
1469
  const r = targetAgent.steer(envelope)
@@ -1118,7 +1481,7 @@ async function deliverSinglePeer(deps, directory, peer, { fromSession, fromLabel
1118
1481
  deliveredPhysical = true
1119
1482
  deliveryMode = 'agent-inject'
1120
1483
  } else if (typeof targetAgent.steer === 'function') {
1121
- targetAgent.steer(formatted)
1484
+ targetAgent.steer(safeBlocks.length ? formatted + imgSuffix : formatted)
1122
1485
  deliveredPhysical = true
1123
1486
  deliveryMode = 'agent-steer-text'
1124
1487
  }
@@ -1142,7 +1505,8 @@ async function deliverSinglePeer(deps, directory, peer, { fromSession, fromLabel
1142
1505
  to: peer.handle,
1143
1506
  toSession: peer.id || peer.key,
1144
1507
  subject,
1145
- text,
1508
+ text: imgCount > 0 ? `${textWithImagePaths}${imgSuffix}` : textWithImagePaths,
1509
+ imageCount: imgCount,
1146
1510
  mode,
1147
1511
  deliveredPhysical,
1148
1512
  readBy: recipientMarks,
@@ -1159,7 +1523,7 @@ async function deliverSinglePeer(deps, directory, peer, { fromSession, fromLabel
1159
1523
  const badge = mode === 'steer' ? '⚡ 插话' : mode === 'silent' ? '📌 备忘纸条' : '📨 递话'
1160
1524
  deps.appendBoardLog(
1161
1525
  peer.rootId || directory.rootId,
1162
- `${badge} ${fromLabel} → ${peer.handle}:${clamp(text, 56)}`,
1526
+ `${badge} ${fromLabel} → ${peer.handle}:${clamp(text, 56)}${imgSuffix}`,
1163
1527
  fromLabel,
1164
1528
  )
1165
1529
  }
@@ -1171,6 +1535,7 @@ async function deliverSinglePeer(deps, directory, peer, { fromSession, fromLabel
1171
1535
  targetId: peer.id,
1172
1536
  deliveredPhysical,
1173
1537
  deliveryMode,
1538
+ savedImagePaths: safePaths,
1174
1539
  ...(errorNote && !deliveredPhysical ? { note: '目标暂未在线运行,已存入参谋部协同信箱,将在其下一步自动送达(' + errorNote + ')' } : {}),
1175
1540
  }
1176
1541
  }
@@ -1261,8 +1626,8 @@ const NARRATIVE_SYSTEM = [
1261
1626
  '你是「DSH 参谋长」(如同统揽全局的宰相),负责把当前工作区和协同团队的目标、进展、纪律与红线边界,提炼成用户一眼扫完就能掌握全局的「摘要」。',
1262
1627
  '严格遵守以下【简明结构化 · 分点作答】规范:',
1263
1628
  '1. 使用简体中文,语气精炼干脆、直击要害,严禁寒暄套话与冗长铺垫。',
1264
- '2. 全文分为 2 到 4 个模块,每个模块以一行 `## 模块短标题` 开头(如 `## 核心目标与态势`、`## 关键结论与进展`、`## 协作纪律与边界`)。',
1265
- '3. **每个模块下方必须全部使用 `- ` 分点列表作答(严禁写成挤在一起的长段落散文!)**。每一点控制在 1 行(最多不超过 2 行),推荐在要点开头用方括号短标签提亮,如 `- 【推进中】…`、`- 【受阻】…`、`- 【结论】…`、`- 【禁止红线】…`、`- 【允许范围】…`。',
1629
+ '2. 全文分为 2 到 4 个模块,每个模块以一行 `## 模块短标题` 开头(如 `## 核心目标与态势`、`## 关键结论与进展`、`## 协作纪律与红线`、`## 协作纪律与边界`)。',
1630
+ '3. **每个模块下方必须全部使用 `- ` 分点列表作答(严禁写成挤在一起的长段落散文!)**。每一点控制在 1 行(最多不超过 2 行),推荐在要点开头用方括号短标签提亮,如 `- 【总目标】…`、`- 【推进中】…`、`- 【已完】…`、`- 【已验证】…`、`- 【结论】…`、`- 【待办】…`、`- 【待收尾】…`、`- 【注意】…`、`- 【归因纪律】…`、`- 【收尾纪律】…`、`- 【并列直接原因】…`、`- 【受阻】…`、`- 【禁止红线】…`、`- 【允许范围】…`。',
1266
1631
  '4. **去噪与聚合铁律**:遇到大量同前缀或已结束的后台巡检子代理(如 `mnemon-review-*`),**严禁逐一报菜名罗列**,必须合并成一句话统计(如 `- 【团队】1 名子代理运行中,其余 12 名历史巡检已结束`);自动忽略 `[dsh-mnemon:...]` 等系统内部检查点噪音。',
1267
1632
  '5. 具体路径、端口、版本号、命令原样保留,同一事实绝不重复,只陈述真实输入,第一个 `## ` 之前不要输出任何多余字符。',
1268
1633
  ].join('\n')
@@ -1440,7 +1805,8 @@ export async function getChiefView(deps, sessionId, { regenerate = false, autoSu
1440
1805
  const state = loadChiefState()
1441
1806
  const view = clusterView(state, rootId)
1442
1807
  const modelsInfo = await listChiefModels(deps, false, rootId)
1443
- const paceMode = (state.config && state.config.paceMode) || 'manual'
1808
+ const effCfgBefore = resolveWorkspaceConfig(state, rootId)
1809
+ const paceMode = effCfgBefore.paceMode || 'manual'
1444
1810
 
1445
1811
  const rawInput = buildNarrativeInput({
1446
1812
  board,
@@ -1496,10 +1862,12 @@ export async function getChiefView(deps, sessionId, { regenerate = false, autoSu
1496
1862
  ? latestView.narrative.text
1497
1863
  : buildFallbackNarrative({ board, facts: latestView.facts, targets: directory.targets })
1498
1864
 
1865
+ const ownWs = ensureWorkspace(latestState, rootId)
1866
+ const effectiveConfig = resolveWorkspaceConfig(latestState, rootId)
1499
1867
  return {
1500
1868
  ok: true,
1501
1869
  rootId,
1502
- config: latestState.config,
1870
+ config: effectiveConfig,
1503
1871
  models: modelsInfo,
1504
1872
  narrative: {
1505
1873
  text: narrativeText,
@@ -1517,9 +1885,136 @@ export async function getChiefView(deps, sessionId, { regenerate = false, autoSu
1517
1885
  peers: directory.targets,
1518
1886
  otherSessions: directory.otherSessions,
1519
1887
  cluster: directory.cluster,
1888
+ flippedPrecipitatedIds: (ownWs.flippedPrecipitatedIds || []).slice(),
1889
+ runtimeGuard: { ...ownWs.runtimeGuard },
1520
1890
  }
1521
1891
  }
1522
1892
 
1893
+ /** Manage which cold precipitated-vault entries are explicitly unsealed/flipped into a single root session. */
1894
+ export function updateWorkspaceFlippedIds(sessionId, { flippedId = '', sealId = '', clearAll = false } = {}) {
1895
+ const key = String(sessionId || 'global').trim() || 'global'
1896
+ return mutateChiefState((state) => {
1897
+ const ws = ensureWorkspace(state, key)
1898
+ const set = new Set(ws.flippedPrecipitatedIds || [])
1899
+ if (clearAll) {
1900
+ set.clear()
1901
+ } else {
1902
+ if (flippedId) set.add(String(flippedId).trim())
1903
+ if (sealId) set.delete(String(sealId).trim())
1904
+ }
1905
+ ws.flippedPrecipitatedIds = [...set].slice(-20)
1906
+ return { ok: true, flippedPrecipitatedIds: ws.flippedPrecipitatedIds.slice() }
1907
+ })
1908
+ }
1909
+
1910
+ /** One-click system deployment of Chief state (`facts`, `narrative`, `chat`/`mailbox` bridge) to a target Chief workspace (strictly keeping `flippedPrecipitatedIds = []`). */
1911
+ export function deployChiefWorkspaceState(deps, {
1912
+ fromRootId = '',
1913
+ toRootId = '',
1914
+ fromTitle = '',
1915
+ customText = '',
1916
+ objective = '',
1917
+ } = {}) {
1918
+ const fromKey = String(fromRootId || 'global').trim() || 'global'
1919
+ const toKey = String(toRootId || '').trim()
1920
+ if (!toKey) return { ok: false, error: '目标会话 ID 不能为空' }
1921
+
1922
+ return mutateChiefState((state) => {
1923
+ const fromWs = ensureWorkspace(state, fromKey)
1924
+ const toWs = ensureWorkspace(state, toKey)
1925
+
1926
+ const existingTexts = new Set(toWs.facts.map(f => f.text.trim()))
1927
+ let copiedFacts = 0
1928
+ for (const f of fromWs.facts) {
1929
+ if (!f || !f.text) continue
1930
+ const norm = f.text.trim()
1931
+ if (existingTexts.has(norm)) continue
1932
+ existingTexts.add(norm)
1933
+ toWs.facts.push({
1934
+ ...f,
1935
+ id: nextId('fact'),
1936
+ source: f.source || `移交自 ${fromTitle || fromKey}`,
1937
+ updatedAt: Date.now(),
1938
+ })
1939
+ copiedFacts += 1
1940
+ }
1941
+ if (toWs.facts.length > FACTS_CAP) {
1942
+ const pinned = toWs.facts.filter(f => f.pinned)
1943
+ const rest = toWs.facts.filter(f => !f.pinned).slice(-(FACTS_CAP - pinned.length))
1944
+ toWs.facts = [...pinned, ...rest].slice(-FACTS_CAP)
1945
+ }
1946
+
1947
+ if (fromWs.narrative && fromWs.narrative.text && !toWs.narrative.text) {
1948
+ toWs.narrative = {
1949
+ ...fromWs.narrative,
1950
+ hash: fromWs.narrative.hash || '',
1951
+ at: Date.now(),
1952
+ }
1953
+ }
1954
+
1955
+ const briefLines = [
1956
+ `- 【跨会话接力部署】本会话参谋状态已自 **${fromTitle || fromKey}** 系统级一键移交部署完成。`,
1957
+ objective ? `- 【继承总目标】${clamp(objective, 180)}` : '',
1958
+ copiedFacts > 0 ? `- 【继承纪律与事实】共继承 **${copiedFacts} 条**核心记忆与纪律。` : '',
1959
+ customText ? `- 【附带交接叮嘱】${clamp(customText, 240)}` : '',
1960
+ ].filter(Boolean).join('\n')
1961
+
1962
+ const mailItem = normalizeMail({
1963
+ id: nextId('mail'),
1964
+ from: 'DSH 参谋长 (接力部署)',
1965
+ fromSession: fromKey,
1966
+ to: 'lead',
1967
+ toSession: toKey,
1968
+ subject: `跨会话参谋部署:自 ${fromTitle || fromKey}`,
1969
+ text: briefLines,
1970
+ mode: 'silent',
1971
+ deliveredPhysical: false,
1972
+ at: Date.now(),
1973
+ })
1974
+ if (mailItem) {
1975
+ toWs.mailbox.push(mailItem)
1976
+ if (toWs.mailbox.length > MAIL_CAP) toWs.mailbox = toWs.mailbox.slice(-MAIL_CAP)
1977
+ }
1978
+
1979
+ toWs.chat.push({
1980
+ id: nextId('chat'),
1981
+ role: 'chief',
1982
+ text: briefLines,
1983
+ actions: ['系统接力部署', ...(copiedFacts > 0 ? [`继承记忆 ×${copiedFacts}`] : [])],
1984
+ at: Date.now(),
1985
+ })
1986
+ if (toWs.chat.length > CHAT_CAP) toWs.chat = toWs.chat.slice(-CHAT_CAP)
1987
+
1988
+ // Clone safe workspace chief config (model, pace, tactical preferences), ALWAYS forcing intervention=false!
1989
+ const fromCfg = resolveWorkspaceConfig(state, fromKey)
1990
+ toWs.config = {
1991
+ modelRef: fromCfg.modelRef || '',
1992
+ paceMode: fromCfg.paceMode || 'manual',
1993
+ autoPilot: Boolean(fromCfg.autoPilot),
1994
+ autoReview: Boolean(fromCfg.autoReview),
1995
+ tacticalModes: {
1996
+ ...normalizeTacticalModes(fromCfg.tacticalModes),
1997
+ intervention: false,
1998
+ },
1999
+ }
2000
+ toWs.runtimeGuard.interventionTurns = 0
2001
+ toWs.runtimeGuard.unchangedCount = 0
2002
+ toWs.runtimeGuard.circuitBroken = false
2003
+ toWs.runtimeGuard.circuitReason = ''
2004
+
2005
+ // Strictly keep precipitated cold vault isolated at 0-token default in destination session!
2006
+ toWs.flippedPrecipitatedIds = []
2007
+
2008
+ return {
2009
+ ok: true,
2010
+ copiedFacts,
2011
+ narrativeCopied: Boolean(fromWs.narrative && fromWs.narrative.text),
2012
+ flippedPrecipitatedIds: [],
2013
+ config: { ...toWs.config, tacticalModes: { ...toWs.config.tacticalModes } },
2014
+ }
2015
+ })
2016
+ }
2017
+
1523
2018
  /* -------------------------------------------------------------------------- */
1524
2019
  /* Chief Command Bar: All-Seeing Strategist + Relay + Bounds + Board Ops */
1525
2020
  /* -------------------------------------------------------------------------- */
@@ -1533,7 +2028,7 @@ const ASK_CHIEF_SYSTEM = [
1533
2028
  '',
1534
2029
  '请精准洞悉用户意图(态势汇报、卡点诊断、战术参谋、拆话传话、代维护看板、记忆管理、提炼或浓缩零散边界),并**只输出一个合法 JSON 对象**:',
1535
2030
  '{',
1536
- ' "reply": "必须【简明、结构化、分点作答】!用换行 `- 【标签】结论` 列出(如【当前进展】【活跃现场】【受阻卡点】【下一步建议】),直给干货,绝不说『记忆里没有这条』,绝不堆砌废话或暴露内部 sessionId",',
2031
+ ' "reply": "必须【简明、结构化、分点作答】!用换行 `- 【标签】结论` 列出(优先使用语义清晰标签:如【总目标】【推进中】【已完】【已验证】【结论】【待办】【待收尾】【注意】【归因纪律】【并列直接原因】【受阻】【禁止红线】【下一步建议】),直给干货,绝不说『记忆里没有这条』,绝不堆砌废话或暴露内部 sessionId",',
1537
2032
  ' "relays": [',
1538
2033
  ' { "target": "成员 key 或名字(如 lead / 子代理名 / session-xxx / all)", "mode": "steer|followup|silent", "subject": "简短事由", "text": "替用户转化好的清晰可执行指令" }',
1539
2034
  ' ],',
@@ -1568,6 +2063,7 @@ const ASK_CHIEF_SYSTEM = [
1568
2063
  '- 【边界奏请与零散浓缩】:',
1569
2064
  ' 1) 总结踩坑红线时,生成 `boundProposals` 呈交用户拍板(若用户提到「全局定住/以后所有任务都生效」则设 `"pinGlobal": true`);只有用户明确下令「直接写进禁止/允许边界」时才用 `boardOps`。',
1570
2065
  ' 2) 当用户要求「把重要的零散边界总结成一条 / 合并重复边界」时,仔细阅读现有边界,保留关键命令名/路径/硬红线,浓缩为 1 条精炼总则放入 `boundProposals[0].item`,并把被它吸收替代的旧条文原样放进 `replaces` 数组(若被合并旧规中含 📌 全局定住项,则 `"pinGlobal": true`)。',
2066
+ '- 【看图与带图拆话】:当用户附带上传图片时,请直接结合图片画面诊断 UI 样式、报错截图或架构图;若你在 relays 中向代理拆话派活,系统会自动把用户附带的图片一并转送给目标代理。',
1571
2067
  ].join('\n')
1572
2068
 
1573
2069
  const CONSOLIDATE_BOUNDS_SYSTEM = [
@@ -1807,6 +2303,25 @@ function applyBoardOps(deps, rootId, boardOps) {
1807
2303
  by: 'chief',
1808
2304
  })
1809
2305
  if (res && res.ok) executed.push('更新推进断点')
2306
+ } else if (op === 'plan.resetForGoal') {
2307
+ const res = deps.runAction({ action: 'plan.resetForGoal', session: rootId, by: 'chief' })
2308
+ if (res && res.ok) executed.push('清空陈旧计划以便按新目标重编')
2309
+ } else if (op === 'plan.set' && Array.isArray(opItem.steps)) {
2310
+ const steps = opItem.steps.map(s => (typeof s === 'string' ? { text: s, done: false } : s)).filter(Boolean)
2311
+ if (steps.length > 0) {
2312
+ const res = deps.runAction({ action: 'plan.set', steps, session: rootId, by: 'chief' })
2313
+ if (res && res.ok) executed.push(`更新计划共 ${steps.length} 步`)
2314
+ }
2315
+ } else if (op === 'goal.proposeApproval') {
2316
+ const res = deps.runAction({
2317
+ action: 'goal.proposeApproval',
2318
+ objective: String(opItem.objective || ''),
2319
+ summary: String(opItem.summary || ''),
2320
+ evidence: String(opItem.evidence || ''),
2321
+ session: rootId,
2322
+ by: 'chief',
2323
+ })
2324
+ if (res && res.ok) executed.push('呈批目标结项')
1810
2325
  } else if ((op === 'bounds.forbid' || op === 'bounds.allow') && opItem.item) {
1811
2326
  const field = op === 'bounds.forbid' ? 'forbidden' : 'allowed'
1812
2327
  const val = clamp(opItem.item, 220)
@@ -2189,14 +2704,15 @@ const ORGANIZE_ARCHIVES_SYSTEM = [
2189
2704
  */
2190
2705
  export async function organizeArchivesWithChief(deps, {
2191
2706
  sessionId = '',
2707
+ cabinetId = '',
2192
2708
  ids = [],
2193
2709
  folder = '',
2194
2710
  scope = 'unorganized',
2195
2711
  instruction = '',
2196
2712
  } = {}) {
2197
2713
  const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
2198
- const sharedFile = typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile
2199
- const store = loadArchiveStore(sharedFile)
2714
+ const targetOpt = archiveTargetForRoot(deps, rootId, cabinetId)
2715
+ const store = loadArchiveStore(targetOpt)
2200
2716
 
2201
2717
  if (!store.items.length) {
2202
2718
  return {
@@ -2298,8 +2814,8 @@ export async function organizeArchivesWithChief(deps, {
2298
2814
  }
2299
2815
  }
2300
2816
 
2301
- const applied = applyChiefArchiveCurations(allCurations, allNewFolders, sharedFile)
2302
- const refreshedList = listArchiveHeaders(rootId, {}, sharedFile)
2817
+ const applied = applyChiefArchiveCurations(allCurations, allNewFolders, targetOpt)
2818
+ const refreshedList = listArchiveHeaders(rootId, { includePrecipitated: false }, targetOpt)
2303
2819
  const folderNameMap = new Map(refreshedList.folders.map(f => [f.id, f.label]))
2304
2820
 
2305
2821
  const folderStats = new Map()
@@ -2347,20 +2863,369 @@ export async function organizeArchivesWithChief(deps, {
2347
2863
  }
2348
2864
  }
2349
2865
 
2866
+ const HARVEST_ARCHIVE_SYSTEM = [
2867
+ '你是「DSH 参谋长」的高精度上下文抢救员。当前即将执行上下文压缩或用户主动抢救本轮现场细节,请从原始对话与看板轨迹中无损抢救工程硬细节并归档!',
2868
+ '要求:',
2869
+ '1. 重点抓取:**具体文件路径、行号、真实命令/脚本参数、刚确认的报错根因与结论、尚未完成的断点、未解决的阻塞细节**,严禁泛泛而谈或丢弃关键参数。',
2870
+ '2. 绝对不要编造原文未出现的文件名或命令。',
2871
+ '3. 只输出一个合法 JSON 对象:',
2872
+ '{',
2873
+ ' "folder": "coords|incidents|contracts|ops|plans",',
2874
+ ' "paperclip": "gold|silver|copper",',
2875
+ ' "title": "精炼明确归档标题(≤38字)",',
2876
+ ' "summary": "一句话总结核心工程事实(≤56字)",',
2877
+ ' "tags": ["标签1", "标签2"],',
2878
+ ' "points": [',
2879
+ ' { "title": "记忆点短标题", "cue": "速览钩子", "detail": "含原文件路径/命令/结论的高保真明细" }',
2880
+ ' ]',
2881
+ '}',
2882
+ ].join('\n')
2883
+
2884
+ function collectRawSessionEvidence(deps, { sessionId = '', rootId = '', agent = null }) {
2885
+ const board = deps && deps.boardForSession && deps.boardFileFor
2886
+ ? deps.boardForSession(deps.boardFileFor(rootId))
2887
+ : null
2888
+ const lines = []
2889
+ if (board && board.objective) lines.push(`【当前总目标】${board.objective}`)
2890
+ if (board && board.cursor && (board.cursor.step || board.cursor.next || board.cursor.blocked)) {
2891
+ lines.push(`【断点游标】当前=${board.cursor.step || '无'} | 下一步=${board.cursor.next || '无'} | 阻塞=${board.cursor.blocked || '无'}`)
2892
+ }
2893
+ const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
2894
+ const openTasks = tasks.filter(t => t.status !== 'done').slice(0, 6)
2895
+ if (openTasks.length > 0) {
2896
+ lines.push('【进行中/未完任务】')
2897
+ for (const t of openTasks) {
2898
+ lines.push(`- [${t.status}] #${t.id} ${t.title}${t.note ? `(${clamp(t.note, 100)})` : ''}`)
2899
+ }
2900
+ }
2901
+
2902
+ let targetAgent = agent
2903
+ if (!targetAgent && deps && deps.runtime) {
2904
+ try {
2905
+ const agentsSvc = deps.runtime.get('agents')
2906
+ if (agentsSvc && typeof agentsSvc.get === 'function') {
2907
+ targetAgent = agentsSvc.get(sessionId) || agentsSvc.get(rootId)
2908
+ }
2909
+ } catch {}
2910
+ }
2911
+
2912
+ const pathsFound = new Set()
2913
+ const cmdsFound = new Set()
2914
+ const rawTurns = []
2915
+ try {
2916
+ if (targetAgent && targetAgent.session && typeof targetAgent.session.deriveMessages === 'function') {
2917
+ const msgs = targetAgent.session.deriveMessages() || []
2918
+ for (const m of msgs.slice(-14)) {
2919
+ if (!m || !m.role) continue
2920
+ if (m.source && m.source.kind && m.source.kind !== 'user' && m.role === 'user') continue
2921
+ const blocks = Array.isArray(m.content)
2922
+ ? m.content
2923
+ : (typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : [])
2924
+ for (const b of blocks) {
2925
+ if (!b || typeof b !== 'object') continue
2926
+ if (b.type === 'text' && typeof b.text === 'string') {
2927
+ const clean = stripCheckpointNoise(b.text)
2928
+ if (!clean || isInternalCheckpointNoise(clean) || secretLike(clean)) continue
2929
+ rawTurns.push(`${m.role === 'user' ? 'User' : 'Assistant'}: ${clamp(clean, 500)}`)
2930
+ const pathMatches = clean.match(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`<>|]{2,70})+/g) || []
2931
+ for (const p of pathMatches.slice(0, 8)) pathsFound.add(p)
2932
+ } else if ((b.type === 'tool_use' || b.type === 'tool-call' || b.type === 'toolCall') && (b.name || b.toolName)) {
2933
+ const name = String(b.name || b.toolName)
2934
+ const rawArgs = b.input || b.arguments || b.args
2935
+ let obj = null
2936
+ try { obj = typeof rawArgs === 'string' ? JSON.parse(rawArgs) : rawArgs } catch {}
2937
+ const cmd = obj && (obj.command || obj.cmd || obj.CommandLine)
2938
+ const fpath = obj && (obj.path || obj.file_path || obj.Path)
2939
+ if (fpath && !secretLike(String(fpath))) pathsFound.add(String(fpath))
2940
+ if (cmd && !secretLike(String(cmd))) cmdsFound.add(clamp(String(cmd), 140))
2941
+ rawTurns.push(`Tool[${name}]: ${clamp(JSON.stringify(obj || {}), 220)}`)
2942
+ }
2943
+ }
2944
+ }
2945
+ }
2946
+ } catch {}
2947
+
2948
+ if (pathsFound.size > 0) lines.push('', '【涉及路径与符号】\n' + [...pathsFound].slice(0, 12).map(p => `- ${p}`).join('\n'))
2949
+ if (cmdsFound.size > 0) lines.push('', '【近期执行命令】\n' + [...cmdsFound].slice(0, 8).map(c => `- \`${c}\``).join('\n'))
2950
+ if (rawTurns.length > 0) lines.push('', '【近期对话与工具流水】\n' + rawTurns.slice(-10).join('\n'))
2951
+ return {
2952
+ board,
2953
+ text: lines.join('\n').trim(),
2954
+ hasTranscript: rawTurns.length > 0,
2955
+ pathCount: pathsFound.size,
2956
+ cmdCount: cmdsFound.size,
2957
+ }
2958
+ }
2959
+
2960
+ /** High-precision harvest of recent session details into active project's working archive cabinet (`pre-compaction` or `manual`). */
2961
+ export async function harvestTurnDetailsToArchive(deps, {
2962
+ sessionId = '',
2963
+ agent = null,
2964
+ trigger = 'manual',
2965
+ focusHint = '',
2966
+ cabinetId = '',
2967
+ } = {}) {
2968
+ const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId, agent)) || String(sessionId || 'global')
2969
+ const targetOpt = archiveTargetForRoot(deps, rootId, cabinetId)
2970
+ const evidence = collectRawSessionEvidence(deps, { sessionId: sessionId || rootId, rootId, agent })
2971
+ const bodySource = [
2972
+ focusHint ? `【抢救焦点提示】${cleanMultiline(focusHint, 240)}` : '',
2973
+ evidence.text || `【抢救快照】时间 ${new Date().toLocaleString('zh-CN')} | 触发原因:${trigger}`,
2974
+ ].filter(Boolean).join('\n\n')
2975
+
2976
+ let parsed = null
2977
+ let usedLlm = false
2978
+ try {
2979
+ const llmRes = await callChiefLlm(deps, {
2980
+ sessionId: rootId,
2981
+ system: HARVEST_ARCHIVE_SYSTEM,
2982
+ prompt: `触发模式:${trigger === 'pre-compaction' ? '上下文压缩前自动高保真抢救' : '用户手动抢救当前工作细节入柜'}\n\n${cleanMultiline(bodySource, 5200)}`,
2983
+ maxTokens: SUMMARY_MAX_TOKENS,
2984
+ })
2985
+ if (llmRes && llmRes.ok && llmRes.text) {
2986
+ parsed = extractJsonObject(llmRes.text)
2987
+ if (parsed && (parsed.title || (Array.isArray(parsed.points) && parsed.points.length > 0))) {
2988
+ usedLlm = true
2989
+ }
2990
+ }
2991
+ } catch {}
2992
+
2993
+ const fallback = smartParseNoteToDossier({
2994
+ title: `${trigger === 'pre-compaction' ? '【压缩前抢救】' : '【细节抢救】'}${clamp(focusHint || (evidence.board && evidence.board.objective) || '本轮工作现场细节', 28)}`,
2995
+ body: bodySource,
2996
+ })
2997
+ const d = new Date()
2998
+ const timeStamp = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
2999
+ const title = clamp((parsed && parsed.title) || `${fallback.title || '工作细节抢救'} (${timeStamp})`, 70)
3000
+ const folder = String((parsed && parsed.folder) || fallback.folder || 'incidents').trim()
3001
+ const paperclip = ['gold', 'silver', 'copper'].includes(parsed && parsed.paperclip)
3002
+ ? parsed.paperclip
3003
+ : (trigger === 'pre-compaction' ? 'gold' : fallback.paperclip)
3004
+ const summary = clamp((parsed && parsed.summary) || fallback.summary || clamp(bodySource, 110), 180)
3005
+ const tags = Array.isArray(parsed && parsed.tags) && parsed.tags.length > 0
3006
+ ? parsed.tags.slice(0, 6)
3007
+ : [trigger === 'pre-compaction' ? '压缩抢救' : '细节抢救', ...(evidence.cmdCount > 0 ? ['命令流水'] : [])]
3008
+ const points = Array.isArray(parsed && parsed.points) && parsed.points.length > 0
3009
+ ? parsed.points
3010
+ : fallback.points
3011
+
3012
+ const saveRes = mutateArchive({
3013
+ op: 'save',
3014
+ session: rootId,
3015
+ folder,
3016
+ paperclip,
3017
+ title,
3018
+ summary,
3019
+ tags,
3020
+ points,
3021
+ body: bodySource,
3022
+ }, targetOpt)
3023
+
3024
+ if (!saveRes || !saveRes.ok || !saveRes.item || !saveRes.item.id) {
3025
+ return { ok: false, error: (saveRes && saveRes.error) || '工作档案写入失败,未执行后续操作' }
3026
+ }
3027
+
3028
+ // Strictly verify persistence on disk before returning ok!
3029
+ const verify = getArchiveDetail(saveRes.item.id, rootId, targetOpt)
3030
+ if (!verify || !verify.ok || !verify.item || verify.item.id !== saveRes.item.id) {
3031
+ return { ok: false, error: '档案硬盘落盘复核失败' }
3032
+ }
3033
+
3034
+ if (deps && typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
3035
+ deps.appendBoardLog(rootId, `📥 已将本轮工程细节抢救入柜:《${title}》(trigger=${trigger})`, 'chief')
3036
+ }
3037
+
3038
+ return {
3039
+ ok: true,
3040
+ trigger,
3041
+ usedLlm,
3042
+ savedId: saveRes.item.id,
3043
+ item: verify.item,
3044
+ cabinetId: targetOpt.cabinetId || verify.cabinetId || '',
3045
+ archives: listArchiveHeaders(rootId, { includePrecipitated: trigger === 'manual' }, targetOpt),
3046
+ }
3047
+ }
3048
+
3049
+ const PRECIPITATE_EXPERIENCE_SYSTEM = [
3050
+ '你是「DSH 参谋长」的知识沉淀总编。请把当前工作档案柜(或指定抽屉)的多份工作卷宗脱水提炼为 1~3 条**跨会话长期可复用**的高密度经验胶囊,准备封存入 0-Token 冷库!',
3051
+ '原则:',
3052
+ '1. **去水保干**:彻底剔除单轮聊天客套话、过时中间试错步骤与一次性状态;只保留长期有价值的【工程架构契约 / 踩坑根因与解法 / 核心文件路径与校验命令】。',
3053
+ '2. 保留真实文件名、函数名、配置键、关键命令,绝不编造不存在的细节。',
3054
+ '3. 只输出一个合法 JSON 对象:',
3055
+ '{',
3056
+ ' "entries": [',
3057
+ ' {',
3058
+ ' "title": "沉淀经验短标题(≤36字)",',
3059
+ ' "category": "coords|incidents|contracts|ops",',
3060
+ ' "summary": "一句话价值摘要(≤60字)",',
3061
+ ' "tags": ["标签1", "标签2"],',
3062
+ ' "points": [',
3063
+ ' { "title": "要点标题", "cue": "一句话钩子", "detail": "完整可复用步骤/路径/契约" }',
3064
+ ' ],',
3065
+ ' "body": "完整精炼正文"',
3066
+ ' }',
3067
+ ' ]',
3068
+ '}',
3069
+ ].join('\n')
3070
+
3071
+ /** Purify working archive items into reusable long-term entries saved to `precipitated/<projectKey>.json`. */
3072
+ export async function precipitateExperienceWithChief(deps, {
3073
+ sessionId = '',
3074
+ op = 'cabinet',
3075
+ cabinetId = '',
3076
+ folder = '',
3077
+ clearSource = false,
3078
+ } = {}) {
3079
+ const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
3080
+ const targetOpt = archiveTargetForRoot(deps, rootId, cabinetId)
3081
+ const store = loadArchiveStore(targetOpt)
3082
+ const projectKey = resolveProjectKey(targetOpt.cwd)
3083
+
3084
+ const selectedItems = (op === 'drawer' && folder)
3085
+ ? store.items.filter(it => it.folder === folder)
3086
+ : store.items.slice()
3087
+
3088
+ if (!selectedItems.length) {
3089
+ return { ok: false, error: '当前选定范围暂无工作档案可沉淀' }
3090
+ }
3091
+
3092
+ const promptBody = selectedItems.slice(0, 12).map((it, idx) => [
3093
+ `--- 工作档案 #${idx + 1}: 《${it.title}》 (drawer=${it.folder}, clip=${it.paperclip}) ---`,
3094
+ `提要: ${it.summary || '无'}`,
3095
+ Array.isArray(it.points) && it.points.length > 0
3096
+ ? '记忆点:\n' + it.points.map(p => `- ${p.title}: ${p.detail || p.cue}`).join('\n')
3097
+ : `正文:\n${cleanMultiline(it.body, 1500)}`,
3098
+ ].join('\n')).join('\n\n')
3099
+
3100
+ let entriesRaw = null
3101
+ let usedLlm = false
3102
+ try {
3103
+ const llmRes = await callChiefLlm(deps, {
3104
+ sessionId: rootId,
3105
+ system: PRECIPITATE_EXPERIENCE_SYSTEM,
3106
+ prompt: `待沉淀工程档案范围:${op === 'drawer' && folder ? `抽屉 ${folder}` : '整柜'}(共 ${selectedItems.length} 卷)\n\n${cleanMultiline(promptBody, 6400)}`,
3107
+ maxTokens: SUMMARY_MAX_TOKENS,
3108
+ })
3109
+ if (llmRes && llmRes.ok && llmRes.text) {
3110
+ const parsed = extractJsonObject(llmRes.text)
3111
+ if (parsed && Array.isArray(parsed.entries) && parsed.entries.length > 0) {
3112
+ entriesRaw = parsed.entries.slice(0, 4)
3113
+ usedLlm = true
3114
+ }
3115
+ }
3116
+ } catch {}
3117
+
3118
+ if (!entriesRaw) {
3119
+ // Deterministic distillation fallback preserving high-signal points & paths
3120
+ const leadTitle = op === 'drawer' && folder
3121
+ ? `【${folder} 沉淀】${selectedItems[0].title}`
3122
+ : `【工程沉淀】${selectedItems[0].title}${selectedItems.length > 1 ? ` 等 ${selectedItems.length} 卷精华` : ''}`
3123
+ const mergedPoints = []
3124
+ const mergedTags = new Set(['已沉淀'])
3125
+ const bodyBlocks = []
3126
+ for (const it of selectedItems.slice(0, 8)) {
3127
+ for (const tg of (it.tags || [])) mergedTags.add(tg)
3128
+ bodyBlocks.push(`### ${it.title}\n${cleanMultiline(it.summary || it.body, 500)}`)
3129
+ if (Array.isArray(it.points) && it.points.length > 0) {
3130
+ for (const pt of it.points.slice(0, 3)) {
3131
+ mergedPoints.push(pt)
3132
+ }
3133
+ } else {
3134
+ mergedPoints.push({
3135
+ title: clamp(it.title, 32),
3136
+ cue: clamp(it.summary || it.body, 56),
3137
+ detail: cleanMultiline(it.body || it.summary, 420),
3138
+ })
3139
+ }
3140
+ }
3141
+ entriesRaw = [{
3142
+ title: clamp(leadTitle, 64),
3143
+ category: folder || selectedItems[0].folder || 'contracts',
3144
+ summary: clamp(selectedItems.map(x => x.summary || x.title).filter(Boolean).slice(0, 2).join(';'), 140),
3145
+ tags: [...mergedTags].slice(0, 6),
3146
+ points: mergedPoints.slice(0, 10),
3147
+ body: bodyBlocks.join('\n\n'),
3148
+ }]
3149
+ }
3150
+
3151
+ const savedEntries = []
3152
+ for (const raw of entriesRaw) {
3153
+ const res = savePrecipitatedEntry(projectKey, {
3154
+ ...raw,
3155
+ sourceCabinet: store.cabinetName || store.cabinetId,
3156
+ sourceCount: selectedItems.length,
3157
+ }, targetOpt)
3158
+ if (res && res.ok && res.entry) savedEntries.push(res.entry)
3159
+ }
3160
+
3161
+ if (!savedEntries.length) {
3162
+ return { ok: false, error: '沉淀写入冷库失败,已保留原有工作档案' }
3163
+ }
3164
+
3165
+ let clearedSource = false
3166
+ if (clearSource) {
3167
+ if (op === 'drawer' && folder) {
3168
+ mutateArchive({ op: 'clearFolder', folder }, targetOpt)
3169
+ clearedSource = true
3170
+ } else {
3171
+ mutateArchive({ op: 'clearByIds', ids: selectedItems.map(x => x.id) }, targetOpt)
3172
+ clearedSource = true
3173
+ }
3174
+ }
3175
+
3176
+ if (deps && typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
3177
+ deps.appendBoardLog(rootId, `⏬ 已从${selectedItems.length} 卷工作档案提炼 ${savedEntries.length} 条可复用经验封存入 0-Token 冷库`, 'chief')
3178
+ }
3179
+
3180
+ return {
3181
+ ok: true,
3182
+ projectKey,
3183
+ usedLlm,
3184
+ createdCount: savedEntries.length,
3185
+ entries: savedEntries,
3186
+ clearedSource,
3187
+ archives: listArchiveHeaders(rootId, { includePrecipitated: true }, targetOpt),
3188
+ }
3189
+ }
3190
+
2350
3191
  export async function askOrCommandChief(deps, {
2351
3192
  sessionId = '',
2352
3193
  text = '',
2353
3194
  forcedTarget = '',
2354
3195
  forcedMode = 'steer',
3196
+ images = [],
2355
3197
  }) {
2356
- const input = cleanMultiline(text, 2000)
2357
- if (!input) return { ok: false, error: '请输入要询问或吩咐参谋长的内容' }
3198
+ const rawInput = cleanMultiline(text, 2000)
3199
+ const rawImages = Array.isArray(images) ? images : []
3200
+ if (!rawInput && !rawImages.length) {
3201
+ return { ok: false, error: '请输入要询问或吩咐参谋长的内容或上传图片' }
3202
+ }
2358
3203
 
2359
3204
  const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
3205
+ const savedImagePaths = rawImages.length > 0 ? persistChiefImagesToWorkspace(deps, rootId, rawImages) : []
3206
+ let imageBlocks = []
3207
+ if (rawImages.length > 0) {
3208
+ try {
3209
+ imageBlocks = await admitChiefImages(deps, rawImages)
3210
+ } catch (err) {
3211
+ if (!savedImagePaths.length) {
3212
+ return { ok: false, error: String(err && err.message ? err.message : err) }
3213
+ }
3214
+ imageBlocks = []
3215
+ }
3216
+ }
3217
+
3218
+ const effectiveImgCount = Math.max(imageBlocks.length, savedImagePaths.length)
3219
+ const input = rawInput || '请结合我上传的图片进行分析处理。'
3220
+ const userDisplayText = rawInput || `[上传图片 ×${effectiveImgCount}]`
3221
+ const imgMeta = effectiveImgCount > 0 ? { imageCount: effectiveImgCount } : {}
3222
+
2360
3223
  const directory = await listPeerDirectory(deps, rootId)
2361
3224
  const board = deps.boardForSession(deps.boardFileFor(rootId))
2362
3225
  const state = loadChiefState()
2363
3226
  const view = clusterView(state, rootId)
3227
+ const ownWs = ensureWorkspace(state, rootId)
3228
+ const targetOpt = archiveTargetForRoot(deps, rootId)
2364
3229
 
2365
3230
  // Fast path: if user explicitly picked a concrete target pill AND used direct relay mode without asking chief to decompose
2366
3231
  if (forcedTarget && forcedTarget !== 'auto') {
@@ -2368,17 +3233,19 @@ export async function askOrCommandChief(deps, {
2368
3233
  fromSession: rootId,
2369
3234
  fromLabel: '用户 (经 DSH 参谋长)',
2370
3235
  target: forcedTarget,
2371
- text: input,
3236
+ text: rawInput || '请查看随信附带的图片与落盘路径。',
2372
3237
  mode: ['steer', 'followup', 'silent'].includes(forcedMode) ? forcedMode : 'steer',
3238
+ imageBlocks,
3239
+ savedImagePaths,
2373
3240
  })
2374
3241
  const reply = delivery.ok
2375
- ? `已按你的指定向 ${delivery.target || forcedTarget} ${forcedMode === 'steer' ? '插话' : forcedMode === 'silent' ? '投递备忘纸条' : '递话'}${delivery.note ? '(' + delivery.note + ')' : '。'}`
3242
+ ? `已按你的指定向 ${delivery.target || forcedTarget} ${forcedMode === 'steer' ? '插话' : forcedMode === 'silent' ? '投递备忘纸条' : '递话'}${effectiveImgCount ? `(附带 ${effectiveImgCount} 张图片,原图已落盘)` : ''}${delivery.note ? '(' + delivery.note + ')' : '。'}`
2376
3243
  : `投递失败:${delivery.error}`
2377
3244
 
2378
3245
  mutateChiefState((s) => {
2379
3246
  const ws = ensureWorkspace(s, rootId)
2380
3247
  ws.chat.push(
2381
- { id: nextId('chat'), role: 'user', text: input, target: forcedTarget, actions: [], at: Date.now() },
3248
+ { id: nextId('chat'), role: 'user', text: userDisplayText, target: forcedTarget, ...imgMeta, actions: [], at: Date.now() },
2382
3249
  { id: nextId('chat'), role: 'chief', text: reply, actions: [delivery.ok ? `→ ${delivery.target || forcedTarget}` : '投递失败'], at: Date.now() },
2383
3250
  )
2384
3251
  if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
@@ -2388,6 +3255,7 @@ export async function askOrCommandChief(deps, {
2388
3255
  ok: delivery.ok,
2389
3256
  reply,
2390
3257
  relays: [delivery],
3258
+ savedImagePaths,
2391
3259
  memoryChanges: [],
2392
3260
  boardOps: [],
2393
3261
  view: await getChiefView(deps, rootId, { autoSummarize: false }),
@@ -2416,19 +3284,39 @@ export async function askOrCommandChief(deps, {
2416
3284
  }
2417
3285
  }
2418
3286
 
2419
- // On-demand lazy archive lookup ONLY when the user explicitly asks about archives / historical engineering records
3287
+ // 0-Token Precipitated Vault Contract: ONLY read precipitated vault if this session EXPLICITLY flipped entries out!
3288
+ const flippedIds = Array.isArray(ownWs.flippedPrecipitatedIds) ? ownWs.flippedPrecipitatedIds : []
3289
+ const flippedVaultLines = []
3290
+ if (flippedIds.length > 0) {
3291
+ const projectKey = resolveProjectKey(targetOpt.cwd)
3292
+ const flippedItems = getFlippedOutPrecipitatedForSession(projectKey, rootId, true, targetOpt)
3293
+ if (flippedItems.length > 0) {
3294
+ flippedVaultLines.push('', '## 8. 本会话已显式翻出的跨会话沉淀经验(仅包含用户显式翻出授权的条目)')
3295
+ for (const entry of flippedItems) {
3296
+ flippedVaultLines.push(`- 🏛️ [沉淀/${entry.category}] 《${entry.title}》:${entry.summary}`)
3297
+ if (Array.isArray(entry.points) && entry.points.length > 0) {
3298
+ for (const pt of entry.points.slice(0, 4)) {
3299
+ flippedVaultLines.push(` * ${pt.title}:${clamp(pt.detail || pt.cue, 200)}`)
3300
+ }
3301
+ } else if (entry.body) {
3302
+ flippedVaultLines.push(` * 正文:${clamp(entry.body, 280)}`)
3303
+ }
3304
+ }
3305
+ }
3306
+ }
3307
+
3308
+ // On-demand lazy archive lookup ONLY when the user explicitly asks about working archives (never reads precipitated vault!)
2420
3309
  const asksArchiveExplicitly = /(?:档案|卷宗|归档|以前|历史记录|工程坐标|老笔记|查一下.*(?:怎么|路径|命令|配置))/.test(input)
2421
3310
  const onDemandArchiveLines = []
2422
3311
  if (asksArchiveExplicitly) {
2423
- const sharedFile = typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile
2424
- const found = searchArchives(input, { limit: 4 }, sharedFile)
3312
+ const found = searchArchives(input, { limit: 4 }, targetOpt)
2425
3313
  if (found.ok && found.hits.length > 0) {
2426
- onDemandArchiveLines.push('', '## 7. 按需调取的沉淀工程档案(仅因用户本次提问涉及历史档案而临时检索)')
3314
+ onDemandArchiveLines.push('', '## 7. 按需调取的工作档案柜卷宗(仅因用户本次提问涉及历史档案而临时检索)')
2427
3315
  for (let i = 0; i < found.hits.length; i += 1) {
2428
3316
  const hit = found.hits[i]
2429
3317
  onDemandArchiveLines.push(`- 📎 [${hit.folderLabel}] 《${hit.title}》:${hit.summary}`)
2430
3318
  if (i < 2) {
2431
- const det = getArchiveDetail(hit.id, rootId, sharedFile)
3319
+ const det = getArchiveDetail(hit.id, rootId, targetOpt)
2432
3320
  if (det.ok && det.item && Array.isArray(det.item.points)) {
2433
3321
  for (const pt of det.item.points.slice(0, 4)) {
2434
3322
  onDemandArchiveLines.push(` * ${pt.title}:${clamp(pt.detail || pt.cue, 180)}`)
@@ -2479,8 +3367,8 @@ export async function askOrCommandChief(deps, {
2479
3367
  `- 实时断点游标 (Cursor): 当前步骤="${cursor.step || '无'}" | 下一步="${cursor.next || '无'}" | 阻塞点="${cursor.blocked || '无'}"`,
2480
3368
  `- 计划步骤 (Plan): ${((board.plan || []).slice(0, 8).map(s => `${s.done ? '[✓]' : '[ ]'} ${clamp(s.text, 60)}`).join(';')) || '(无)'}`,
2481
3369
  `- 🔴 受阻任务 (${blockedTasks.length} 项): ${blockedTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}${t.note ? ' [原因:' + clamp(t.note, 80) + ']' : ''}`).join(';') || '(无)'}`,
2482
- `- 🟢 推进中任务 (${doingTasks.length} 项): ${doingTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}${t.note ? ' [' + clamp(t.note, 60) + ']' : ''}`).join(';') || '(无)'}`,
2483
- `- ⏳ 待办任务 (${todoTasks.length} 项): ${todoTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}`).join(';') || '(无)'}`,
3370
+ `- 🔵 推进中任务 (${doingTasks.length} 项): ${doingTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}${t.note ? ' [' + clamp(t.note, 60) + ']' : ''}`).join(';') || '(无)'}`,
3371
+ `- ⚪ 待办任务 (${todoTasks.length} 项): ${todoTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}`).join(';') || '(无)'}`,
2484
3372
  `- ✅ 最近完成 (${doneTasks.length} 项): ${doneTasks.slice(-5).map(t => `#${t.id} ${t.title}${t.evidence ? ' [证据:' + clamp(t.evidence, 60) + ']' : ''}`).join(';') || '(无)'}`,
2485
3373
  '',
2486
3374
  '## 4. 当前生效边界(📌全局定住 vs 本任务)',
@@ -2500,9 +3388,18 @@ export async function askOrCommandChief(deps, {
2500
3388
  .map(m => `- [回合/${m.section}] ${clamp(stripCheckpointNoise(m.title || m.text), 150)}`)),
2501
3389
  ...(view.mailbox.slice(-4).map(m => `- [信箱 ${m.from} → @${m.to}] ${clamp(m.text, 120)}`)),
2502
3390
  ...onDemandArchiveLines,
3391
+ ...flippedVaultLines,
2503
3392
  '',
2504
3393
  '## 用户刚刚对你说的话:',
2505
3394
  input,
3395
+ ...(savedImagePaths.length > 0
3396
+ ? [
3397
+ '',
3398
+ `🖼️ 用户随信上传了 ${savedImagePaths.length} 张原图(已真实落盘到工作区):`,
3399
+ ...savedImagePaths.map(p => `- ${p.path}`),
3400
+ '(重要提示:若当前参谋长模型不支持视觉看图,请把任务与上述绝对路径直接调度/递话给支持看图或读文件工具的主对话 @lead / 子代理处理,严禁臆造图内细节!)',
3401
+ ]
3402
+ : []),
2506
3403
  ]
2507
3404
 
2508
3405
  const llmRes = await callChiefLlm(deps, {
@@ -2510,8 +3407,17 @@ export async function askOrCommandChief(deps, {
2510
3407
  system: ASK_CHIEF_SYSTEM,
2511
3408
  prompt: promptLines.join('\n'),
2512
3409
  maxTokens: SUMMARY_MAX_TOKENS,
3410
+ imageBlocks,
3411
+ allowTextFallbackOnVisionMiss: savedImagePaths.length > 0,
2513
3412
  })
2514
3413
 
3414
+ if (imageBlocks.length > 0 && !llmRes.ok && !savedImagePaths.length) {
3415
+ return {
3416
+ ok: false,
3417
+ error: llmRes.error || '当前参谋长模型无法识别图片,请在右上角切换支持视觉的多模态模型后重试',
3418
+ }
3419
+ }
3420
+
2515
3421
  let parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
2516
3422
 
2517
3423
  // Graceful intelligent fallback if LLM is offline / unconfigured / returned non-JSON
@@ -2527,14 +3433,16 @@ export async function askOrCommandChief(deps, {
2527
3433
  target: targetName,
2528
3434
  text: msgBody,
2529
3435
  mode: 'steer',
3436
+ imageBlocks,
3437
+ savedImagePaths,
2530
3438
  })
2531
3439
  const fallbackReply = delivery.ok
2532
- ? `- 【已递话】已向 @${delivery.target} 插话传达指令。`
3440
+ ? `- 【已递话】已向 @${delivery.target} 插话传达指令${savedImagePaths.length ? `(附原图路径 ×${savedImagePaths.length})` : ''}。`
2533
3441
  : `- 【投递失败】未找到目标 ${targetName}(${delivery.error})`
2534
3442
  mutateChiefState((s) => {
2535
3443
  const ws = ensureWorkspace(s, rootId)
2536
3444
  ws.chat.push(
2537
- { id: nextId('chat'), role: 'user', text: input, actions: [], at: Date.now() },
3445
+ { id: nextId('chat'), role: 'user', text: userDisplayText, ...imgMeta, actions: [], at: Date.now() },
2538
3446
  { id: nextId('chat'), role: 'chief', text: fallbackReply, actions: [], at: Date.now() },
2539
3447
  )
2540
3448
  if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
@@ -2543,6 +3451,7 @@ export async function askOrCommandChief(deps, {
2543
3451
  ok: delivery.ok,
2544
3452
  reply: fallbackReply,
2545
3453
  relays: [delivery],
3454
+ savedImagePaths,
2546
3455
  memoryChanges: [],
2547
3456
  boardOps: [],
2548
3457
  view: await getChiefView(deps, rootId, { autoSummarize: false }),
@@ -2550,7 +3459,7 @@ export async function askOrCommandChief(deps, {
2550
3459
  }
2551
3460
 
2552
3461
  // 2) Natural-language request to consolidate scattered boundaries into one
2553
- if (/边界|红线/.test(input) && /总结成一条|合并成一条|浓缩|合一|整合/.test(input)) {
3462
+ if (!imageBlocks.length && /边界|红线/.test(input) && /总结成一条|合并成一条|浓缩|合一|整合/.test(input)) {
2554
3463
  const targetCol = /允许/.test(input) ? 'allowed' : /注意/.test(input) ? 'notes' : ''
2555
3464
  const consRes = await consolidateBoundsWithChief(deps, {
2556
3465
  sessionId: rootId,
@@ -2561,7 +3470,7 @@ export async function askOrCommandChief(deps, {
2561
3470
  mutateChiefState((s) => {
2562
3471
  const ws = ensureWorkspace(s, rootId)
2563
3472
  ws.chat.push(
2564
- { id: nextId('chat'), role: 'user', text: input, actions: [], at: Date.now() },
3473
+ { id: nextId('chat'), role: 'user', text: userDisplayText, ...imgMeta, actions: [], at: Date.now() },
2565
3474
  { id: nextId('chat'), role: 'chief', text: consRes.reply, actions: ['呈批浓缩边界'], at: Date.now() },
2566
3475
  )
2567
3476
  if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
@@ -2597,7 +3506,7 @@ export async function askOrCommandChief(deps, {
2597
3506
  mutateChiefState((s) => {
2598
3507
  const ws = ensureWorkspace(s, rootId)
2599
3508
  ws.chat.push(
2600
- { id: nextId('chat'), role: 'user', text: input, actions: [], at: Date.now() },
3509
+ { id: nextId('chat'), role: 'user', text: userDisplayText, ...imgMeta, actions: [], at: Date.now() },
2601
3510
  { id: nextId('chat'), role: 'chief', text: replyText, actions: [], at: Date.now() },
2602
3511
  )
2603
3512
  if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
@@ -2624,6 +3533,8 @@ export async function askOrCommandChief(deps, {
2624
3533
  subject: r.subject || '',
2625
3534
  text: r.text,
2626
3535
  mode: ['steer', 'followup', 'silent'].includes(r.mode) ? r.mode : 'steer',
3536
+ imageBlocks,
3537
+ savedImagePaths,
2627
3538
  })
2628
3539
  relayResults.push(deliv)
2629
3540
  if (deliv.ok) actionBadges.push(`${r.mode === 'steer' ? '插话' : '递话'} → ${deliv.target}`)
@@ -2693,7 +3604,7 @@ export async function askOrCommandChief(deps, {
2693
3604
  }
2694
3605
 
2695
3606
  ws.chat.push(
2696
- { id: nextId('chat'), role: 'user', text: input, actions: [], at: Date.now() },
3607
+ { id: nextId('chat'), role: 'user', text: userDisplayText, ...imgMeta, actions: [], at: Date.now() },
2697
3608
  { id: nextId('chat'), role: 'chief', text: replyText, actions: actionBadges, at: Date.now() },
2698
3609
  )
2699
3610
  if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
@@ -2812,34 +3723,174 @@ export function proposeBoundToChief(deps, { sessionId, callerAgent, by, field, i
2812
3723
  /* -------------------------------------------------------------------------- */
2813
3724
 
2814
3725
  const TURN_REVIEW_SYSTEM = [
2815
- '你是「DSH 参谋长」(宰相级协同中枢)的后台复盘与参谋模块。某个对话刚结束一轮输出。',
2816
- '请阅读最新对话片段、团队状态、当前边界与持久记忆,完成两件事并**只输出一个 JSON 对象**:',
2817
- '1. `memoryChanges`:仅当出现跨轮次持久有效的规矩、分工、关键架构结论或踩坑教训时才新增/修订/删除(精炼一句话);普通干活过程返回 `[]`。严禁保存密码或密钥。',
2818
- '2. `suggestions`(最多 1 条,宁缺毋滥,没有高价值事项必须返回 `[]`):',
2819
- ' - **类型 A · 宰相边界请示 (`"kind": "bound"`)**:若主代理或子代理在本轮**明显撞墙**(如权限拒绝、沙箱越界、目录不可写、某工具/命令严禁调用、环境硬限制),或用户明确提出了某条应长期遵守的工作红线/允许范围,且尚不在「已有全局边界」中 → 生成一条 `bound` 请示,由用户一键批准后正式注入全局边界!',
2820
- ' - **类型 B · 跨对话递话建议 (`"kind": "relay"`)**:若发现明确的跨对话信息差(如子代理刚查清下游急需的关键结论、或某代理偏离目标需纠偏) → 生成一条简明分点的 `relay` 递话建议。',
3726
+ '你是「DSH 参谋长」(宰相级协同与督导中枢)的后台复盘与督导模块。某个对话刚结束一轮输出。',
3727
+ '请阅读最新对话片段、工作区目标、计划步骤、团队状态、生效边界(尤其红线)、持久记忆与当前开启的战术开关,只输出一个 JSON 对象:',
3728
+ '',
3729
+ '1. `memoryChanges`:仅当出现跨轮次持久有效的规矩、分工、关键架构结论或踩坑教训时才新增/修订/删除;普通干活过程返回 `[]`。严禁保存密码或密钥。',
3730
+ '2. `boardOps`:若发现当前 `计划步骤 (Plan)` 明显仍对应旧需求/与最新 `总目标 (Objective)` 严重脱节(stale plan),务必输出 `{ "op": "plan.resetForGoal" }` 或 `{ "op": "plan.set", "steps": [...] }` 自动修正计划;也可更新 `task.update` / `cursor.set`。',
3731
+ '3. `planAssessment`:`{ "stale": true|false, "reason": "…" }`,指明当前计划步骤是否与总目标失配陈旧。',
3732
+ '4. `goalStatus`:仅当处于 Goal 督导模式时重点评估,取值 `"in_progress" | "achieved" | "blocked"`;若 `achieved`,填写简明 `goalSummary` 与实测 `goalEvidence`;若未完成填写 `goalMissing`。',
3733
+ '5. `shouldIntervene` & `interventionText`:当开启「接管督导模式」且主代理停下但总目标仍未完成(或存在计划失配 / 未提供验证证据却自称完成 / 触及红线风险)时,设 `shouldIntervene: true` 并写出清晰简明、可直接投递给 `@lead` 推进下一回合的执行指令;若处于 `strictVerify` 模式但回复无实测输出证据,务必驳回自称完成并要求补跑验证;若开启 `conciseBrief`,督导指令严格限定在 3 条以内要点。若已达成 `achieved` 等待人类结项批示、或正常等待子代理回信/人工决策,设 `shouldIntervene: false`。',
3734
+ '6. `suggestions`(最多 1 条,宁缺毋滥):',
3735
+ ' - `"kind": "bound"`:明显撞墙或发现长期红线时请示注入全局边界;',
3736
+ ' - `"kind": "relay"`:发现明确跨对话信息差时的递话建议。',
2821
3737
  '',
2822
- '输出格式:',
3738
+ '输出格式(严格 JSON):',
2823
3739
  '{',
2824
- ' "memoryChanges": [',
2825
- ' { "op": "add", "category": "discipline|architecture|progress|preference|team", "text": "…" }',
2826
- ' ],',
2827
- ' "suggestions": [',
2828
- ' {',
2829
- ' "kind": "bound 或 relay",',
2830
- ' "boundField": "当 kind=bound 时必填: forbidden|allowed|notes",',
2831
- ' "title": "一句话简明标题(≤26字)",',
2832
- ' "reason": "简要说明撞墙背景或递话原因(≤65字)",',
2833
- ' "target": "当 kind=relay 时填目标 key(如 lead 或子代理名);kind=bound 时填 bounds",',
2834
- ' "targetLabel": "目标显示名(如 主对话 / 禁止红线)",',
2835
- ' "mode": "steer|followup|silent",',
2836
- ' "draftText": "kind=bound 时填精炼的一句话边界条文;kind=relay 时填简明分点的递话内容"',
2837
- ' }',
2838
- ' ]',
3740
+ ' "memoryChanges": [{ "op": "add", "category": "discipline|architecture|progress|preference|team", "text": "…" }],',
3741
+ ' "boardOps": [],',
3742
+ ' "planAssessment": { "stale": false, "reason": "" },',
3743
+ ' "goalStatus": "in_progress",',
3744
+ ' "goalSummary": "",',
3745
+ ' "goalEvidence": "",',
3746
+ ' "goalMissing": "",',
3747
+ ' "shouldIntervene": false,',
3748
+ ' "interventionText": "",',
3749
+ ' "suggestions": []',
2839
3750
  '}',
2840
3751
  ].join('\n')
2841
3752
 
2842
3753
  const reviewTimers = new Map()
3754
+ const COMPACT_POLL_MS = 180
3755
+ const COMPACT_IDLE_WAIT_MS = 15_000
3756
+
3757
+ async function waitUntilAgentIdle(getStatusFn, timeoutMs = COMPACT_IDLE_WAIT_MS, pollMs = COMPACT_POLL_MS) {
3758
+ const deadline = Date.now() + Math.max(200, timeoutMs)
3759
+ while (Date.now() < deadline) {
3760
+ let status = 'idle'
3761
+ try { status = getStatusFn() || 'idle' } catch {}
3762
+ if (status !== 'running') return true
3763
+ await new Promise(resolve => setTimeout(resolve, pollMs))
3764
+ }
3765
+ try {
3766
+ return (getStatusFn() || 'idle') !== 'running'
3767
+ } catch {
3768
+ return false
3769
+ }
3770
+ }
3771
+
3772
+ function measureAgentSessionTokensFallback(agent) {
3773
+ if (!agent || !agent.session) return null
3774
+ try {
3775
+ let totalTokens = 0
3776
+ let seq = 0
3777
+ let contextWindow = 128_000
3778
+ if (typeof agent.session.ownEvents === 'function') {
3779
+ const events = agent.session.ownEvents() || []
3780
+ seq = events.length
3781
+ for (let i = events.length - 1; i >= 0; i -= 1) {
3782
+ const ev = events[i]
3783
+ const usage = ev && (ev.usage || (ev.message && ev.message.usage) || (ev.data && ev.data.usage))
3784
+ if (usage && typeof usage === 'object') {
3785
+ const calc = (Number(usage.inputTokens) || 0)
3786
+ + (Number(usage.cacheReadTokens) || 0)
3787
+ + (Number(usage.outputTokens) || 0)
3788
+ totalTokens = Number(usage.totalTokens) || calc
3789
+ if (Number(usage.contextWindow) > 0) contextWindow = Number(usage.contextWindow)
3790
+ if (totalTokens > 0) break
3791
+ }
3792
+ }
3793
+ }
3794
+ return totalTokens > 0 ? { totalTokens, contextWindow, seq } : null
3795
+ } catch {
3796
+ return null
3797
+ }
3798
+ }
3799
+
3800
+ /**
3801
+ * Post-Turn Auto-Compaction Pipeline (strict safety contract):
3802
+ * 1. NEVER run inside synchronous `turn-stopping` or while agent.status === 'running'. Wait for idle first.
3803
+ * 2. Check token threshold against contextWindow and guard with `lastCompactedSeq`.
3804
+ * 3. Execute `harvestTurnDetailsToArchive` and verify dossier persisted on disk.
3805
+ * 4. ONLY then call `compactSessionNow`!
3806
+ */
3807
+ export async function maybeRunPreCompaction(deps, {
3808
+ agent = null,
3809
+ sessionId = '',
3810
+ rootId: explicitRootId = '',
3811
+ bypassIdleWait = false,
3812
+ } = {}) {
3813
+ const sid = String(sessionId || (agent && agent.id) || '').trim()
3814
+ if (!sid) return { ok: false, skipped: 'no-session' }
3815
+ const rootId = explicitRootId || (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid, agent) : '') || sid
3816
+
3817
+ const state = loadChiefState()
3818
+ const effCfg = resolveWorkspaceConfig(state, rootId)
3819
+ const tactical = normalizeTacticalModes(effCfg.tacticalModes)
3820
+ if (!tactical.autoCompact) return { ok: false, skipped: 'disabled' }
3821
+ if (!deps || typeof deps.compactSessionNow !== 'function') return { ok: false, skipped: 'no-compaction-service' }
3822
+
3823
+ const getStatus = () => {
3824
+ if (typeof deps.getAgentStatus === 'function') return deps.getAgentStatus(sid)
3825
+ return (agent && agent.status) || 'idle'
3826
+ }
3827
+ if (getStatus() === 'running') {
3828
+ if (bypassIdleWait) return { ok: false, skipped: 'running' }
3829
+ const becameIdle = await waitUntilAgentIdle(getStatus)
3830
+ if (!becameIdle) return { ok: false, skipped: 'busy-running' }
3831
+ }
3832
+
3833
+ let usage = null
3834
+ try {
3835
+ usage = typeof deps.measureSessionTokens === 'function'
3836
+ ? await deps.measureSessionTokens(sid, agent)
3837
+ : measureAgentSessionTokensFallback(agent)
3838
+ } catch {}
3839
+ if (!usage || !Number(usage.totalTokens)) {
3840
+ return { ok: false, skipped: 'no-token-usage' }
3841
+ }
3842
+ const contextWindow = Math.max(1000, Number(usage.contextWindow) || 128_000)
3843
+ const totalTokens = Number(usage.totalTokens) || 0
3844
+ const seq = Math.max(0, Math.round(Number(usage.seq) || 0))
3845
+ const ratioPct = (totalTokens / contextWindow) * 100
3846
+ const wsSnapshot = ensureWorkspace(loadChiefState(), rootId)
3847
+ const lastSeq = (wsSnapshot.runtimeGuard && wsSnapshot.runtimeGuard.lastCompactedSeq) || 0
3848
+
3849
+ if (ratioPct < tactical.compactThresholdPct) {
3850
+ return { ok: false, skipped: 'below-threshold', ratioPct: Math.round(ratioPct), thresholdPct: tactical.compactThresholdPct }
3851
+ }
3852
+ if (seq > 0 && seq <= lastSeq) {
3853
+ return { ok: false, skipped: 'already-compacted-seq', seq, lastSeq }
3854
+ }
3855
+
3856
+ // Step 1: High-precision harvest to working archive cabinet BEFORE compaction!
3857
+ const harvest = await harvestTurnDetailsToArchive(deps, {
3858
+ sessionId: rootId,
3859
+ agent,
3860
+ trigger: 'pre-compaction',
3861
+ focusHint: `上下文占用已达 ${Math.round(ratioPct)}%(${totalTokens}/${contextWindow} tokens),压缩前抢救现场细节。`,
3862
+ })
3863
+ if (!harvest || !harvest.ok || !harvest.savedId) {
3864
+ return { ok: false, error: 'harvest-failed-abort-compact', detail: harvest && harvest.error }
3865
+ }
3866
+
3867
+ // Step 2: Double-verify written dossier exists cleanly on disk
3868
+ const targetOpt = archiveTargetForRoot(deps, rootId)
3869
+ const verified = getArchiveDetail(harvest.savedId, rootId, targetOpt)
3870
+ if (!verified || !verified.ok || !verified.item) {
3871
+ return { ok: false, error: 'harvest-verify-failed-abort-compact' }
3872
+ }
3873
+
3874
+ // Step 3: Record compacted seq before triggering host compaction
3875
+ mutateChiefState((s) => {
3876
+ const ws = ensureWorkspace(s, rootId)
3877
+ ws.runtimeGuard.lastCompactedSeq = seq > 0 ? seq : (ws.runtimeGuard.lastCompactedSeq + 1)
3878
+ ws.runtimeGuard.lastCompactedAt = Date.now()
3879
+ })
3880
+
3881
+ // Step 4: Execute compaction safely while agent is idle
3882
+ const cmdId = `dsh-chief-autocompact-${Date.now().toString(36)}`
3883
+ const compactRes = await deps.compactSessionNow(sid, cmdId)
3884
+ if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
3885
+ deps.appendBoardLog(rootId, `🗜️ 已先抢救入柜(#${harvest.savedId})并自动完成上下文压缩(占 ${Math.round(ratioPct)}%)`, 'chief')
3886
+ }
3887
+ return {
3888
+ ok: true,
3889
+ harvestId: harvest.savedId,
3890
+ ratioPct: Math.round(ratioPct),
3891
+ compactRes,
3892
+ }
3893
+ }
2843
3894
 
2844
3895
  function extractLatestTurnDigest(agent, turn) {
2845
3896
  if (!agent || !agent.session) return null
@@ -2882,73 +3933,125 @@ export function scheduleChiefTurnReview(deps, { agent, sessionId, turn }) {
2882
3933
  return
2883
3934
  }
2884
3935
  const state = loadChiefState()
2885
- const paceMode = (state.config && state.config.paceMode) || 'manual'
2886
- // Default 'manual' mode: ZERO automatic background LLM calls! Human controls the rhythm.
2887
- if (paceMode === 'manual' || state.config.autoReview === false) return
2888
-
2889
3936
  const rootKey = (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid, agent) : '') || sid
3937
+ const effCfg = resolveWorkspaceConfig(state, rootKey)
3938
+ const paceMode = effCfg.paceMode || 'manual'
3939
+ const tactical = normalizeTacticalModes(effCfg.tacticalModes)
3940
+ const board = deps && deps.boardForSession && deps.boardFileFor
3941
+ ? deps.boardForSession(deps.boardFileFor(rootKey))
3942
+ : null
3943
+ const isGoalMode = Boolean(board && board.mode === 'goal')
3944
+ const hasHighPriorityChannel = isGoalMode || tactical.autoCompact || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify
3945
+
3946
+ // Default 'manual' mode without tactical/goal active: ZERO background LLM calls!
3947
+ if (!hasHighPriorityChannel && (paceMode === 'manual' || effCfg.autoReview === false)) return
3948
+
2890
3949
  clearTimeout(reviewTimers.get(rootKey))
3950
+ const delayMs = hasHighPriorityChannel ? 1_200 : REVIEW_DELAY_MS
2891
3951
  const timer = setTimeout(() => {
2892
3952
  reviewTimers.delete(rootKey)
2893
3953
  runTurnReview(deps, { agent, sessionId: sid, turn }).catch(() => {})
2894
- }, REVIEW_DELAY_MS)
3954
+ }, delayMs)
2895
3955
  timer.unref?.()
2896
3956
  reviewTimers.set(rootKey, timer)
2897
3957
  }
2898
3958
 
2899
- async function runTurnReview(deps, { agent, sessionId, turn }) {
2900
- const rootId = deps.resolveRootSessionId(sessionId, agent) || sessionId
3959
+ export async function runTurnReview(deps, { agent, sessionId, turn, force = false }) {
3960
+ const sid = String(sessionId || (agent && agent.id) || '').trim()
3961
+ if (!sid) return { ok: false, skipped: 'no-session' }
3962
+ const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sid, agent)) || sid
3963
+
2901
3964
  const stateBefore = loadChiefState()
2902
- const paceMode = (stateBefore.config && stateBefore.config.paceMode) || 'manual'
2903
- if (paceMode === 'manual') return
3965
+ const effCfgBefore = resolveWorkspaceConfig(stateBefore, rootId)
3966
+ const tactical = normalizeTacticalModes(effCfgBefore.tacticalModes)
3967
+ const paceMode = effCfgBefore.paceMode || 'manual'
3968
+ const board = deps.boardForSession && deps.boardFileFor
3969
+ ? deps.boardForSession(deps.boardFileFor(rootId))
3970
+ : null
3971
+ const isGoalMode = Boolean(board && board.mode === 'goal')
3972
+ const hasHighPriority = isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify || tactical.autoCompact
3973
+
3974
+ if (!force && !hasHighPriority && paceMode === 'manual') {
3975
+ return { ok: false, skipped: 'manual' }
3976
+ }
3977
+
3978
+ // Always check pre-compaction pipeline first when autoCompact is active
3979
+ if (tactical.autoCompact) {
3980
+ await maybeRunPreCompaction(deps, { agent, sessionId: sid, rootId, bypassIdleWait: Boolean(force) }).catch(() => {})
3981
+ }
3982
+
3983
+ // If ONLY autoCompact was on and neither paceMode != 'manual' nor supervisor toggles are on, exit cleanly here
3984
+ const needsSupervisorLlm = isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify || paceMode !== 'manual'
3985
+ if (!force && !needsSupervisorLlm) return { ok: true, onlyCompactionChecked: true }
2904
3986
 
2905
3987
  const digest = extractLatestTurnDigest(agent, turn)
2906
- if (!digest || !digest.text) return
3988
+ if (!digest || !digest.text) return { ok: false, skipped: 'no-digest' }
2907
3989
 
2908
3990
  const wsBefore = ensureWorkspace(stateBefore, rootId)
2909
- const cursorKey = `${sessionId}`
2910
- if (wsBefore.reviewCursors[cursorKey] === digest.stamp) return
3991
+ const cursorKey = `${sid}`
3992
+ if (!force && wsBefore.reviewCursors[cursorKey] === digest.stamp) {
3993
+ return { ok: false, skipped: 'same-stamp' }
3994
+ }
2911
3995
 
2912
- const identity = deps.resolveAgentIdentity(deps.runtime, sessionId, agent)
2913
- if (identity && /^mnemon-(?:review|run)/i.test(String(identity.self || ''))) return
3996
+ const identity = deps.resolveAgentIdentity ? deps.resolveAgentIdentity(deps.runtime, sid, agent) : null
3997
+ if (identity && /^mnemon-(?:review|run)/i.test(String(identity.self || ''))) return { ok: false, skipped: 'mnemon' }
2914
3998
 
2915
3999
  const hasWallCue = /(?:permission denied|eacces|eperm|forbidden|blocked|not allowed|sandbox|read-only|撞墙|受阻|权限拒绝|越界)/i.test(digest.text)
2916
4000
  const now = Date.now()
2917
4001
  const lastAt = Number(lastReviewAtByRoot.get(rootId) || 0)
2918
- const cooldownMs = paceMode === 'smart'
2919
- ? (hasWallCue ? 45_000 : SMART_REVIEW_COOLDOWN_MS)
2920
- : AUTO_REVIEW_COOLDOWN_MS
2921
- if (now - lastAt < cooldownMs) return
4002
+ const cooldownMs = hasHighPriority
4003
+ ? 4_000
4004
+ : (paceMode === 'smart' ? (hasWallCue ? 45_000 : SMART_REVIEW_COOLDOWN_MS) : AUTO_REVIEW_COOLDOWN_MS)
4005
+ if (!force && now - lastAt < cooldownMs) return { ok: false, skipped: 'cooldown' }
4006
+
4007
+ // Wait if supervisor intervention/goal is running for an active agent so turn-stopping settles to idle
4008
+ if ((tactical.intervention || isGoalMode) && typeof deps.getAgentStatus === 'function' && !force) {
4009
+ await waitUntilAgentIdle(() => deps.getAgentStatus(sid), 5_000, 150)
4010
+ }
2922
4011
 
2923
4012
  const directory = await listPeerDirectory(deps, rootId)
2924
4013
  const realPeers = directory.targets.filter(t => !/^mnemon-(?:review|run)/i.test(String(t.name || t.handle || '')))
2925
4014
 
2926
- // In 'smart' mode, ONLY review when a hard wall/error cue occurred OR multi-agent milestone with human turn
2927
- if (paceMode === 'smart' && !hasWallCue && !(digest.hasUser && realPeers.length > 1)) {
2928
- return
4015
+ // In 'smart' background mode (without supervisor/goal), gate LLM call on wall cue or multi-agent human turn
4016
+ if (!force && !isGoalMode && !tactical.intervention && !tactical.redlineSentinel && !tactical.strictVerify) {
4017
+ if (paceMode === 'smart' && !hasWallCue && !(digest.hasUser && realPeers.length > 1)) {
4018
+ return { ok: false, skipped: 'smart-quiet' }
4019
+ }
4020
+ if (!digest.hasUser && realPeers.length <= 1 && !hasWallCue) return { ok: false, skipped: 'single-quiet' }
2929
4021
  }
2930
- if (!digest.hasUser && realPeers.length <= 1 && !hasWallCue) return
2931
4022
 
2932
- const modelsInfo = await listChiefModels(deps, false, rootId)
2933
- if (!modelsInfo.available) return
4023
+ if (!deps.callLlmOverride) {
4024
+ const modelsInfo = await listChiefModels(deps, false, rootId)
4025
+ if (!modelsInfo.available) return { ok: false, skipped: 'no-models' }
4026
+ }
2934
4027
 
2935
4028
  lastReviewAtByRoot.set(rootId, now)
2936
4029
  const speaker = identity && identity.isChild ? `子代理 @${identity.self}` : '主对话 (@lead)'
2937
4030
  const view = clusterView(stateBefore, rootId)
2938
4031
  const numberedFacts = view.facts.slice()
2939
- const board = deps.boardForSession && deps.boardFileFor
2940
- ? deps.boardForSession(deps.boardFileFor(rootId))
2941
- : null
2942
4032
  const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
4033
+ const planSteps = Array.isArray(board && board.plan) ? board.plan : []
4034
+ const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
2943
4035
 
2944
4036
  const activeTargets = realPeers.filter(t => t.key === 'lead' || t.status === 'running').slice(0, 10)
2945
4037
  const idleCount = Math.max(0, realPeers.length - activeTargets.length)
4038
+ const activeFlags = [
4039
+ isGoalMode ? 'GOAL_MODE' : '',
4040
+ tactical.intervention ? 'INTERVENTION_SUPERVISOR' : '',
4041
+ tactical.strictVerify ? 'STRICT_VERIFY' : '',
4042
+ tactical.redlineSentinel ? 'REDLINE_SENTINEL' : '',
4043
+ tactical.conciseBrief ? 'CONCISE_BRIEF_3_BULLETS' : '',
4044
+ ].filter(Boolean)
2946
4045
 
2947
4046
  const prompt = [
2948
- `刚刚结束回合的对话身份:${speaker}(sessionId=${sessionId})`,
4047
+ `当前激活监督模式:${activeFlags.join(' | ') || paceMode}`,
4048
+ `工作区总目标 (Objective):${(board && board.objective) || '(暂未设定明确总目标)'}`,
4049
+ `当前计划步骤 (Plan):${planSteps.length ? planSteps.map((s, i) => `${i + 1}.${s.done ? '[✓]' : '[ ]'} ${clamp(s.text, 60)}`).join(';') : '(空)'}`,
4050
+ `当前任务列表 (Tasks):${tasks.length ? tasks.slice(0, 10).map(t => `[${t.status}] #${t.id} ${clamp(t.title, 48)}`).join(';') : '(空)'}`,
4051
+ `刚刚结束回合的对话身份:${speaker}(sessionId=${sid})`,
2949
4052
  `活跃团队成员:${activeTargets.map(t => `${t.handle}[key=${t.key}, ${t.status}${t.taskTitle ? ', 任务:' + t.taskTitle : ''}]`).join(';')}${idleCount > 0 ? `(另有 ${idleCount} 名空闲子代理已折叠)` : ''}`,
2950
4053
  '',
2951
- '已有全局边界(请勿重复提议已有项):',
4054
+ '已有工作边界(红线严防越界,请勿重复提议已有项):',
2952
4055
  `- 禁止:${(bounds.forbidden || []).join(';') || '(暂无)'}`,
2953
4056
  `- 允许:${(bounds.allowed || []).join(';') || '(暂无)'}`,
2954
4057
  `- 注意:${(bounds.notes || []).join(';') || '(暂无)'}`,
@@ -2966,32 +4069,83 @@ async function runTurnReview(deps, { agent, sessionId, turn }) {
2966
4069
  prompt,
2967
4070
  maxTokens: SUMMARY_MAX_TOKENS,
2968
4071
  })
2969
- if (!res.ok) return
4072
+ if (!res.ok) return { ok: false, error: res.error }
2970
4073
 
2971
4074
  const parsed = extractJsonObject(res.text)
2972
- if (!parsed) return
4075
+ if (!parsed) return { ok: false, error: 'non-json-review' }
2973
4076
 
2974
- const autoPilot = Boolean(loadChiefState().config.autoPilot)
4077
+ const autoPilot = Boolean(resolveWorkspaceConfig(loadChiefState(), rootId).autoPilot)
2975
4078
  const rawSuggestions = (Array.isArray(parsed.suggestions) ? parsed.suggestions : [])
2976
4079
  .map(raw => normalizeSuggestion({ ...raw, fromAgent: raw?.fromAgent || speaker }))
2977
4080
  .filter(Boolean)
2978
4081
  .slice(0, 1)
2979
4082
 
2980
- let factsChanged = false
4083
+ // Stale plan check & auto-reconcile
4084
+ const isStalePlan = Boolean(parsed.planAssessment && parsed.planAssessment.stale)
4085
+ const parsedBoardOps = Array.isArray(parsed.boardOps) ? parsed.boardOps.slice() : []
4086
+ if (isStalePlan && !parsedBoardOps.some(op => op && (op.op === 'plan.resetForGoal' || op.op === 'plan.set'))) {
4087
+ parsedBoardOps.unshift({ op: 'plan.resetForGoal' })
4088
+ }
4089
+ const executedOps = parsedBoardOps.length > 0 && deps.runAction
4090
+ ? applyBoardOps(deps, rootId, parsedBoardOps)
4091
+ : []
4092
+
4093
+ const isGoalAchieved = isGoalMode && String(parsed.goalStatus || '') === 'achieved'
4094
+ let goalProposalCreated = false
4095
+ if (isGoalAchieved && deps.runAction) {
4096
+ const existingApproval = board && board.goalApproval
4097
+ const alreadyPendingSame = existingApproval
4098
+ && existingApproval.status === 'pending'
4099
+ && existingApproval.objective === board.objective
4100
+ if (!alreadyPendingSame) {
4101
+ const propRes = deps.runAction({
4102
+ action: 'goal.proposeApproval',
4103
+ objective: board.objective || '',
4104
+ summary: cleanMultiline(parsed.goalSummary || '总目标各项核心要求及验证均已完成,建议结项。', 320),
4105
+ evidence: cleanMultiline(parsed.goalEvidence || '', 420),
4106
+ session: rootId,
4107
+ by: 'DSH 参谋长',
4108
+ })
4109
+ goalProposalCreated = Boolean(propRes && propRes.ok)
4110
+ }
4111
+ }
4112
+
4113
+ let circuitTripped = false
4114
+ let circuitReason = ''
4115
+ let interventionMessage = ''
2981
4116
  const autoRelays = []
2982
4117
 
2983
4118
  mutateChiefState((s) => {
2984
4119
  const ws = ensureWorkspace(s, rootId)
2985
4120
  ws.reviewCursors[cursorKey] = digest.stamp
2986
- const applied = applyFactChanges(ws, numberedFacts, parsed.memoryChanges, speaker)
2987
- if (applied.length > 0) factsChanged = true
4121
+ applyFactChanges(ws, numberedFacts, parsed.memoryChanges, speaker)
4122
+
4123
+ // Goal achieved: create user approval suggestion pill (NEVER exit goal mode automatically!)
4124
+ if (isGoalAchieved) {
4125
+ const hasPendingGoalSug = ws.suggestions.some(
4126
+ sug => sug.status === 'pending' && sug.kind === 'goal_approval',
4127
+ )
4128
+ if (!hasPendingGoalSug) {
4129
+ const goalSug = normalizeSuggestion({
4130
+ kind: 'goal_approval',
4131
+ fromAgent: '🎯 目标督导参谋',
4132
+ title: '🎯 目标已达成,请示批准结项',
4133
+ reason: cleanMultiline(parsed.goalSummary || '主对话已完成当前设定总目标,请批示是否结束督导。', 220),
4134
+ evidence: cleanMultiline(parsed.goalEvidence || '', 480),
4135
+ target: 'board',
4136
+ targetLabel: '目标结项',
4137
+ mode: 'silent',
4138
+ draftText: cleanMultiline(parsed.goalSummary || '批准结项并退出 Goal 督导模式', 400),
4139
+ })
4140
+ if (goalSug) ws.suggestions.push(goalSug)
4141
+ }
4142
+ }
2988
4143
 
2989
4144
  for (const sug of rawSuggestions) {
2990
4145
  if (sug.kind === 'bound') {
2991
4146
  const colList = Array.isArray(bounds[sug.boundField]) ? bounds[sug.boundField] : []
2992
4147
  if (colList.some(x => String(x).trim() === sug.draftText)) continue
2993
4148
  }
2994
- // Prime Minister Rule: Boundary changes NEVER auto-execute without explicit user approval!
2995
4149
  if (autoPilot && sug.kind === 'relay' && sug.draftText) {
2996
4150
  sug.status = 'applied'
2997
4151
  autoRelays.push(sug)
@@ -3004,15 +4158,91 @@ async function runTurnReview(deps, { agent, sessionId, turn }) {
3004
4158
  if (!dup) {
3005
4159
  const pending = ws.suggestions.filter(item => item.status === 'pending')
3006
4160
  if (pending.length >= 5) {
3007
- const victim = pending.find(item => item.kind !== 'bound') || pending[0]
4161
+ const victim = pending.find(item => item.kind !== 'bound' && item.kind !== 'goal_approval') || pending[0]
3008
4162
  victim.status = 'dismissed'
3009
4163
  }
3010
4164
  ws.suggestions.push(sug)
3011
4165
  }
3012
4166
  }
3013
4167
  }
4168
+
4169
+ // Intervention Supervisor follow-up + Circuit Breaker
4170
+ const candidateIntervention = parsed.interventionText
4171
+ || (parsed.nextActionForLead && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress') ? parsed.nextActionForLead : '')
4172
+ if (!isGoalAchieved && tactical.intervention && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress') && candidateIntervention) {
4173
+ const assistantTail = (digest.text.split('Assistant:').pop() || digest.text)
4174
+ const sig = crypto
4175
+ .createHash('sha1')
4176
+ .update(JSON.stringify({
4177
+ objective: (board && board.objective) || '',
4178
+ goalStatus: parsed.goalStatus || '',
4179
+ donePlanCount: planSteps.filter(p => p.done).length,
4180
+ doneTaskCount: tasks.filter(t => t.status === 'done').length,
4181
+ blockedTaskCount: tasks.filter(t => t.status === 'blocked').length,
4182
+ assistantTail: clamp(assistantTail, 140),
4183
+ }))
4184
+ .digest('hex')
4185
+ .slice(0, 12)
4186
+
4187
+ const nextUnchanged = ws.runtimeGuard.lastDigestHash === sig
4188
+ ? (ws.runtimeGuard.unchangedCount + 1)
4189
+ : 1
4190
+ const nextTurns = ws.runtimeGuard.interventionTurns + 1
4191
+ const maxTurns = tactical.maxInterventionTurns || 10
4192
+
4193
+ if (nextTurns > maxTurns || nextUnchanged >= 3) {
4194
+ circuitTripped = true
4195
+ circuitReason = nextTurns > maxTurns
4196
+ ? `接管督导连续介入已达上限 (${maxTurns} 轮),触发安全熔断,已自动退回人工监督。`
4197
+ : '连续 3 轮检测进展无实质变化,触发死循环熔断,已自动关闭接管督导并交还用户控制。'
4198
+ if (!ws.config || typeof ws.config !== 'object') ws.config = resolveWorkspaceConfig(s, rootId)
4199
+ ws.config.tacticalModes = {
4200
+ ...normalizeTacticalModes(ws.config.tacticalModes),
4201
+ intervention: false,
4202
+ }
4203
+ s.config.tacticalModes = {
4204
+ ...normalizeTacticalModes(s.config.tacticalModes),
4205
+ intervention: false,
4206
+ }
4207
+ ws.runtimeGuard.circuitBroken = true
4208
+ ws.runtimeGuard.circuitReason = circuitReason
4209
+ ws.runtimeGuard.interventionTurns = 0
4210
+ ws.runtimeGuard.unchangedCount = 0
4211
+ ws.chat.push({
4212
+ id: nextId('chat'),
4213
+ role: 'chief',
4214
+ text: `- 【⚠️ 安全熔断】${circuitReason}`,
4215
+ actions: ['熔断停机'],
4216
+ at: Date.now(),
4217
+ })
4218
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
4219
+ } else {
4220
+ ws.runtimeGuard.lastDigestHash = sig
4221
+ ws.runtimeGuard.unchangedCount = nextUnchanged
4222
+ ws.runtimeGuard.interventionTurns = nextTurns
4223
+ ws.runtimeGuard.circuitBroken = false
4224
+ ws.runtimeGuard.circuitReason = ''
4225
+ interventionMessage = cleanMultiline(candidateIntervention, tactical.conciseBrief ? 420 : 1200)
4226
+ }
4227
+ }
3014
4228
  })
3015
4229
 
4230
+ if (interventionMessage) {
4231
+ const tags = [
4232
+ tactical.strictVerify ? '严格校验实测' : '',
4233
+ tactical.redlineSentinel ? '红线哨兵巡检' : '',
4234
+ tactical.conciseBrief ? '精炼要点' : '',
4235
+ ].filter(Boolean).join(' · ')
4236
+ await deliverCrossMessage(deps, {
4237
+ fromSession: rootId,
4238
+ fromLabel: `DSH 参谋长 (接管督导${tags ? '·' + tags : ''})`,
4239
+ target: 'lead',
4240
+ subject: '参谋长自动督导推进',
4241
+ text: interventionMessage,
4242
+ mode: 'followup',
4243
+ })
4244
+ }
4245
+
3016
4246
  for (const sug of autoRelays) {
3017
4247
  await deliverCrossMessage(deps, {
3018
4248
  fromSession: rootId,
@@ -3023,7 +4253,17 @@ async function runTurnReview(deps, { agent, sessionId, turn }) {
3023
4253
  mode: sug.mode || 'silent',
3024
4254
  })
3025
4255
  }
3026
- // Never chain an automatic LLM summary right after turn review — human controls summary rhythm!
4256
+
4257
+ return {
4258
+ ok: true,
4259
+ executedOps,
4260
+ isStalePlan,
4261
+ goalAchieved: isGoalAchieved,
4262
+ goalProposalCreated,
4263
+ intervened: Boolean(interventionMessage),
4264
+ circuitTripped,
4265
+ circuitReason,
4266
+ }
3027
4267
  }
3028
4268
 
3029
4269
  export async function handleSuggestionDecision(deps, { sessionId, suggestionId, decision, editedText, boundField, pinGlobal }) {
@@ -3101,6 +4341,33 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
3101
4341
  }
3102
4342
  }
3103
4343
 
4344
+ if (decision === 'approve' && found.kind === 'goal_approval') {
4345
+ const res = deps.runAction
4346
+ ? deps.runAction({ action: 'goal.approve', session: rootId, by: 'user' })
4347
+ : { ok: false, error: 'runAction unavailable' }
4348
+ return {
4349
+ ok: Boolean(res && res.ok),
4350
+ goalApproved: true,
4351
+ view: await getChiefView(deps, rootId, { autoSummarize: false }),
4352
+ }
4353
+ }
4354
+
4355
+ if (decision !== 'approve' && found.kind === 'goal_approval') {
4356
+ const res = deps.runAction
4357
+ ? deps.runAction({
4358
+ action: 'goal.reject',
4359
+ reason: editedText || '暂不结项,继续推进完善',
4360
+ session: rootId,
4361
+ by: 'user',
4362
+ })
4363
+ : { ok: false }
4364
+ return {
4365
+ ok: Boolean(res && res.ok),
4366
+ goalRejected: true,
4367
+ view: await getChiefView(deps, rootId, { autoSummarize: false }),
4368
+ }
4369
+ }
4370
+
3104
4371
  if (decision === 'approve' && found.kind === 'relay') {
3105
4372
  const body = editedText ? cleanMultiline(editedText, 1200) : found.draftText
3106
4373
  const delivery = await deliverCrossMessage(deps, {
@@ -3125,22 +4392,89 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
3125
4392
  }
3126
4393
 
3127
4394
  export function updateChiefConfig(patch) {
4395
+ const safePatch = patch && typeof patch === 'object' ? patch : {}
4396
+ const sid = String(safePatch.sessionId || safePatch.session || '').trim()
3128
4397
  return mutateChiefState((state) => {
3129
- if (typeof patch.modelRef === 'string') state.config.modelRef = patch.modelRef.trim()
3130
- if (typeof patch.paceMode === 'string' && ['manual', 'smart', 'auto'].includes(patch.paceMode)) {
3131
- state.config.paceMode = patch.paceMode
3132
- state.config.autoPilot = patch.paceMode === 'auto'
3133
- state.config.autoReview = patch.paceMode !== 'manual'
3134
- } else if (typeof patch.autoPilot === 'boolean') {
3135
- state.config.paceMode = patch.autoPilot ? 'auto' : 'manual'
3136
- state.config.autoPilot = patch.autoPilot
3137
- state.config.autoReview = patch.autoPilot
3138
- }
3139
- if (typeof patch.autoReview === 'boolean' && typeof patch.paceMode !== 'string') {
3140
- state.config.autoReview = patch.autoReview
3141
- if (!patch.autoReview) state.config.paceMode = 'manual'
3142
- }
3143
- return { ok: true, config: { ...state.config } }
4398
+ const ws = sid ? ensureWorkspace(state, sid) : null
4399
+ const effBefore = resolveWorkspaceConfig(state, sid)
4400
+ const prevTactical = normalizeTacticalModes(effBefore.tacticalModes)
4401
+ if (safePatch.emergencyStopIntervention === true) {
4402
+ if (ws) {
4403
+ if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effBefore }
4404
+ ws.config.tacticalModes = { ...normalizeTacticalModes(ws.config.tacticalModes), intervention: false }
4405
+ ws.runtimeGuard.interventionTurns = 0
4406
+ ws.runtimeGuard.unchangedCount = 0
4407
+ ws.runtimeGuard.circuitBroken = false
4408
+ ws.runtimeGuard.circuitReason = ''
4409
+ }
4410
+ state.config.tacticalModes = { ...normalizeTacticalModes(state.config.tacticalModes), intervention: false }
4411
+ const stoppedCfg = resolveWorkspaceConfig(state, sid)
4412
+ return {
4413
+ ok: true,
4414
+ emergencyStopped: true,
4415
+ config: { ...stoppedCfg, tacticalModes: { ...stoppedCfg.tacticalModes } },
4416
+ }
4417
+ }
4418
+
4419
+ const incomingTactical = safePatch.tacticalModes && typeof safePatch.tacticalModes === 'object'
4420
+ ? safePatch.tacticalModes
4421
+ : null
4422
+ if (incomingTactical && incomingTactical.intervention === true && !prevTactical.intervention) {
4423
+ if (safePatch.confirmedInterventionRisk !== true) {
4424
+ return {
4425
+ ok: false,
4426
+ error: '开启「接管督导模式」需先确认双项风险免责声明(confirmedInterventionRisk: true)',
4427
+ }
4428
+ }
4429
+ if (ws) {
4430
+ ws.runtimeGuard.interventionTurns = 0
4431
+ ws.runtimeGuard.unchangedCount = 0
4432
+ ws.runtimeGuard.circuitBroken = false
4433
+ ws.runtimeGuard.circuitReason = ''
4434
+ }
4435
+ }
4436
+
4437
+ const applyPatchTo = (targetCfg, allowIntervention) => {
4438
+ if (typeof safePatch.modelRef === 'string') targetCfg.modelRef = safePatch.modelRef.trim()
4439
+ if (typeof safePatch.paceMode === 'string' && ['manual', 'smart', 'auto'].includes(safePatch.paceMode)) {
4440
+ targetCfg.paceMode = safePatch.paceMode
4441
+ targetCfg.autoPilot = safePatch.paceMode === 'auto'
4442
+ targetCfg.autoReview = safePatch.paceMode !== 'manual'
4443
+ } else if (typeof safePatch.autoPilot === 'boolean') {
4444
+ targetCfg.paceMode = safePatch.autoPilot ? 'auto' : 'manual'
4445
+ targetCfg.autoPilot = safePatch.autoPilot
4446
+ targetCfg.autoReview = safePatch.autoPilot
4447
+ }
4448
+ if (typeof safePatch.autoReview === 'boolean' && typeof safePatch.paceMode !== 'string') {
4449
+ targetCfg.autoReview = safePatch.autoReview
4450
+ if (!safePatch.autoReview) targetCfg.paceMode = 'manual'
4451
+ }
4452
+ if (incomingTactical) {
4453
+ const merged = normalizeTacticalModes({
4454
+ ...normalizeTacticalModes(targetCfg.tacticalModes),
4455
+ ...incomingTactical,
4456
+ })
4457
+ if (!allowIntervention) merged.intervention = false
4458
+ targetCfg.tacticalModes = merged
4459
+ } else if (!allowIntervention && targetCfg.tacticalModes) {
4460
+ targetCfg.tacticalModes = { ...normalizeTacticalModes(targetCfg.tacticalModes), intervention: false }
4461
+ }
4462
+ }
4463
+
4464
+ if (ws) {
4465
+ if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effBefore }
4466
+ applyPatchTo(ws.config, true)
4467
+ // Keep global non-dangerous defaults aligned while NEVER leaking intervention globally!
4468
+ applyPatchTo(state.config, false)
4469
+ } else {
4470
+ applyPatchTo(state.config, true)
4471
+ }
4472
+
4473
+ const finalCfg = resolveWorkspaceConfig(state, sid)
4474
+ return {
4475
+ ok: true,
4476
+ config: { ...finalCfg, tacticalModes: { ...finalCfg.tacticalModes } },
4477
+ }
3144
4478
  })
3145
4479
  }
3146
4480