dsh-chief 1.6.0 → 1.7.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.
@@ -0,0 +1,709 @@
1
+ /**
2
+ * board-handoff.js — 边界汇总、长程交接单生成与跨会话状态投放部署辅助模块
3
+ *
4
+ * 【核心职责】
5
+ * 为 `board-actions.js` 的 `createBoardActions(deps)` 提供档案归属解析(`archiveTarget`)、
6
+ * 边界聚合(`boundaries`)、叙事交接单推导(`resolveEffectiveHandoff`)、档案摘取收集、
7
+ * 以及跨会话 `deployStateToTargetChief` / `transferChief` 投递实现。
8
+ *
9
+ * 【边界约定】
10
+ * - 无全局可变状态,通过 `createBoardHandoffHelpers(deps, shared)` 与主动作分发器共享纯函数契约。
11
+ */
12
+
13
+ import fs from 'node:fs'
14
+ import { planFromTodos, objectiveFromGoal, planSignature } from './digest.js'
15
+ import { renderHandoff } from './handoff.js'
16
+ import {
17
+ loadChiefState,
18
+ resolveWorkspaceConfig,
19
+ deployChiefWorkspaceState,
20
+ hasValidChiefRiskAck,
21
+ } from './chief.js'
22
+ import {
23
+ resolveProjectKey,
24
+ listArchiveHeaders,
25
+ copyArchivesBetweenSessionsOrCabinets,
26
+ getTakenOutArchivesForSession,
27
+ getTakenOutGlobalForSession,
28
+ getFlippedOutPrecipitatedForSession,
29
+ } from './archives.js'
30
+ import {
31
+ DEFAULT_CHIEF_PERMISSION_MODE,
32
+ normalizePermissionMode,
33
+ } from './chief-executor.js'
34
+ import {
35
+ newId,
36
+ nowMs,
37
+ emptyBoard,
38
+ str,
39
+ asBool,
40
+ normalizeTask,
41
+ BOUND_FIELDS,
42
+ BOUND_CAP,
43
+ normalizeBounds,
44
+ pushLog,
45
+ safe,
46
+ } from './board-schema.js'
47
+
48
+ export function createBoardHandoffHelpers(deps, shared) {
49
+ const agentOf = (...args) => deps.agentOf(...args)
50
+ const boardFile = (...args) => deps.boardFile(...args)
51
+ const boardFileFor = (...args) => deps.boardFileFor(...args)
52
+ const boardForSession = (...args) => deps.boardForSession(...args)
53
+ const clearPending = (...args) => deps.clearPending(...args)
54
+ const clearPendingDeploy = (...args) => deps.clearPendingDeploy(...args)
55
+ const fetchTeamTasks = (...args) => deps.fetchTeamTasks(...args)
56
+ const getSessionCwd = (...args) => deps.getSessionCwd(...args)
57
+ const isInternalProfileCwd = (...args) => deps.isInternalProfileCwd(...args)
58
+ const loadBoard = (...args) => deps.loadBoard(...args)
59
+ const makeChiefDeps = (...args) => deps.makeChiefDeps(...args)
60
+ const readPending = (...args) => deps.readPending(...args)
61
+ const readPendingDeploy = (...args) => deps.readPendingDeploy(...args)
62
+ const resolveBoundRootSid = (...args) => deps.resolveBoundRootSid(...args)
63
+ const resolveRootSessionId = (...args) => deps.resolveRootSessionId(...args)
64
+ const resolveWorkspaceIdForSession = (...args) => deps.resolveWorkspaceIdForSession(...args)
65
+ const saveBoard = (...args) => deps.saveBoard(...args)
66
+ const sessionName = (...args) => deps.sessionName(...args)
67
+ const withBoardLock = (...args) => deps.withBoardLock(...args)
68
+ const writePending = (...args) => deps.writePending(...args)
69
+ const writePendingDeploy = (...args) => deps.writePendingDeploy(...args)
70
+ const isObjectiveLockedByIntervention = (...args) => shared.isObjectiveLockedByIntervention(...args)
71
+
72
+ function boundaries(runtime, sessionId) {
73
+ const wd = runtime.get('workingDirectory')
74
+ const sandboxPolicy = runtime.get('sandboxPolicy')
75
+ const webApp = runtime.get('webApp')
76
+ const tools = runtime.get('tools')
77
+ const file = boardFile()
78
+ const agent = agentOf(runtime, sessionId)
79
+ const session = agent && agent.session ? agent.session : undefined
80
+ const resolvedSessionId = str(agent && agent.id, '') || str(sessionId, '') || null
81
+ const sessionResolved = !!(agent && agent.session)
82
+ return {
83
+ workingDirectory: safe(() => wd.defaultDirectory, process.cwd()),
84
+ sandboxMode: safe(() => sandboxPolicy.defaultMode, 'unknown'),
85
+ workspaceRoot: safe(() => sandboxPolicy.workspaceRoot, null),
86
+ extraWritableRoots: safe(() => sandboxPolicy.additionalWritableRoots, null),
87
+ profile: process.env.DSH_PROFILE || null,
88
+ dshHome: process.env.DSH_HOME || null,
89
+ boardFile: file,
90
+ boardExists: safe(() => fs.existsSync(file), false),
91
+ webUrl: safe(() => webApp.getAdvertisedUrl(), null),
92
+ toolCount: safe(() => tools.definitions().length, null),
93
+ sessionId: resolvedSessionId,
94
+ sessionResolved,
95
+ sessionWorkingDirectory: session ? safe(() => wd.get(session), null) : null,
96
+ sessionSandboxMode: session ? safe(() => sandboxPolicy.resolve({ session }).mode, null) : null,
97
+ sessionSandboxOverride: session ? safe(() => sandboxPolicy.overrideOf(session) ?? null, null) : null,
98
+ liveAgents: safe(() => (runtime.get('agents').list() || []).map(agent => ({
99
+ id: String(agent.id),
100
+ canInject: typeof agent.inject === 'function',
101
+ })), []),
102
+ pendingTransfer: readPending() ? true : false,
103
+ pid: process.pid,
104
+ platform: process.platform,
105
+ node: process.version,
106
+ cwd: process.cwd(),
107
+ }
108
+ }
109
+
110
+ function archiveTarget(runtime, sessionId, optOrId = '') {
111
+ const opts = optOrId && typeof optOrId === 'object'
112
+ ? optOrId
113
+ : { cabinetId: typeof optOrId === 'string' ? optOrId : '' }
114
+ const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
115
+ const sid = String(sessionId || '').trim()
116
+ const rootSid = resolveBoundRootSid(sid)
117
+ let cabinetId = vaultScope !== 'global' && typeof opts.cabinetId === 'string' ? opts.cabinetId.trim() : ''
118
+ if (vaultScope !== 'global' && !cabinetId && rootSid) {
119
+ try {
120
+ cabinetId = loadBoard(boardFileFor(rootSid)).activeCabinetId || ''
121
+ } catch {}
122
+ }
123
+ return {
124
+ customSharedBoardFile: boardFile(),
125
+ cwd: getSessionCwd(runtime, rootSid || (sid !== 'global' ? sid : '')),
126
+ vaultScope,
127
+ ...(vaultScope !== 'global' && rootSid ? { rootSessionId: rootSid } : {}),
128
+ ...(vaultScope !== 'global' && cabinetId ? { cabinetId } : {}),
129
+ }
130
+ }
131
+
132
+ function composeHandoffFromNarrative({ board, narrativeText = '', cluster = [] } = {}) {
133
+ const b = board || emptyBoard()
134
+ const lines = ['# 交接单(参谋长提炼同步版)', '']
135
+ if (b.objective) {
136
+ lines.push('## 总目标', `- ${b.objective}`, '')
137
+ }
138
+ if (b.cursor && (b.cursor.step || b.cursor.next || b.cursor.blocked)) {
139
+ lines.push('## 当前断点', `- 当前步骤:${b.cursor.step || '无'}`, b.cursor.next ? `- 下一步:${b.cursor.next}` : '', b.cursor.blocked ? `- 阻塞点:${b.cursor.blocked}` : '', '')
140
+ }
141
+ if (narrativeText) {
142
+ lines.push('## 参谋长态势研判与进展摘要', narrativeText.trim(), '')
143
+ }
144
+ const openSteps = (b.plan || []).filter(s => s && !s.done)
145
+ if (openSteps.length) {
146
+ lines.push('## 待推进计划', ...openSteps.slice(0, 8).map((s, i) => `${i + 1}. ${s.text}`), '')
147
+ }
148
+ const openTasks = (b.tasks || []).filter(t => t && t.status !== 'done')
149
+ if (openTasks.length) {
150
+ lines.push('## 未完任务', ...openTasks.slice(0, 8).map(t => `- [${t.status}] #${t.id} ${t.title}${t.note ? `(${String(t.note).slice(0, 100)})` : ''}`), '')
151
+ }
152
+ const fb = (b.bounds && b.bounds.forbidden) || []
153
+ const al = (b.bounds && b.bounds.allowed) || []
154
+ const nt = (b.bounds && b.bounds.notes) || []
155
+ if (fb.length || al.length || nt.length) {
156
+ lines.push('## 生效红线与工作边界')
157
+ if (fb.length) lines.push(...fb.slice(0, 6).map(x => `- 🚫 禁止:${x}`))
158
+ if (al.length) lines.push(...al.slice(0, 4).map(x => `- ✅ 必做:${x}`))
159
+ if (nt.length) lines.push(...nt.slice(0, 4).map(x => `- 📌 注意:${x}`))
160
+ lines.push('')
161
+ }
162
+ if (Array.isArray(cluster) && cluster.length > 1) {
163
+ lines.push(`## 当前协同网络`, `- 已联通协同群组共 ${cluster.length} 个独立会话。`, '')
164
+ }
165
+ return lines.filter((l, i, arr) => !(l === '' && arr[i - 1] === '')).join('\n').slice(0, 12000)
166
+ }
167
+
168
+ function resolveEffectiveHandoff(runtime, sessionId, board, extraTeamTasks = undefined) {
169
+ const b = board || emptyBoard()
170
+ const h = b.handoff || {}
171
+ const rootSid = sessionId ? (resolveRootSessionId(sessionId) || sessionId) : ''
172
+ const customText = typeof h.customText === 'string' ? h.customText.trim() : ''
173
+ const pinned = Boolean(h.pinned)
174
+ const syncOnDigest = Boolean(h.syncOnDigest)
175
+
176
+ const teamTasks = extraTeamTasks !== undefined
177
+ ? extraTeamTasks
178
+ : fetchTeamTasks(runtime, sessionId ? { id: sessionId } : null)
179
+ const takenOutArchives = rootSid ? collectTakenOutAndFlipped(runtime, rootSid, b.activeCabinetId) : []
180
+ const autoText = renderHandoff(b, boundaries(runtime, sessionId), 5200, sessionId, {
181
+ teamTasks,
182
+ takenOutArchives,
183
+ })
184
+
185
+ const effectiveText = customText ? h.customText : autoText
186
+ let chiefNarrativeAt = 0
187
+ let chiefNarrativeText = ''
188
+ try {
189
+ const st = loadChiefState()
190
+ const ws = st && st.workspaces && st.workspaces[rootSid || 'global']
191
+ if (ws && ws.narrative && ws.narrative.text) {
192
+ chiefNarrativeText = ws.narrative.text
193
+ chiefNarrativeAt = Number(ws.narrative.at) || 0
194
+ }
195
+ } catch {}
196
+
197
+ const updatedAt = Number(h.updatedAt) || Number(h.at) || 0
198
+ const hasRichWork = Boolean(b.objective || (b.plan && b.plan.length) || (b.tasks && b.tasks.length) || (b.memory && b.memory.length))
199
+ const isIncomplete = !effectiveText.trim() || (!customText && !b.objective && !(b.tasks && b.tasks.length) && !(b.plan && b.plan.length))
200
+ const isStale = !pinned && Boolean(
201
+ hasRichWork && (
202
+ (chiefNarrativeText && h.source !== 'human' && chiefNarrativeAt > updatedAt + 2000)
203
+ || (Number(b.updatedAt) > updatedAt + 60_000 && !customText)
204
+ ),
205
+ )
206
+
207
+ return {
208
+ text: effectiveText,
209
+ autoText,
210
+ source: customText ? (h.source || 'human') : 'auto',
211
+ isCustom: Boolean(customText),
212
+ pinned,
213
+ pinnedAt: Number(h.pinnedAt) || 0,
214
+ pinnedBy: h.pinnedBy || '',
215
+ updatedAt,
216
+ handoffAt: Number(h.at) || 0,
217
+ syncOnDigest,
218
+ isIncomplete,
219
+ isStale,
220
+ hasNarrativeUpdate: Boolean(chiefNarrativeText && chiefNarrativeAt > updatedAt + 2000),
221
+ }
222
+ }
223
+
224
+ /** Combine Session-Cabinet mounted items with explicitly flipped precipitated entries (NEVER reads Global Cabinet!). */
225
+ function collectTakenOutAndFlipped(runtime, rootId, cabinetId = '') {
226
+ if (!rootId) return []
227
+ const targetOpt = archiveTarget(runtime, rootId, { cabinetId, vaultScope: 'session' })
228
+ const working = getTakenOutArchivesForSession(rootId, targetOpt).map(e => ({
229
+ ...e,
230
+ _deskScope: 'session',
231
+ folderLabel: `本局桌面/${e.folder || '档案'}`,
232
+ title: `[桌面强调·本局] ${e.title}`,
233
+ }))
234
+ const globalTargetOpt = archiveTarget(runtime, rootId, { cabinetId: '', vaultScope: 'global' })
235
+ const takenGlobal = getTakenOutGlobalForSession(rootId, globalTargetOpt).map(e => ({
236
+ ...e,
237
+ _deskScope: 'global',
238
+ folderLabel: `全局桌面/${e.folder || '经验'}`,
239
+ title: `[桌面强调·全局] ${e.title}`,
240
+ }))
241
+ const state = loadChiefState()
242
+ const ws = state && state.workspaces && state.workspaces[rootId]
243
+ const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
244
+ let mappedFlipped = []
245
+ if (flippedIds.length) {
246
+ const projectKey = resolveProjectKey(targetOpt.cwd)
247
+ const flippedEntries = getFlippedOutPrecipitatedForSession(projectKey, rootId, true, targetOpt)
248
+ mappedFlipped = flippedEntries.map(e => ({
249
+ ...e,
250
+ _deskScope: 'precipitated',
251
+ folder: e.category || 'contracts',
252
+ folderLabel: `沉淀桌面/${e.category || '经验'}`,
253
+ title: `[桌面强调·沉淀] ${e.title}`,
254
+ }))
255
+ }
256
+ return [...working, ...takenGlobal, ...mappedFlipped]
257
+ }
258
+
259
+ /** Collect digest-safe archive context for Lead/Subagent prompt: ONLY desk-spotlight items + Chief-curated session hooks (0 raw/global/cold leak!). */
260
+ function collectDigestArchiveContext(runtime, rootId, cabinetId = '') {
261
+ const takenOutArchives = rootId ? collectTakenOutAndFlipped(runtime, rootId, cabinetId) : []
262
+ let sessionHookedArchives = []
263
+ let desktopUsedTokens = 0
264
+ if (rootId && rootId !== 'global') {
265
+ try {
266
+ const targetOpt = archiveTarget(runtime, rootId, { cabinetId, vaultScope: 'session' })
267
+ const hdrRes = listArchiveHeaders(rootId, { vaultScope: 'session', includeCounts: false }, targetOpt)
268
+ if (hdrRes && hdrRes.ok) {
269
+ desktopUsedTokens = Number(hdrRes.desktop && hdrRes.desktop.usedTokens) || 0
270
+ sessionHookedArchives = (Array.isArray(hdrRes.items) ? hdrRes.items : [])
271
+ .filter(it => it && it.hasHook && !it.takenOut)
272
+ .slice(0, 6)
273
+ .map(it => ({
274
+ id: it.id,
275
+ title: it.title,
276
+ folder: it.folder,
277
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
278
+ hookCue: it.hookCue || '',
279
+ }))
280
+ }
281
+ } catch {}
282
+ }
283
+ let smartCompactActive = false
284
+ let chiefPermissionMode = DEFAULT_CHIEF_PERMISSION_MODE
285
+ if (rootId) {
286
+ try {
287
+ const st = loadChiefState()
288
+ const cfg = resolveWorkspaceConfig(st, rootId)
289
+ const ws = st && st.workspaces && st.workspaces[rootId]
290
+ const tm = (cfg && cfg.tacticalModes) || {}
291
+ smartCompactActive = Boolean(tm.smartCompact)
292
+ chiefPermissionMode = normalizePermissionMode(cfg && cfg.permissionMode, {
293
+ requireAck: true,
294
+ hasChiefRiskAck: hasValidChiefRiskAck(ws),
295
+ })
296
+ } catch {}
297
+ }
298
+ return { takenOutArchives, sessionHookedArchives, desktopUsedTokens, smartCompactActive, chiefPermissionMode }
299
+ }
300
+
301
+ /* ------------------------------------------------------------------- auto sync */
302
+
303
+ /** todo_write → plan. Skipped when the plan already says the same thing. */
304
+ function syncPlanFromTodos(args, sessionId) {
305
+ const steps = planFromTodos(args)
306
+ if (!steps) return
307
+ const file = boardFileFor(sessionId)
308
+ withBoardLock(file, () => {
309
+ const board = loadBoard(file)
310
+ if (planSignature(board.plan) === planSignature(steps)) return
311
+ board.plan = steps
312
+ saveBoard(board, file)
313
+ })
314
+ }
315
+
316
+ /** create_goal / update_goal → objective. */
317
+ function syncObjective(name, args, sessionId) {
318
+ if (isObjectiveLockedByIntervention(sessionId)) return
319
+ const objective = objectiveFromGoal(name, args)
320
+ if (!objective) return
321
+ const file = boardFileFor(sessionId)
322
+ withBoardLock(file, () => {
323
+ const board = loadBoard(file)
324
+ const wantGoalMode = name === 'create_goal'
325
+ if (board.objective === objective && (!wantGoalMode || board.mode === 'goal')) return
326
+ const previous = board.objective
327
+ board.objective = objective.slice(0, 2000)
328
+ board.objectiveBy = String(sessionId || '')
329
+ board.objectiveAt = nowMs()
330
+ if (wantGoalMode) {
331
+ board.mode = 'goal'
332
+ if (board.goalApproval && board.goalApproval.status !== 'pending') board.goalApproval = null
333
+ }
334
+ board.objectiveUpdatedAt = board.objectiveAt
335
+ pushLog(board, '长期目标改为:' + objective.slice(0, 60) + (previous && previous !== objective ? '(原:' + previous.slice(0, 40) + ')' : ''), 'agent', sessionId)
336
+ saveBoard(board, file)
337
+ })
338
+ }
339
+
340
+ /** Put one packet into exactly one place, because the operator asked for it.
341
+ *
342
+ * Shape matters more than anything else here. The queue in front of an agent
343
+ * records what it was handed, and the session log stores that record verbatim
344
+ * (`agent/inbox/spliced`). A bare string there makes the whole log unloadable
345
+ * ("requires message objects"), and a message without a producer-owned
346
+ * `source.kind` makes the client crash while it resolves submission
347
+ * insertions. So the payload is always a complete message: id, role, content,
348
+ * and a source kind this package owns.
349
+ */
350
+ const HANDOFF_SOURCE = { kind: 'dsh-chief-handoff' }
351
+
352
+ function buildHandoffMessage(text) {
353
+ deps.hostState.handoffSeq += 1
354
+ return {
355
+ id: 'handoff-' + Date.now().toString(36) + '-' + deps.hostState.handoffSeq.toString(36),
356
+ role: 'user',
357
+ content: [{ type: 'text', text }],
358
+ source: { ...HANDOFF_SOURCE },
359
+ }
360
+ }
361
+
362
+ async function injectInto(agent, text) {
363
+ if (!agent || typeof agent.inject !== 'function') {
364
+ return { ok: false, error: '这个 agent 没有 inject 方法' }
365
+ }
366
+ const message = buildHandoffMessage(text)
367
+ const shapes = [message, { content: message.content, source: message.source, role: message.role, id: message.id }]
368
+ for (const shape of shapes) {
369
+ try {
370
+ const result = agent.inject(shape)
371
+ if (result && typeof result.then === 'function') await result
372
+ return { ok: true }
373
+ } catch {}
374
+ }
375
+ return { ok: false, error: 'inject 不接受完整消息形状(纯文本会写坏会话日志,不试)' }
376
+ }
377
+
378
+ /**
379
+ * System-level handover & state deployment to a target Chief workspace (`一键部署参谋`).
380
+ * Copies active objective, mode, plan steps, unfinished tasks (scrubbing stale `doing` / child handles),
381
+ * cursor, bounds, and Chief facts/narrative/chat — while optionally copying working cabinet archives
382
+ * per `archiveTransferPolicy` ('none' | 'mounted' | 'drawer' | 'all') and strictly NEVER leaking precipitated cold vault.
383
+ */
384
+ function deployStateToTargetChief(runtime, {
385
+ fromSessionId = '',
386
+ toSessionId = '',
387
+ archiveTransferPolicy = 'none',
388
+ archiveDrawer = '',
389
+ toCabinetId = '',
390
+ customNote = '',
391
+ } = {}) {
392
+ const fromRoot = resolveRootSessionId(fromSessionId) || String(fromSessionId || '').trim()
393
+ const toRoot = resolveRootSessionId(toSessionId) || String(toSessionId || '').trim()
394
+ if (!fromRoot || !toRoot || fromRoot === toRoot) {
395
+ return { ok: false, error: '跨会话移交需要两个不同的会话 ID' }
396
+ }
397
+
398
+ const srcBoard = boardForSession(boardFileFor(fromRoot))
399
+ const destFile = boardFileFor(toRoot)
400
+ let copiedTaskCount = 0
401
+ let copiedStepCount = 0
402
+
403
+ withBoardLock(destFile, () => {
404
+ const dest = loadBoard(destFile)
405
+ if (srcBoard.objective) {
406
+ dest.objective = srcBoard.objective
407
+ dest.objectiveBy = srcBoard.objectiveBy || fromRoot
408
+ dest.objectiveAt = srcBoard.objectiveAt || nowMs()
409
+ dest.objectiveUpdatedAt = nowMs()
410
+ }
411
+ dest.mode = srcBoard.mode === 'goal' ? 'goal' : 'plan'
412
+ dest.goalApproval = null
413
+
414
+ if (Array.isArray(srcBoard.plan) && srcBoard.plan.length > 0) {
415
+ dest.plan = srcBoard.plan.map(step => ({
416
+ id: step.id || newId('s'),
417
+ text: step.text,
418
+ done: Boolean(step.done),
419
+ }))
420
+ copiedStepCount = dest.plan.length
421
+ }
422
+
423
+ const srcTasks = Array.isArray(srcBoard.tasks) ? srcBoard.tasks : []
424
+ const unfinished = srcTasks.filter(t => t && t.status !== 'done')
425
+ const unfinishedIds = new Set(unfinished.map(t => t.id))
426
+ const existingIds = new Set((dest.tasks || []).map(t => t.id))
427
+ for (const rawTask of unfinished) {
428
+ if (existingIds.has(rawTask.id)) continue
429
+ const remainingBlockers = (rawTask.blockedBy || []).filter(bid => unfinishedIds.has(bid))
430
+ const droppedDoneCount = (rawTask.blockedBy || []).length - remainingBlockers.length
431
+ dest.tasks.push(normalizeTask({
432
+ ...rawTask,
433
+ status: rawTask.status === 'doing' ? 'todo' : rawTask.status,
434
+ session: '',
435
+ subagent: '',
436
+ blockedBy: remainingBlockers,
437
+ note: droppedDoneCount > 0
438
+ ? [rawTask.note, `[接力已自动解除 ${droppedDoneCount} 项已完成前置依赖]`].filter(Boolean).join(' ')
439
+ : rawTask.note,
440
+ updatedAt: nowMs(),
441
+ }))
442
+ copiedTaskCount += 1
443
+ }
444
+
445
+ if (srcBoard.cursor && (srcBoard.cursor.step || srcBoard.cursor.next || srcBoard.cursor.blocked)) {
446
+ dest.cursor = {
447
+ ...srcBoard.cursor,
448
+ at: nowMs(),
449
+ by: 'deploy',
450
+ session: fromRoot,
451
+ }
452
+ }
453
+
454
+ // Merge local non-pinned bounds from source session board into destination session board
455
+ const srcLocal = srcBoard.localBounds || { allowed: [], forbidden: [], notes: [] }
456
+ const destBounds = normalizeBounds(dest.bounds)
457
+ for (const col of BOUND_FIELDS) {
458
+ const merged = new Set(destBounds[col] || [])
459
+ for (const item of (srcLocal[col] || [])) merged.add(item)
460
+ destBounds[col] = [...merged].slice(0, BOUND_CAP)
461
+ }
462
+ dest.bounds = destBounds
463
+
464
+ // Carry non-anchor handoff context notes selectively if target has room
465
+ dest.handoff = {
466
+ at: nowMs(),
467
+ by: 'deploy',
468
+ session: fromRoot,
469
+ customText: '',
470
+ pinned: false,
471
+ pinnedAt: 0,
472
+ pinnedBy: '',
473
+ updatedAt: 0,
474
+ source: 'auto',
475
+ syncOnDigest: false,
476
+ }
477
+ pushLog(
478
+ dest,
479
+ `🚀 已系统级移交部署自会话 ${fromRoot.slice(0, 12)}:计划 ${copiedStepCount} 步、未完任务 ${copiedTaskCount} 项`,
480
+ 'deploy',
481
+ toRoot,
482
+ )
483
+ saveBoard(dest, destFile)
484
+ })
485
+
486
+ const chiefRes = deployChiefWorkspaceState(makeChiefDeps(runtime), {
487
+ fromRootId: fromRoot,
488
+ toRootId: toRoot,
489
+ fromTitle: sessionName(runtime, fromRoot) || fromRoot,
490
+ customText: customNote,
491
+ objective: srcBoard.objective || '',
492
+ })
493
+
494
+ let archiveCopyRes = { ok: true, policy: 'none', copiedCount: 0 }
495
+ const policy = ['none', 'mounted', 'drawer', 'all'].includes(archiveTransferPolicy)
496
+ ? archiveTransferPolicy
497
+ : 'none'
498
+ if (policy !== 'none') {
499
+ archiveCopyRes = copyArchivesBetweenSessionsOrCabinets({
500
+ fromRootSessionId: fromRoot,
501
+ toRootSessionId: toRoot,
502
+ fromCwd: getSessionCwd(runtime, fromRoot),
503
+ toCwd: getSessionCwd(runtime, toRoot),
504
+ fromCabinetId: srcBoard.activeCabinetId || '',
505
+ toCabinetId: toCabinetId || loadBoard(boardFileFor(toRoot)).activeCabinetId || '',
506
+ policy,
507
+ drawer: archiveDrawer,
508
+ customSharedBoardFile: boardFile(),
509
+ })
510
+ }
511
+
512
+ return {
513
+ ok: true,
514
+ fromSessionId: fromRoot,
515
+ toSessionId: toRoot,
516
+ copiedTaskCount,
517
+ copiedStepCount,
518
+ chiefDeployed: chiefRes,
519
+ archiveTransfer: archiveCopyRes,
520
+ }
521
+ }
522
+
523
+ async function transferChief(runtime, args, sessionId) {
524
+ const passed = args && typeof args === 'object' ? args : {}
525
+ const target = typeof passed.target === 'string' ? passed.target.trim() : 'new'
526
+ const deployChief = asBool(passed.deployChief) !== false
527
+ const archiveTransferPolicy = ['none', 'mounted', 'drawer', 'all'].includes(str(passed.archiveTransferPolicy, 'none'))
528
+ ? str(passed.archiveTransferPolicy, 'none')
529
+ : 'none'
530
+ const archiveDrawer = str(passed.archiveDrawer, '')
531
+ const toCabinetId = str(passed.toCabinetId, '')
532
+ const customNote = str(passed.customNote, '')
533
+
534
+ const board = boardForSession(boardFileFor(sessionId))
535
+ const rootSid = resolveRootSessionId(sessionId) || sessionId
536
+ const packet = resolveEffectiveHandoff(runtime, sessionId, board).text
537
+ const by = typeof passed.by === 'string' && passed.by ? passed.by : 'user'
538
+
539
+ if (!target || target === 'new' || target === 'latest') {
540
+ if (!writePending({ at: nowMs(), by, session: sessionId, text: packet })) {
541
+ return { ok: false, error: '待领取文件写入失败' }
542
+ }
543
+ if (deployChief && rootSid) {
544
+ writePendingDeploy({
545
+ at: nowMs(),
546
+ by,
547
+ fromSessionId: rootSid,
548
+ archiveTransferPolicy,
549
+ archiveDrawer,
550
+ toCabinetId,
551
+ customNote,
552
+ })
553
+ }
554
+ const owner = boardFileFor(sessionId)
555
+ withBoardLock(owner, () => {
556
+ const next = loadBoard(owner)
557
+ pushLog(next, '交接单与参谋接力包已投放:等下一个新会话自动部署领取', by, sessionId)
558
+ saveBoard(next, owner)
559
+ })
560
+ return { ok: true, mode: 'pending', deployQueued: deployChief, text: packet }
561
+ }
562
+
563
+ if (target === 'create') {
564
+ const controller = runtime.get('sessionController')
565
+ const parked = writePending({ at: nowMs(), by, session: sessionId, text: packet })
566
+ if (!parked) return { ok: false, error: '待领取文件写入失败' }
567
+ if (deployChief && rootSid) {
568
+ writePendingDeploy({
569
+ at: nowMs(),
570
+ by,
571
+ fromSessionId: rootSid,
572
+ archiveTransferPolicy,
573
+ archiveDrawer,
574
+ toCabinetId,
575
+ customNote,
576
+ })
577
+ }
578
+ if (!controller || typeof controller.create !== 'function') {
579
+ return { ok: false, error: '这个部署没有 sessionController,交接单已放进待领取', mode: 'pending', text: packet }
580
+ }
581
+ const matchedWorkspaceId = resolveWorkspaceIdForSession(runtime, rootSid || sessionId)
582
+ const srcCwd = getSessionCwd(runtime, rootSid || sessionId)
583
+ const fallbackCwdReq = srcCwd && !isInternalProfileCwd(srcCwd) ? { cwd: srcCwd } : {}
584
+ const createReq = matchedWorkspaceId ? { workspaceId: matchedWorkspaceId } : fallbackCwdReq
585
+
586
+ let created
587
+ try {
588
+ created = await controller.create(createReq)
589
+ } catch (error) {
590
+ if (createReq.workspaceId) {
591
+ try {
592
+ created = await controller.create(fallbackCwdReq)
593
+ } catch (fallbackErr) {
594
+ return {
595
+ ok: false,
596
+ error: '唤起新会话失败:' + String((fallbackErr && fallbackErr.message) || fallbackErr),
597
+ mode: 'pending',
598
+ text: packet,
599
+ }
600
+ }
601
+ } else {
602
+ return {
603
+ ok: false,
604
+ error: '唤起新会话失败:' + String((error && error.message) || error),
605
+ mode: 'pending',
606
+ text: packet,
607
+ }
608
+ }
609
+ }
610
+ const createdId = str(created && created.sessionId, '')
611
+ if (!createdId) return { ok: false, error: '新会话没有返回 id', mode: 'pending', text: packet }
612
+
613
+ let deployResult = null
614
+ if (deployChief && rootSid && readPendingDeploy()) {
615
+ clearPendingDeploy()
616
+ deployResult = deployStateToTargetChief(runtime, {
617
+ fromSessionId: rootSid,
618
+ toSessionId: createdId,
619
+ archiveTransferPolicy,
620
+ archiveDrawer,
621
+ toCabinetId,
622
+ customNote,
623
+ })
624
+ }
625
+
626
+ const owner = boardFileFor(sessionId)
627
+ if (!readPending()) {
628
+ withBoardLock(owner, () => {
629
+ const next = loadBoard(owner)
630
+ pushLog(next, '交接单与参谋已由新会话 ' + createdId.replace(/^session-/, '').slice(0, 8) + ' 领取部署', by, sessionId)
631
+ saveBoard(next, owner)
632
+ })
633
+ return { ok: true, mode: 'created', sessionId: createdId, delivered: true, deployResult, text: packet }
634
+ }
635
+ const agents = runtime.get('agents')
636
+ const fresh = agents && typeof agents.get === 'function' ? agents.get(createdId) : undefined
637
+ const delivered = fresh ? await injectInto(fresh, packet) : { ok: false, error: '新会话还没有活的 agent,交接单留在待领取' }
638
+ if (delivered.ok) clearPending()
639
+ withBoardLock(owner, () => {
640
+ const next = loadBoard(owner)
641
+ pushLog(
642
+ next,
643
+ (delivered.ok ? '交接单与参谋已部署至新会话 ' : '新会话已建(交接单仍待领取):') + createdId.replace(/^session-/, '').slice(0, 8),
644
+ by,
645
+ sessionId,
646
+ )
647
+ saveBoard(next, owner)
648
+ })
649
+ return { ok: delivered.ok, mode: delivered.ok ? 'created' : 'pending', sessionId: createdId, deployResult, text: packet }
650
+ }
651
+
652
+ let deployResult = null
653
+ if (deployChief && rootSid && target !== rootSid) {
654
+ deployResult = deployStateToTargetChief(runtime, {
655
+ fromSessionId: rootSid,
656
+ toSessionId: target,
657
+ archiveTransferPolicy,
658
+ archiveDrawer,
659
+ toCabinetId,
660
+ customNote,
661
+ })
662
+ }
663
+
664
+ const agents = runtime.get('agents')
665
+ const agent = agents && typeof agents.get === 'function' ? agents.get(target) : undefined
666
+ if (!agent) {
667
+ writePending({ at: nowMs(), by, session: sessionId, text: packet, failedTarget: target })
668
+ return {
669
+ ok: Boolean(deployResult && deployResult.ok),
670
+ error: deployResult && deployResult.ok ? '' : '目标会话没有活的 agent:已改成待领取,下次新会话可取',
671
+ mode: 'pending',
672
+ deployResult,
673
+ text: packet,
674
+ }
675
+ }
676
+ const delivered = await injectInto(agent, packet)
677
+ const owner = boardFileFor(sessionId)
678
+ withBoardLock(owner, () => {
679
+ const next = loadBoard(owner)
680
+ pushLog(
681
+ next,
682
+ (delivered.ok ? '交接单与参谋已投放到会话 ' : '投放失败(' + delivered.error + '):') + String(target).replace(/^session-/, '').slice(0, 8),
683
+ by,
684
+ sessionId,
685
+ )
686
+ saveBoard(next, owner)
687
+ })
688
+ if (!delivered.ok) {
689
+ writePending({ at: nowMs(), by, session: sessionId, text: packet, failedTarget: target })
690
+ return { ok: false, error: delivered.error, mode: 'pending', deployResult, text: packet }
691
+ }
692
+ return { ok: true, mode: 'injected', target, deployResult, text: packet }
693
+ }
694
+
695
+ return {
696
+ boundaries,
697
+ archiveTarget,
698
+ composeHandoffFromNarrative,
699
+ resolveEffectiveHandoff,
700
+ collectTakenOutAndFlipped,
701
+ collectDigestArchiveContext,
702
+ syncPlanFromTodos,
703
+ syncObjective,
704
+ buildHandoffMessage,
705
+ injectInto,
706
+ deployStateToTargetChief,
707
+ transferChief,
708
+ }
709
+ }