dsh-chief 1.2.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1950 @@
1
+ /**
2
+ * board-actions.js
3
+ *
4
+ * Board action dispatcher, boundary facts, handoff resolution, and cross-session deployment.
5
+ */
6
+
7
+ import fs from 'node:fs'
8
+ import { planFromTodos, objectiveFromGoal, planSignature } from './digest.js'
9
+ import { renderHandoff } from './handoff.js'
10
+ import { appendMemory, answerMemory, normalizeMemory } from './memory.js'
11
+ import {
12
+ loadChiefState,
13
+ resolveWorkspaceConfig,
14
+ deployChiefWorkspaceState,
15
+ hasValidChiefRiskAck,
16
+ } from './chief.js'
17
+ import {
18
+ resolveProjectKey,
19
+ getArchiveDetail,
20
+ searchArchives,
21
+ mutateArchive,
22
+ copyArchivesBetweenSessionsOrCabinets,
23
+ getTakenOutArchivesForSession,
24
+ getTakenOutGlobalForSession,
25
+ getFlippedOutPrecipitatedForSession,
26
+ } from './archives.js'
27
+ import {
28
+ DEFAULT_CHIEF_PERMISSION_MODE,
29
+ normalizePermissionMode,
30
+ verifyBoundsWriteAuth,
31
+ listGuardWalls,
32
+ mutateGuardWalls,
33
+ } from './chief-executor.js'
34
+ import {
35
+ enforceAnchorCap,
36
+ STATUSES,
37
+ PRIORITIES,
38
+ newId,
39
+ nowMs,
40
+ emptyBoard,
41
+ LEADING_MARKER,
42
+ str,
43
+ CAP_TASK_TITLE,
44
+ CAP_TASK_NOTE,
45
+ CAP_TASK_INTENT,
46
+ CAP_TASK_EVIDENCE,
47
+ CAP_ASSUMPTION,
48
+ CAP_NOTE_TITLE,
49
+ CAP_NOTE_BODY,
50
+ CAP_PLAN_STEP,
51
+ CAP_OBJECTIVE,
52
+ CAP_CURSOR,
53
+ CAP_LOG_TEXT,
54
+ CAP_MEMORY_TITLE,
55
+ CAP_MEMORY_TEXT,
56
+ clipInto,
57
+ clipped,
58
+ asBool,
59
+ asCount,
60
+ asList,
61
+ normalizeTags,
62
+ normalizeTask,
63
+ reconcileTaskDependencies,
64
+ normalizeNote,
65
+ BOUND_FIELDS,
66
+ normalizeBoundFieldName,
67
+ BOUND_CAP,
68
+ normalizeList,
69
+ normalizeBounds,
70
+ guardCount,
71
+ pushLog,
72
+ safe,
73
+ summary,
74
+ } from './board-schema.js'
75
+
76
+ export function createBoardActions(deps) {
77
+
78
+ const agentOf = (...args) => deps.agentOf(...args)
79
+ const boardFile = (...args) => deps.boardFile(...args)
80
+ const boardFileFor = (...args) => deps.boardFileFor(...args)
81
+ const boardForSession = (...args) => deps.boardForSession(...args)
82
+ const clearPending = (...args) => deps.clearPending(...args)
83
+ const clearPendingDeploy = (...args) => deps.clearPendingDeploy(...args)
84
+ const fetchTeamTasks = (...args) => deps.fetchTeamTasks(...args)
85
+ const getSessionCwd = (...args) => deps.getSessionCwd(...args)
86
+ const isInternalProfileCwd = (...args) => deps.isInternalProfileCwd(...args)
87
+ const loadBoard = (...args) => deps.loadBoard(...args)
88
+ const makeChiefDeps = (...args) => deps.makeChiefDeps(...args)
89
+ const readPending = (...args) => deps.readPending(...args)
90
+ const readPendingDeploy = (...args) => deps.readPendingDeploy(...args)
91
+ const resolveBoundRootSid = (...args) => deps.resolveBoundRootSid(...args)
92
+ const resolveRootSessionId = (...args) => deps.resolveRootSessionId(...args)
93
+ const resolveWorkspaceIdForSession = (...args) => deps.resolveWorkspaceIdForSession(...args)
94
+ const saveBoard = (...args) => deps.saveBoard(...args)
95
+ const sessionName = (...args) => deps.sessionName(...args)
96
+ const withBoardLock = (...args) => deps.withBoardLock(...args)
97
+ const writePending = (...args) => deps.writePending(...args)
98
+ const writePendingDeploy = (...args) => deps.writePendingDeploy(...args)
99
+
100
+ /* ------------------------------------------------------------- one operation */
101
+
102
+ /**
103
+ * The single operation surface shared by the browser routes and the model
104
+ * tools. Every mutation returns `{ ok, board }` or `{ ok: false, error }`.
105
+ */
106
+ /* Reads never take the lock: loadBoard already caches by mtime and a torn read
107
+ * is impossible (the file is replaced by rename). Every mutation does, so two
108
+ * writers cannot both read the same board and have the later rename throw the
109
+ * earlier one's append away. */
110
+ /* Writes that belong to the machine rather than to the Session that asked.
111
+ * settings are read by every surface, and an anchor note is worth nothing unless
112
+ * a Session that never saw this board can read it: both are promises made to the
113
+ * whole machine, so both land on the shared board whatever the caller passed.
114
+ * Deciding it here instead of trusting scope keeps a caller that forgets the flag
115
+ * from writing a local copy nothing reads — which is exactly how a pinned note
116
+ * used to become a dead flag (pinned=true, no anchor tag, no shared copy). */
117
+ function forcesShared(action, args) {
118
+ if (str(args.scope, '') === 'shared') return true
119
+ if (action === 'settings.set') return true
120
+ if (!str(args.session, '') && action.startsWith('bounds.')) return true
121
+ // note.write only becomes machine-wide when it claims to pin.
122
+ return action === 'note.write' && asBool(args.pinned) === true
123
+ }
124
+
125
+ /** Check whether Strong Intervention (`主动强介入`) is active and locks `board.objective` for a session tree. */
126
+ function isObjectiveLockedByIntervention(sessionId) {
127
+ const rawSid = str(sessionId, '').trim()
128
+ if (!rawSid) return false
129
+ try {
130
+ const rootSid = resolveRootSessionId(rawSid) || rawSid
131
+ const cfg = resolveWorkspaceConfig(loadChiefState(), rootSid)
132
+ return Boolean(cfg && cfg.tacticalModes && cfg.tacticalModes.intervention === true)
133
+ } catch {
134
+ return false
135
+ }
136
+ }
137
+
138
+ function runAction(input) {
139
+ const args = input && typeof input === 'object' ? input : {}
140
+ const action = str(args.action, 'snapshot')
141
+ if (
142
+ action === 'snapshot'
143
+ || action === 'memory.ask'
144
+ || action === 'archive.search'
145
+ || action === 'archive.read'
146
+ || action === 'archive.save'
147
+ ) {
148
+ return runActionUnlocked(args)
149
+ }
150
+ // Machine-wide writes (settings, pinned anchors) are forced onto the shared
151
+ // board here rather than trusting the caller to pass scope, because the panel
152
+ // never does: a settings write that landed on a session board would flip the
153
+ // checkbox and change nothing at runtime, and a pinned note that landed there
154
+ // would be an anchor no fresh Session could ever read.
155
+ const shared = forcesShared(action, args)
156
+ const session = str(args.session, '')
157
+ const file = shared ? boardFile() : boardFileFor(session)
158
+ return withBoardLock(file, () => runActionUnlocked(args))
159
+ }
160
+
161
+ function runActionUnlocked(input) {
162
+ const args = input && typeof input === 'object' ? input : {}
163
+ const action = str(args.action, 'snapshot')
164
+ const by = str(args.by, 'agent')
165
+ const session = str(args.session, '')
166
+ const shared = forcesShared(action, args)
167
+ const file = shared ? boardFile() : boardFileFor(session)
168
+
169
+ // Session-scoped Engineering Archives: Lead/Subagents may ONLY access THIS session's cabinet (never global or unflipped precipitated!).
170
+ if (action === 'archive.search') {
171
+ const q = str(args.query !== undefined ? args.query : (args.question !== undefined ? args.question : args.text), '')
172
+ const folder = str(args.folder, '')
173
+ const rootSid = resolveRootSessionId(session) || session
174
+ if (!rootSid) {
175
+ return {
176
+ ok: true,
177
+ archiveSearch: { ok: true, totalArchives: 0, matchCount: 0, hits: [], unboundSession: true },
178
+ board: emptyBoard(),
179
+ }
180
+ }
181
+ const res = searchArchives(q, { folder, limit: 10, vaultScope: 'session' }, archiveTarget(deps.hostState.activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
182
+ return {
183
+ ok: true,
184
+ archiveSearch: res,
185
+ board: session ? loadBoard(file) : emptyBoard(),
186
+ }
187
+ }
188
+
189
+ if (action === 'archive.read') {
190
+ const target = str(args.archiveId !== undefined ? args.archiveId : (args.id !== undefined ? args.id : args.title), '').trim()
191
+ if (!target) return { ok: false, error: 'archive.read requires archiveId, id, or title' }
192
+ const rootSid = resolveRootSessionId(session) || session
193
+ if (!rootSid) return { ok: false, error: '当前未绑定对话会话,无法读取本会话档案柜' }
194
+ const res = getArchiveDetail(target, rootSid, archiveTarget(deps.hostState.activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
195
+ if (!res.ok) return { ok: false, error: res.error }
196
+ return {
197
+ ok: true,
198
+ archiveItem: res.item,
199
+ board: session ? loadBoard(file) : emptyBoard(),
200
+ }
201
+ }
202
+
203
+ if (action === 'archive.save') {
204
+ const rootSid = resolveRootSessionId(session) || session
205
+ if (!rootSid) return { ok: false, error: '当前未绑定对话会话,无法保存到本会话档案柜' }
206
+ const res = mutateArchive({
207
+ op: 'save',
208
+ vaultScope: 'session',
209
+ archiveId: str(args.archiveId !== undefined ? args.archiveId : args.id, ''),
210
+ title: str(args.title, ''),
211
+ body: typeof args.body === 'string' ? args.body : undefined,
212
+ summary: str(args.summary, ''),
213
+ folder: str(args.folder, ''),
214
+ paperclip: str(args.paperclip, ''),
215
+ tags: asList(args.tags),
216
+ points: Array.isArray(args.points) ? args.points : undefined,
217
+ by,
218
+ rootSessionId: rootSid,
219
+ }, archiveTarget(deps.hostState.activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
220
+ if (!res.ok) return { ok: false, error: res.error }
221
+ if (session) {
222
+ withBoardLock(file, () => {
223
+ const b = loadBoard(file)
224
+ pushLog(b, '🗄️ 归档工程记忆:' + String(res.item.title).slice(0, 50), by, session)
225
+ saveBoard(b, file)
226
+ })
227
+ }
228
+ return {
229
+ ok: true,
230
+ archiveSaved: res.item,
231
+ board: session ? loadBoard(file) : emptyBoard(),
232
+ }
233
+ }
234
+
235
+ // A caller with no Session is an unbound surface (blank new conversation,
236
+ // hero state): reads must see an empty board — never the shared anchors —
237
+ // and writes have nowhere legitimate to land, so they fail loudly instead
238
+ // of silently polluting the shared board.
239
+ if (!session && !shared) {
240
+ if (action === 'snapshot') return { ok: true, board: emptyBoard() }
241
+ return { ok: false, error: 'no session bound — the board is per-session now' }
242
+ }
243
+
244
+ if (action === 'snapshot') return { ok: true, board: loadBoard(file) }
245
+
246
+ const board = loadBoard(file)
247
+
248
+ if (action === 'task.reset') {
249
+ const mode = str(args.mode, 'clear').trim().toLowerCase()
250
+ const hadCount = Array.isArray(board.tasks) ? board.tasks.length : 0
251
+ if (mode === 'reopen') {
252
+ board.tasks = (board.tasks || []).map(t => ({
253
+ ...t,
254
+ status: 'todo',
255
+ evidence: '',
256
+ updatedAt: nowMs(),
257
+ }))
258
+ reconcileTaskDependencies(board, by, session)
259
+ pushLog(board, '已将本会话全部任务重置为待推进(共 ' + board.tasks.length + ' 项)', by, session)
260
+ } else {
261
+ board.tasks = []
262
+ if (asBool(args.alsoResetPlan) === true) {
263
+ board.plan = []
264
+ board.cursor = { at: nowMs(), step: '', next: '', blocked: '', by, session }
265
+ }
266
+ pushLog(board, '已重设清空本会话任务列表(原 ' + hadCount + ' 项)', by, session)
267
+ }
268
+ return { ok: true, clearedTasks: hadCount, mode, board: saveBoard(board, file) }
269
+ }
270
+
271
+ if (action === 'task.add') {
272
+ const title = str(args.title, '').trim()
273
+ if (!title) return { ok: false, error: 'title required' }
274
+ const clips = []
275
+ const ownerVal = str(args.subagent || args.target || args.owner, by)
276
+ const task = normalizeTask({
277
+ id: str(args.id, '') ? str(args.id, '').slice(0, 64) : newId('t'),
278
+ title: clipInto(clips, 'task.title', title, CAP_TASK_TITLE),
279
+ note: clipInto(clips, 'task.note', str(args.note, ''), CAP_TASK_NOTE),
280
+ status: STATUSES.includes(args.status) ? args.status : 'todo',
281
+ priority: PRIORITIES.includes(args.priority) ? args.priority : 'normal',
282
+ owner: ownerVal,
283
+ subagent: str(args.subagent || args.target, ''),
284
+ preset: str(args.preset, ''),
285
+ session,
286
+ intent: clipInto(clips, 'task.intent', str(args.intent, ''), CAP_TASK_INTENT),
287
+ evidence: clipInto(clips, 'task.evidence', str(args.evidence, ''), CAP_TASK_EVIDENCE),
288
+ blockedBy: Array.isArray(args.blockedBy) ? args.blockedBy : (typeof args.blockedBy === 'string' && args.blockedBy ? args.blockedBy.split(',').map(s => s.trim()) : []),
289
+ parentId: str(args.parentId, '').slice(0, 200),
290
+ assumptions: str(args.assumption, '') ? [{ text: str(args.assumption, '').slice(0, CAP_ASSUMPTION), verified: false, verifiedAt: 0, note: '' }] : [],
291
+ createdAt: nowMs(),
292
+ updatedAt: nowMs(),
293
+ })
294
+ board.tasks.push(task)
295
+ reconcileTaskDependencies(board, by, session)
296
+ pushLog(board, '新建任务:' + task.title, by, session)
297
+ return clipped({ ok: true, task, board: saveBoard(board, file) }, clips)
298
+ }
299
+
300
+ if (action === 'graph.plan' || action === 'task.batch') {
301
+ const clips = []
302
+ if (typeof args.objective === 'string' && args.objective.trim()) {
303
+ if (isObjectiveLockedByIntervention(session) && asBool(args._fromInterventionSetup) !== true) {
304
+ if (args.objective.trim() !== String(board.objective || '').trim()) {
305
+ pushLog(board, '🔒 主动强介入已锁定核心目标,忽略本次任务图目标改写', by, session)
306
+ }
307
+ } else {
308
+ board.objective = clipInto(clips, 'objective', args.objective.trim(), CAP_OBJECTIVE)
309
+ board.objectiveBy = session
310
+ board.objectiveAt = nowMs()
311
+ }
312
+ }
313
+ const rawList = Array.isArray(args.tasks) ? args.tasks : (Array.isArray(args.nodes) ? args.nodes : [])
314
+ if (!rawList.length) return { ok: false, error: 'graph.plan requires a non-empty tasks array' }
315
+
316
+ if (asBool(args.replace) === true) {
317
+ board.tasks = []
318
+ }
319
+
320
+ const keyMap = new Map()
321
+ for (const existing of board.tasks) {
322
+ keyMap.set(existing.id, existing.id)
323
+ }
324
+
325
+ const staged = []
326
+ for (let i = 0; i < rawList.length; i += 1) {
327
+ const item = rawList[i] && typeof rawList[i] === 'object' ? rawList[i] : { title: String(rawList[i] || '') }
328
+ const title = str(item.title, '').trim()
329
+ if (!title) continue
330
+ const rawKey = str(item.id || item.key, '').trim()
331
+ const existing = rawKey ? board.tasks.find(t => t.id === rawKey) : null
332
+ const realId = existing ? existing.id : (rawKey && /^[a-zA-Z0-9_-]{1,40}$/.test(rawKey) && !keyMap.has(rawKey) ? rawKey : newId('t'))
333
+ if (rawKey) keyMap.set(rawKey, realId)
334
+ keyMap.set(realId, realId)
335
+ staged.push({ item, existing, realId, title })
336
+ }
337
+
338
+ const touchedTasks = []
339
+ for (const { item, existing, realId, title } of staged) {
340
+ const rawParent = str(item.parentId || item.parent, '').trim()
341
+ const resolvedParent = rawParent ? (keyMap.get(rawParent) || rawParent) : ''
342
+ const rawDeps = Array.isArray(item.blockedBy)
343
+ ? item.blockedBy
344
+ : (typeof item.blockedBy === 'string' && item.blockedBy ? item.blockedBy.split(',').map(s => s.trim()) : [])
345
+ const resolvedDeps = rawDeps
346
+ .map(d => str(d, '').trim())
347
+ .filter(Boolean)
348
+ .map(d => keyMap.get(d) || d)
349
+ .filter(d => d !== realId)
350
+
351
+ const ownerVal = str(item.subagent || item.target || item.owner, existing ? existing.owner : '')
352
+ const subagentVal = str(item.subagent || item.target || (ownerVal && ownerVal !== 'agent' && ownerVal !== 'operator' ? ownerVal : ''), existing ? existing.subagent : '')
353
+
354
+ if (existing) {
355
+ existing.title = clipInto(clips, 'task.title', title, CAP_TASK_TITLE)
356
+ if (typeof item.note === 'string') existing.note = clipInto(clips, 'task.note', item.note, CAP_TASK_NOTE)
357
+ if (typeof item.intent === 'string') existing.intent = clipInto(clips, 'task.intent', item.intent, CAP_TASK_INTENT)
358
+ if (typeof item.evidence === 'string') existing.evidence = clipInto(clips, 'task.evidence', item.evidence, CAP_TASK_EVIDENCE)
359
+ if (ownerVal) existing.owner = ownerVal.slice(0, 200)
360
+ if (subagentVal) existing.subagent = subagentVal.slice(0, 120)
361
+ if (typeof item.preset === 'string') existing.preset = item.preset.slice(0, 80)
362
+ if (rawParent || item.parentId === '') existing.parentId = resolvedParent.slice(0, 200)
363
+ if (item.blockedBy !== undefined) existing.blockedBy = resolvedDeps
364
+ if (STATUSES.includes(item.status)) existing.status = item.status
365
+ if (PRIORITIES.includes(item.priority)) existing.priority = item.priority
366
+ existing.updatedAt = nowMs()
367
+ touchedTasks.push(existing)
368
+ } else {
369
+ const created = normalizeTask({
370
+ id: realId,
371
+ title: clipInto(clips, 'task.title', title, CAP_TASK_TITLE),
372
+ note: clipInto(clips, 'task.note', str(item.note, ''), CAP_TASK_NOTE),
373
+ status: STATUSES.includes(item.status) ? item.status : 'todo',
374
+ priority: PRIORITIES.includes(item.priority) ? item.priority : 'normal',
375
+ owner: ownerVal,
376
+ subagent: subagentVal,
377
+ preset: str(item.preset, ''),
378
+ session,
379
+ intent: clipInto(clips, 'task.intent', str(item.intent, ''), CAP_TASK_INTENT),
380
+ evidence: clipInto(clips, 'task.evidence', str(item.evidence, ''), CAP_TASK_EVIDENCE),
381
+ blockedBy: resolvedDeps,
382
+ parentId: resolvedParent,
383
+ assumptions: str(item.assumption, '') ? [{ text: str(item.assumption, '').slice(0, CAP_ASSUMPTION), verified: false, verifiedAt: 0, note: '' }] : [],
384
+ createdAt: nowMs(),
385
+ updatedAt: nowMs(),
386
+ })
387
+ board.tasks.push(created)
388
+ touchedTasks.push(created)
389
+ }
390
+ }
391
+
392
+ reconcileTaskDependencies(board, by, session)
393
+ if (!board.plan.length && board.tasks.length) {
394
+ const roots = board.tasks.filter(t => !t.parentId)
395
+ board.plan = (roots.length ? roots : board.tasks).slice(0, 12).map(t => ({
396
+ id: 's-' + t.id,
397
+ text: t.title + (t.owner ? ' (@' + t.owner + ')' : ''),
398
+ done: t.status === 'done',
399
+ }))
400
+ }
401
+ pushLog(board, '规划任务图:共更新/新增 ' + touchedTasks.length + ' 个任务节点', by, session)
402
+ return clipped({ ok: true, tasks: touchedTasks, board: saveBoard(board, file) }, clips)
403
+ }
404
+
405
+ if (action === 'task.update' || action === 'task.claim' || action === 'task.release' || action === 'task.remove') {
406
+ const id = str(args.taskId !== undefined ? args.taskId : args.id, '')
407
+ const index = board.tasks.findIndex(task => task.id === id)
408
+ if (index < 0) return { ok: false, error: 'no such task: ' + id }
409
+ const task = board.tasks[index]
410
+ const clips = []
411
+
412
+ if (action === 'task.remove') {
413
+ board.tasks.splice(index, 1)
414
+ for (const other of board.tasks) {
415
+ if (other.parentId === id) other.parentId = task.parentId || ''
416
+ if (Array.isArray(other.blockedBy) && other.blockedBy.includes(id)) {
417
+ other.blockedBy = other.blockedBy.filter(depId => depId !== id)
418
+ }
419
+ }
420
+ reconcileTaskDependencies(board, by, session)
421
+ pushLog(board, '删除任务:' + task.title, by, session)
422
+ return { ok: true, board: saveBoard(board, file) }
423
+ }
424
+ if (action === 'task.claim') {
425
+ const unresolved = (task.blockedBy || []).filter(depId => {
426
+ const dep = board.tasks.find(t => t.id === depId)
427
+ return dep && dep.status !== 'done'
428
+ })
429
+ if (unresolved.length) {
430
+ return { ok: false, error: 'blocked by ' + unresolved.join(', ') + ' — finish or remove those first' }
431
+ }
432
+ task.owner = str(args.owner, by)
433
+ task.session = session || task.session
434
+ task.status = 'doing'
435
+ task.updatedAt = nowMs()
436
+ pushLog(board, '接手任务:' + task.title, by, session)
437
+ return { ok: true, task, board: saveBoard(board, file) }
438
+ }
439
+ if (action === 'task.release') {
440
+ task.owner = ''
441
+ task.subagent = ''
442
+ task.session = ''
443
+ if (task.status === 'doing') task.status = 'todo'
444
+ task.updatedAt = nowMs()
445
+ reconcileTaskDependencies(board, by, session)
446
+ pushLog(board, '释放任务:' + task.title, by, session)
447
+ return { ok: true, task, board: saveBoard(board, file) }
448
+ }
449
+ if (typeof args.title === 'string' && args.title.trim()) task.title = clipInto(clips, 'task.title', args.title.trim(), CAP_TASK_TITLE)
450
+ if (typeof args.note === 'string') task.note = clipInto(clips, 'task.note', args.note, CAP_TASK_NOTE)
451
+ if (typeof args.intent === 'string') task.intent = clipInto(clips, 'task.intent', args.intent, CAP_TASK_INTENT)
452
+ if (typeof args.evidence === 'string') task.evidence = clipInto(clips, 'task.evidence', args.evidence, CAP_TASK_EVIDENCE)
453
+ if (Array.isArray(args.blockedBy)) task.blockedBy = args.blockedBy.map(item => str(item, '')).filter(Boolean)
454
+ else if (typeof args.blockedBy === 'string') task.blockedBy = args.blockedBy.split(',').map(s => s.trim()).filter(Boolean)
455
+ if (typeof args.assumption === 'string' && args.assumption.trim()) {
456
+ task.assumptions.push({ text: clipInto(clips, 'task.assumption', args.assumption.trim(), CAP_ASSUMPTION), verified: false, verifiedAt: 0, note: '' })
457
+ }
458
+ if (typeof args.parentId === 'string') task.parentId = args.parentId.trim().slice(0, 200)
459
+ if (typeof args.owner === 'string') task.owner = str(args.owner, '').slice(0, 200)
460
+ if (typeof args.target === 'string') {
461
+ task.owner = str(args.target, '').slice(0, 200)
462
+ task.subagent = str(args.target, '').slice(0, 120)
463
+ }
464
+ if (typeof args.subagent === 'string') {
465
+ task.subagent = str(args.subagent, '').slice(0, 120)
466
+ if (!args.owner) task.owner = task.subagent
467
+ }
468
+ if (typeof args.preset === 'string') task.preset = str(args.preset, '').slice(0, 80)
469
+ if (typeof args.session === 'string') task.session = str(args.session, '').slice(0, 200)
470
+ const prevStatus = task.status
471
+ if (STATUSES.includes(args.status)) task.status = args.status
472
+ if (PRIORITIES.includes(args.priority)) task.priority = args.priority
473
+ task.updatedAt = nowMs()
474
+ const unlocked = reconcileTaskDependencies(board, by, session)
475
+ if (prevStatus !== task.status) {
476
+ pushLog(board, '任务状态更新:#' + task.id + ' ' + task.title.slice(0, 40) + ' → ' + task.status + (task.evidence && task.status === 'done' ? '(验证:' + task.evidence.slice(0, 50) + ')' : ''), by, session)
477
+ // Sync corresponding plan step if present
478
+ const step = (board.plan || []).find(s => s.id === 's-' + task.id || s.text.startsWith(task.title))
479
+ if (step) step.done = task.status === 'done'
480
+ }
481
+ return clipped({ ok: true, task, unlocked, board: saveBoard(board, file) }, clips)
482
+ }
483
+
484
+ if (action === 'task.verify') {
485
+ const id = str(args.taskId !== undefined ? args.taskId : args.id, '')
486
+ const task = board.tasks.find(t => t.id === id)
487
+ if (!task) return { ok: false, error: 'no such task: ' + id }
488
+ const idx = typeof args.assumptionIndex === 'number' ? args.assumptionIndex : -1
489
+ if (idx < 0 || idx >= task.assumptions.length) return { ok: false, error: 'no such assumption index: ' + idx + ' (task has ' + task.assumptions.length + ')' }
490
+ task.assumptions[idx].verified = true
491
+ task.assumptions[idx].verifiedAt = nowMs()
492
+ if (typeof args.note === 'string') task.assumptions[idx].note = str(args.note, '').slice(0, CAP_ASSUMPTION)
493
+ task.updatedAt = nowMs()
494
+ pushLog(board, '验证假设:' + task.title + ' #' + idx + ' — ' + task.assumptions[idx].text.slice(0, 60), by, session)
495
+ return { ok: true, task, board: saveBoard(board, file) }
496
+ }
497
+
498
+ if (action === 'plan.set') {
499
+ const clips = []
500
+ if (typeof args.objective === 'string') {
501
+ if (isObjectiveLockedByIntervention(session) && asBool(args._fromInterventionSetup) !== true) {
502
+ if (args.objective.trim() !== String(board.objective || '').trim()) {
503
+ pushLog(board, '🔒 主动强介入已锁定核心目标,保留原核心目标(仅更新计划步骤)', by, session)
504
+ }
505
+ } else {
506
+ board.objective = clipInto(clips, 'objective', args.objective, CAP_OBJECTIVE)
507
+ // Whoever writes the objective owns it. Leaving the previous owner in
508
+ // place made the panel header name the Session that set the *old* text,
509
+ // so a fresh save looked like it came from somebody else.
510
+ board.objectiveBy = session
511
+ board.objectiveAt = nowMs()
512
+ // objective.set logged this write and plan.set did not, so retargeting a
513
+ // board through plan.set left no trace in the log: the objective page
514
+ // said the goal had changed and the log page said nothing had happened.
515
+ // One action, two entry points, one line either way.
516
+ pushLog(board, '目标改为:' + board.objective.slice(0, 60), by, session)
517
+ }
518
+ }
519
+ const steps = asList(args.steps)
520
+ if (steps) {
521
+ board.plan = steps
522
+ .map(raw => {
523
+ // A bare string in a flattened list is one step, not a step with no
524
+ // text: the old shape filtered it out and wiped the plan.
525
+ const step = typeof raw === 'string' ? { text: raw } : (raw && typeof raw === 'object' ? raw : {})
526
+ return {
527
+ id: str(step.id, newId('s')),
528
+ text: clipInto(clips, 'plan.step', str(step.text, ''), CAP_PLAN_STEP),
529
+ done: asBool(step.done) === true,
530
+ }
531
+ })
532
+ .filter(step => step.text !== '')
533
+ }
534
+ return clipped({ ok: true, board: saveBoard(board, file) }, clips)
535
+ }
536
+
537
+ if (action === 'mode.set') {
538
+ const mode = str(args.mode, '').trim().toLowerCase()
539
+ if (mode !== 'plan' && mode !== 'goal') return { ok: false, error: 'mode must be plan or goal' }
540
+ const before = board.mode === 'goal' ? 'goal' : 'plan'
541
+ board.mode = mode
542
+ if (mode === 'goal') {
543
+ if (board.goalApproval && board.goalApproval.status !== 'pending') {
544
+ board.goalApproval = null
545
+ }
546
+ } else if (board.goalApproval && board.goalApproval.status === 'pending') {
547
+ board.goalApproval = null
548
+ }
549
+ if (before !== mode) {
550
+ pushLog(
551
+ board,
552
+ '模式改为:' + mode + (mode === 'goal' ? '(开启长期目标持续督导)' : '(回到按步规划推进)'),
553
+ by,
554
+ session,
555
+ )
556
+ }
557
+ return { ok: true, mode, board: saveBoard(board, file) }
558
+ }
559
+
560
+ if (action === 'plan.resetForGoal') {
561
+ const hadSteps = Array.isArray(board.plan) ? board.plan.length : 0
562
+ board.plan = []
563
+ board.cursor = {
564
+ at: nowMs(),
565
+ step: '',
566
+ next: '',
567
+ blocked: '',
568
+ by,
569
+ session,
570
+ }
571
+ pushLog(board, `已清空陈旧计划步骤(原 ${hadSteps} 步),等待按最新总目标重编`, by, session)
572
+ return { ok: true, clearedSteps: hadSteps, board: saveBoard(board, file) }
573
+ }
574
+
575
+ if (action === 'goal.proposeApproval') {
576
+ const obj = str(args.objective, board.objective).trim().slice(0, 600)
577
+ const summary = str(args.summary, '当前总目标要求已全部完成并已核验,请用户批准结项。').trim().slice(0, 600)
578
+ const evidence = str(args.evidence, '').trim().slice(0, 800)
579
+ // Crucial: keep board.mode === 'goal' until the user explicitly approves!
580
+ board.goalApproval = {
581
+ id: newId('ga'),
582
+ status: 'pending',
583
+ objective: obj,
584
+ summary,
585
+ evidence,
586
+ rejectReason: '',
587
+ at: nowMs(),
588
+ decidedAt: 0,
589
+ }
590
+ pushLog(board, '🎯 参谋长判定目标已达成,呈请用户批准结项:' + summary.slice(0, 60), by, session)
591
+ return { ok: true, goalApproval: board.goalApproval, board: saveBoard(board, file) }
592
+ }
593
+
594
+ if (action === 'goal.approve') {
595
+ const prev = board.goalApproval || { id: newId('ga'), objective: board.objective, summary: '', evidence: '', at: nowMs() }
596
+ board.goalApproval = {
597
+ ...prev,
598
+ status: 'approved',
599
+ rejectReason: '',
600
+ decidedAt: nowMs(),
601
+ }
602
+ board.mode = 'plan'
603
+ appendMemory(board, {
604
+ section: '验证结论',
605
+ title: '🎯 目标结项批准:' + String(prev.objective || board.objective || '阶段目标').slice(0, 60),
606
+ text: prev.summary || '用户已批准目标结项并切换回按步规划模式',
607
+ by,
608
+ session,
609
+ })
610
+ pushLog(board, '✅ 用户已批准目标结项,已退出 Goal 督导模式', by, session)
611
+ return { ok: true, goalApproval: board.goalApproval, mode: board.mode, board: saveBoard(board, file) }
612
+ }
613
+
614
+ if (action === 'goal.reject') {
615
+ const reason = str(args.reason, '仍需继续推进完善').trim().slice(0, 300)
616
+ const prev = board.goalApproval || { id: newId('ga'), objective: board.objective, summary: '', evidence: '', at: nowMs() }
617
+ board.goalApproval = {
618
+ ...prev,
619
+ status: 'rejected',
620
+ rejectReason: reason,
621
+ decidedAt: nowMs(),
622
+ }
623
+ board.mode = 'goal'
624
+ pushLog(board, '↩ 用户驳回结项批示(继续 Goal 督导):' + reason.slice(0, 60), by, session)
625
+ return { ok: true, goalApproval: board.goalApproval, mode: board.mode, board: saveBoard(board, file) }
626
+ }
627
+
628
+ if (action === 'settings.set') {
629
+ const next = board.settings || { autoInject: true, guardIdle: true }
630
+ const auto = asBool(args.autoInject)
631
+ const guard = asBool(args.guardIdle)
632
+ const maxPerSession = asCount(args.guardMaxPerSession)
633
+ const shortAnswer = asCount(args.guardShortAnswer)
634
+ if (auto !== undefined) next.autoInject = auto
635
+ if (guard !== undefined) next.guardIdle = guard
636
+ if (maxPerSession !== undefined) next.guardMaxPerSession = guardCount(maxPerSession, 3, 0, 20)
637
+ if (shortAnswer !== undefined) next.guardShortAnswer = guardCount(shortAnswer, 600, 0, 10000)
638
+ board.settings = next
639
+ const parts = []
640
+ if (auto !== undefined) parts.push('每轮自动摘要 = ' + (next.autoInject ? '开' : '关'))
641
+ if (guard !== undefined) parts.push('空转拦截 = ' + (next.guardIdle ? '开' : '关'))
642
+ if (maxPerSession !== undefined) parts.push('每会话最多催 = ' + next.guardMaxPerSession + ' 次')
643
+ if (shortAnswer !== undefined) parts.push('短回答门槛 = ' + next.guardShortAnswer + ' 字')
644
+ if (parts.length) pushLog(board, '设置:' + parts.join(';') + '(下一轮就生效)', by, session)
645
+ return { ok: true, settings: next, board: saveBoard(board, file) }
646
+ }
647
+
648
+ if (action === 'objective.set') {
649
+ if (isObjectiveLockedByIntervention(session) && asBool(args._fromInterventionSetup) !== true) {
650
+ return {
651
+ ok: false,
652
+ locked: true,
653
+ error: '当前处于「主动强介入」模式,核心目标已锁定;如需修改请先关闭强介入模式。',
654
+ }
655
+ }
656
+ const objective = str(args.objective, '').trim()
657
+ if (!objective) return { ok: false, error: 'objective required' }
658
+ const clips = []
659
+ const changed = board.objective !== objective
660
+ board.objective = clipInto(clips, 'objective', objective, CAP_OBJECTIVE)
661
+ board.objectiveBy = session
662
+ board.objectiveAt = nowMs()
663
+ board.objectiveUpdatedAt = board.objectiveAt
664
+ if (asBool(args.setGoalMode) === true) {
665
+ board.mode = 'goal'
666
+ }
667
+ if (changed && board.goalApproval && board.goalApproval.status !== 'pending') {
668
+ board.goalApproval = null
669
+ }
670
+ if (asBool(args.resetStalePlan) === true) {
671
+ board.plan = []
672
+ board.cursor = { at: nowMs(), step: '', next: '', blocked: '', by, session }
673
+ }
674
+ pushLog(
675
+ board,
676
+ (asBool(args.setGoalMode) === true ? '🎯 设为督导目标:' : '目标改为:') + objective.slice(0, 60),
677
+ by,
678
+ session,
679
+ )
680
+ return clipped({ ok: true, board: saveBoard(board, file) }, clips)
681
+ }
682
+
683
+ if (action === 'bounds.set') {
684
+ const auth = verifyBoundsWriteAuth({
685
+ action,
686
+ field: args.field,
687
+ callerOrigin: args._callerOrigin || '',
688
+ humanConfirmToken: args._humanConfirmToken || null,
689
+ })
690
+ if (!auth.ok) {
691
+ return { ok: false, blockedBySafetyGuard: true, rule: auth.rule, error: auth.error }
692
+ }
693
+ const current = board.bounds || { allowed: [], forbidden: [], notes: [] }
694
+ // A partial list that looks complete is the worst of the three options: the
695
+ // caller walks away believing it imposed 25 restrictions while the board
696
+ // holds 20. Refusing says so, and says that nothing was written, so the
697
+ // retry is a decision the caller makes rather than a mystery to debug.
698
+ const overCap = list => Array.isArray(list) && list.length > BOUND_CAP
699
+ const tooLongNote = length => 'bounds list too long: ' + length + ' entries, ' + BOUND_CAP
700
+ + ' is the cap — nothing was written; trim the list or split it, then send it again'
701
+ // One column at a time is the safer shape, and the one the panel uses.
702
+ // The three-list form below can only say "here are three lists", so a
703
+ // caller whose local copy happened to be empty (a blank conversation is
704
+ // answered with an empty board) wipes the two columns it never touched.
705
+ // Naming the column makes "this list is now empty" and "I did not touch
706
+ // that list" two different sentences.
707
+ const items = asList(args.items)
708
+ const explicitCol = normalizeBoundFieldName(args.field)
709
+ if (explicitCol && items) {
710
+ if (overCap(items)) return { ok: false, error: tooLongNote(items.length) }
711
+ current[explicitCol] = normalizeList(items)
712
+ board.bounds = current
713
+ pushLog(board, '更新边界(必做 ' + current.allowed.length + ' / 禁止 ' + current.forbidden.length + ' / 注意 ' + current.notes.length + ')', by, session)
714
+ return { ok: true, bounds: current, board: saveBoard(board, file) }
715
+ }
716
+ // The whole-table form checks every list it was handed before touching
717
+ // any of them: a refusal must leave the two valid columns alone as well,
718
+ // otherwise the error message and the board disagree about what happened.
719
+ const given = { allowed: asList(args.allowed !== undefined ? args.allowed : args.must), forbidden: asList(args.forbidden), notes: asList(args.notes) }
720
+ const tooLong = BOUND_FIELDS.filter(name => overCap(given[name]))
721
+ if (tooLong.length) {
722
+ return {
723
+ ok: false,
724
+ error: 'bounds list too long: ' + tooLong.map(name => name + ' has ' + given[name].length).join(', ')
725
+ + ', ' + BOUND_CAP + ' is the cap — nothing was written; trim or split those lists, then send them again',
726
+ }
727
+ }
728
+ if (given.allowed) current.allowed = normalizeList(given.allowed)
729
+ if (given.forbidden) current.forbidden = normalizeList(given.forbidden)
730
+ if (given.notes) current.notes = normalizeList(given.notes)
731
+ board.bounds = current
732
+ pushLog(board, '更新边界(必做 ' + current.allowed.length + ' / 禁止 ' + current.forbidden.length + ' / 注意 ' + current.notes.length + ')', by, session)
733
+ return { ok: true, bounds: current, board: saveBoard(board, file) }
734
+ }
735
+
736
+ if (action === 'bounds.add' || action === 'bounds.pin' || action === 'bounds.remove' || action === 'bounds.edit' || action === 'bounds.consolidate') {
737
+ const auth = verifyBoundsWriteAuth({
738
+ action,
739
+ field: args.field,
740
+ callerOrigin: args._callerOrigin || '',
741
+ humanConfirmToken: args._humanConfirmToken || null,
742
+ })
743
+ if (!auth.ok) {
744
+ return { ok: false, blockedBySafetyGuard: true, rule: auth.rule, error: auth.error }
745
+ }
746
+ const col = normalizeBoundFieldName(args.field)
747
+ if (!col) {
748
+ return { ok: false, error: 'bounds operation requires field: allowed (必做) | forbidden (禁止) | notes (注意)' }
749
+ }
750
+ const sharedFile = boardFile()
751
+ const isSameFile = file === sharedFile
752
+ const localBounds = normalizeBounds(board.bounds)
753
+
754
+ if (action === 'bounds.add') {
755
+ const val = str(args.item !== undefined ? args.item : args.text, '').trim().slice(0, 400)
756
+ if (!val) return { ok: false, error: 'bounds.add requires non-empty item' }
757
+ const pin = asBool(args.pinned) === true || isSameFile
758
+
759
+ if (pin) {
760
+ let capErr = ''
761
+ withBoardLock(sharedFile, () => {
762
+ const sb = isSameFile ? board : loadBoard(sharedFile)
763
+ const sBounds = normalizeBounds(sb.bounds)
764
+ if (!sBounds[col].includes(val)) {
765
+ if (sBounds[col].length >= BOUND_CAP) {
766
+ capErr = 'bounds list too long: ' + BOUND_CAP + ' is the cap'
767
+ return
768
+ }
769
+ sBounds[col].push(val)
770
+ sb.bounds = sBounds
771
+ if (!isSameFile) {
772
+ pushLog(sb, '📌 新增全局共享边界(' + col + '):' + val.slice(0, 50), by, session)
773
+ saveBoard(sb, sharedFile)
774
+ }
775
+ }
776
+ })
777
+ if (capErr) return { ok: false, error: capErr }
778
+ if (!isSameFile) {
779
+ localBounds[col] = localBounds[col].filter(x => x !== val)
780
+ board.bounds = localBounds
781
+ }
782
+ pushLog(board, '📌 定住全局边界(' + col + '):' + val.slice(0, 50), by, session)
783
+ return { ok: true, pinned: true, item: val, board: saveBoard(board, file) }
784
+ }
785
+
786
+ const sharedSnap = normalizeBounds(loadBoard(sharedFile).bounds)
787
+ if (!sharedSnap[col].includes(val) && !localBounds[col].includes(val)) {
788
+ if (sharedSnap[col].length + localBounds[col].length >= BOUND_CAP) {
789
+ return { ok: false, error: 'bounds list too long: ' + BOUND_CAP + ' is the cap' }
790
+ }
791
+ localBounds[col].push(val)
792
+ board.bounds = localBounds
793
+ pushLog(board, '新增本任务边界(' + col + '):' + val.slice(0, 50), by, session)
794
+ }
795
+ return { ok: true, pinned: false, item: val, board: saveBoard(board, file) }
796
+ }
797
+
798
+ if (action === 'bounds.pin') {
799
+ const val = str(args.item !== undefined ? args.item : args.text, '').trim().slice(0, 400)
800
+ if (!val) return { ok: false, error: 'bounds.pin requires item' }
801
+ const pin = asBool(args.pinned) !== false
802
+
803
+ if (pin) {
804
+ let capErr = ''
805
+ withBoardLock(sharedFile, () => {
806
+ const sb = isSameFile ? board : loadBoard(sharedFile)
807
+ const sBounds = normalizeBounds(sb.bounds)
808
+ if (!sBounds[col].includes(val)) {
809
+ if (sBounds[col].length >= BOUND_CAP) {
810
+ capErr = 'bounds list too long: ' + BOUND_CAP + ' is the cap'
811
+ return
812
+ }
813
+ sBounds[col].push(val)
814
+ sb.bounds = sBounds
815
+ if (!isSameFile) {
816
+ pushLog(sb, '📌 定住全局共享边界(' + col + '):' + val.slice(0, 50), by, session)
817
+ saveBoard(sb, sharedFile)
818
+ }
819
+ }
820
+ })
821
+ if (capErr) return { ok: false, error: capErr }
822
+ if (!isSameFile) {
823
+ localBounds[col] = localBounds[col].filter(x => x !== val)
824
+ board.bounds = localBounds
825
+ }
826
+ pushLog(board, '📌 已定住为全局共享边界:' + val.slice(0, 50), by, session)
827
+ return { ok: true, pinned: true, item: val, board: saveBoard(board, file) }
828
+ }
829
+
830
+ // Unpin: remove from global shared board, demote onto current session's local board so this task keeps it
831
+ withBoardLock(sharedFile, () => {
832
+ const sb = isSameFile ? board : loadBoard(sharedFile)
833
+ const sBounds = normalizeBounds(sb.bounds)
834
+ if (sBounds[col].includes(val)) {
835
+ sBounds[col] = sBounds[col].filter(x => x !== val)
836
+ sb.bounds = sBounds
837
+ if (!isSameFile) {
838
+ pushLog(sb, '取消全局定住边界(' + col + '):' + val.slice(0, 50), by, session)
839
+ saveBoard(sb, sharedFile)
840
+ }
841
+ }
842
+ })
843
+ if (!isSameFile) {
844
+ if (!localBounds[col].includes(val) && localBounds[col].length < BOUND_CAP) {
845
+ localBounds[col].push(val)
846
+ }
847
+ board.bounds = localBounds
848
+ }
849
+ pushLog(board, '取消全局定住(改为仅当前任务生效):' + val.slice(0, 50), by, session)
850
+ return { ok: true, pinned: false, item: val, board: saveBoard(board, file) }
851
+ }
852
+
853
+ if (action === 'bounds.remove') {
854
+ const val = str(args.item !== undefined ? args.item : args.text, '').trim()
855
+ if (!val) return { ok: false, error: 'bounds.remove requires item' }
856
+ withBoardLock(sharedFile, () => {
857
+ const sb = isSameFile ? board : loadBoard(sharedFile)
858
+ const sBounds = normalizeBounds(sb.bounds)
859
+ if (sBounds[col].includes(val)) {
860
+ sBounds[col] = sBounds[col].filter(x => x !== val)
861
+ sb.bounds = sBounds
862
+ if (!isSameFile) saveBoard(sb, sharedFile)
863
+ }
864
+ })
865
+ if (!isSameFile) {
866
+ localBounds[col] = localBounds[col].filter(x => x !== val)
867
+ board.bounds = localBounds
868
+ }
869
+ pushLog(board, '移除边界(' + col + '):' + val.slice(0, 50), by, session)
870
+ return { ok: true, removed: val, board: saveBoard(board, file) }
871
+ }
872
+
873
+ if (action === 'bounds.edit') {
874
+ const oldVal = str(args.oldItem, '').trim()
875
+ const newVal = str(args.item !== undefined ? args.item : args.text, '').trim().slice(0, 400)
876
+ if (!oldVal || !newVal) return { ok: false, error: 'bounds.edit requires oldItem and item' }
877
+ let editedInShared = false
878
+ withBoardLock(sharedFile, () => {
879
+ const sb = isSameFile ? board : loadBoard(sharedFile)
880
+ const sBounds = normalizeBounds(sb.bounds)
881
+ const idx = sBounds[col].indexOf(oldVal)
882
+ if (idx !== -1) {
883
+ sBounds[col][idx] = newVal
884
+ sBounds[col] = [...new Set(sBounds[col])]
885
+ sb.bounds = sBounds
886
+ editedInShared = true
887
+ if (!isSameFile) saveBoard(sb, sharedFile)
888
+ }
889
+ })
890
+ if (!isSameFile) {
891
+ if (editedInShared) {
892
+ localBounds[col] = localBounds[col].filter(x => x !== oldVal && x !== newVal)
893
+ } else {
894
+ const idx = localBounds[col].indexOf(oldVal)
895
+ if (idx !== -1) {
896
+ localBounds[col][idx] = newVal
897
+ localBounds[col] = [...new Set(localBounds[col])]
898
+ }
899
+ }
900
+ board.bounds = localBounds
901
+ }
902
+ pushLog(board, '修订边界(' + col + '):' + newVal.slice(0, 50), by, session)
903
+ return { ok: true, pinned: editedInShared, item: newVal, board: saveBoard(board, file) }
904
+ }
905
+
906
+ if (action === 'bounds.consolidate') {
907
+ const newVal = str(args.item !== undefined ? args.item : args.text, '').trim().slice(0, 400)
908
+ if (!newVal) return { ok: false, error: 'bounds.consolidate requires consolidated item' }
909
+ const rawRemove = asList(args.removeItems) || asList(args.replaces) || []
910
+ const removeSet = new Set(rawRemove.map(x => str(x, '').trim()).filter(Boolean))
911
+ const pin = asBool(args.pinned) === true || isSameFile
912
+
913
+ withBoardLock(sharedFile, () => {
914
+ const sb = isSameFile ? board : loadBoard(sharedFile)
915
+ const sBounds = normalizeBounds(sb.bounds)
916
+ sBounds[col] = sBounds[col].filter(x => !removeSet.has(x))
917
+ if (pin && !sBounds[col].includes(newVal)) {
918
+ sBounds[col].push(newVal)
919
+ sBounds[col] = sBounds[col].slice(-BOUND_CAP)
920
+ }
921
+ sb.bounds = sBounds
922
+ if (!isSameFile) {
923
+ pushLog(sb, '🏛 浓缩整理边界(' + col + '):' + newVal.slice(0, 50), by, session)
924
+ saveBoard(sb, sharedFile)
925
+ }
926
+ })
927
+ if (!isSameFile) {
928
+ localBounds[col] = localBounds[col].filter(x => !removeSet.has(x) && x !== newVal)
929
+ if (!pin) {
930
+ localBounds[col].push(newVal)
931
+ localBounds[col] = localBounds[col].slice(-BOUND_CAP)
932
+ }
933
+ board.bounds = localBounds
934
+ }
935
+ pushLog(board, '🏛 浓缩边界(' + removeSet.size + ' 合 1' + (pin ? ' · 📌全局定住' : '') + '):' + newVal.slice(0, 50), by, session)
936
+ return { ok: true, pinned: pin, item: newVal, replacedCount: removeSet.size, board: saveBoard(board, file) }
937
+ }
938
+ }
939
+
940
+ if (action === 'cursor.set') {
941
+ const current = board.cursor || { at: 0, step: '', next: '', blocked: '', by: '', session: '' }
942
+ const clips = []
943
+ if (typeof args.step === 'string') current.step = clipInto(clips, 'cursor.step', args.step, CAP_CURSOR)
944
+ if (typeof args.next === 'string') current.next = clipInto(clips, 'cursor.next', args.next, CAP_CURSOR)
945
+ if (typeof args.blocked === 'string') current.blocked = clipInto(clips, 'cursor.blocked', args.blocked, CAP_CURSOR)
946
+ if (typeof args.expectedTaskId === 'string') current.expectedTaskId = args.expectedTaskId.trim() || undefined
947
+ if (asBool(args.clear) === true) {
948
+ current.step = ''
949
+ current.next = ''
950
+ current.blocked = ''
951
+ delete current.expectedTaskId
952
+ }
953
+ current.at = nowMs()
954
+ current.by = by
955
+ current.session = session
956
+ board.cursor = current
957
+ const head = current.next || current.step || current.blocked || '(已清空)'
958
+ pushLog(board, '断点:' + head.slice(0, 100), by, session)
959
+ return clipped({ ok: true, cursor: current, board: saveBoard(board, file) }, clips)
960
+ }
961
+
962
+ if (action === 'wall.list') {
963
+ const targetCwd = session ? getSessionCwd(deps.hostState && deps.hostState.activeRuntime, session) : process.cwd()
964
+ return {
965
+ ok: true,
966
+ guardWalls: listGuardWalls({ cwd: targetCwd }),
967
+ board: loadBoard(file),
968
+ }
969
+ }
970
+
971
+ if (action === 'wall.save' || action === 'wall.setScope' || action === 'wall.remove' || action === 'wall.merge') {
972
+ const targetCwd = session ? getSessionCwd(deps.hostState && deps.hostState.activeRuntime, session) : process.cwd()
973
+ const op = action === 'wall.save'
974
+ ? 'save'
975
+ : (action === 'wall.setScope'
976
+ ? 'set_scope'
977
+ : (action === 'wall.merge' ? 'merge' : 'remove'))
978
+ const res = mutateGuardWalls({
979
+ op,
980
+ wall: (args.wall && typeof args.wall === 'object') ? args.wall : args,
981
+ wallId: args.wallId !== undefined ? args.wallId : args.id,
982
+ wallIds: Array.isArray(args.wallIds) ? args.wallIds : [],
983
+ autoGroup: Boolean(args.autoGroup),
984
+ title: typeof args.title === 'string' ? args.title : '',
985
+ scope: args.scope,
986
+ cwd: targetCwd,
987
+ callerOrigin: args._callerOrigin || '',
988
+ humanConfirmToken: args._humanConfirmToken || null,
989
+ })
990
+ if (!res.ok) return res
991
+ const actionLabel = op === 'remove'
992
+ ? `移除物理驻墙 ${args.wallId || args.id || ''}`
993
+ : (op === 'merge'
994
+ ? `合并同类物理驻墙(${res.mergedCount || 0} 条合为 ${res.createdCount || 1} 条)`
995
+ : (op === 'set_scope'
996
+ ? `切换物理驻墙「${(res.wall && res.wall.title) || ''}」状态为 ${args.scope}`
997
+ : `驻防物理墙「${(res.wall && res.wall.title) || ''}」(${res.wall && res.wall.scope === 'workspace' ? '本工程' : (res.wall && res.wall.scope === 'paused' ? '暂挂' : '全局常驻')})`))
998
+ pushLog(board, '🧱 ' + actionLabel, by, session)
999
+ return {
1000
+ ok: true,
1001
+ mergedCount: res.mergedCount || 0,
1002
+ createdCount: res.createdCount || 0,
1003
+ wall: res.wall,
1004
+ guardWalls: res.walls,
1005
+ board: saveBoard(board, file),
1006
+ }
1007
+ }
1008
+
1009
+ if (action === 'note.unpin') {
1010
+ const id = str(args.noteId !== undefined ? args.noteId : args.id, '')
1011
+ const note = board.notes.find(item => item.id === id)
1012
+ if (!note) return { ok: false, error: 'no such note: ' + id }
1013
+ if (!note.pinned) return { ok: false, error: 'note is not pinned: ' + id }
1014
+ delete note.pinned
1015
+ note.tags = (note.tags || []).filter(tag => String(tag).toLowerCase() !== 'anchor')
1016
+ note.updatedAt = nowMs()
1017
+ const sharedFile = boardFile()
1018
+ withBoardLock(sharedFile, () => {
1019
+ const sharedBoard = loadBoard(sharedFile)
1020
+ const same = sharedBoard.notes.find(item => item.title === note.title)
1021
+ if (same) {
1022
+ delete same.pinned
1023
+ same.tags = (same.tags || []).filter(tag => String(tag).toLowerCase() !== 'anchor')
1024
+ same.updatedAt = nowMs()
1025
+ saveBoard(sharedBoard, sharedFile)
1026
+ }
1027
+ })
1028
+ pushLog(board, '笔记取消置顶:' + String(note.title).slice(0, 60), by, session)
1029
+ return { ok: true, note, board: saveBoard(board, file) }
1030
+ }
1031
+
1032
+ if (action === 'note.pin') {
1033
+ // Pinning is the one operation that crosses the per-Session boundary on
1034
+ // behalf of the agent: a lesson learned here must survive into a session
1035
+ // that never sees this board. So pin writes the note into THIS board and
1036
+ // copies it, tagged `anchor`, onto the shared board the digest reads.
1037
+ const id = str(args.noteId !== undefined ? args.noteId : args.id, '')
1038
+ const note = id
1039
+ ? board.notes.find(item => item.id === id)
1040
+ : board.notes.find(item => item.title === str(args.title, '').trim())
1041
+ if (!note) return { ok: false, error: 'no such note: ' + (id || str(args.title, '')) }
1042
+ const tags = normalizeTags((note.tags || []).concat(['anchor']))
1043
+ note.tags = tags
1044
+ note.updatedAt = nowMs()
1045
+ note.pinned = true
1046
+ const sharedFile = boardFile()
1047
+ const copy = { ...note, id: note.id, tags, pinned: true, session: session || note.session || '' }
1048
+ withBoardLock(sharedFile, () => {
1049
+ const sharedBoard = loadBoard(sharedFile)
1050
+ const same = sharedBoard.notes.find(item => item.title === copy.title)
1051
+ if (same) {
1052
+ same.body = copy.body
1053
+ same.tags = copy.tags
1054
+ same.pinned = true
1055
+ same.updatedAt = nowMs()
1056
+ same.by = by
1057
+ same.session = copy.session
1058
+ } else {
1059
+ sharedBoard.notes.unshift(normalizeNote(copy))
1060
+ }
1061
+ // Anchor notes are what a fresh Session actually reads, so the count is
1062
+ // capped. note.pin and a pinned note.write both add anchors, so both run
1063
+ // the same eviction here instead of each carrying half of the rule.
1064
+ sharedBoard.notes = enforceAnchorCap(sharedBoard.notes)
1065
+ pushLog(sharedBoard, '锚点笔记:' + String(note.title).slice(0, 60), by, session)
1066
+ saveBoard(sharedBoard, sharedFile)
1067
+ })
1068
+ pushLog(board, '笔记已钉为锚点(下一会话可见):' + String(note.title).slice(0, 60), by, session)
1069
+ return { ok: true, note, board: saveBoard(board, file) }
1070
+ }
1071
+
1072
+ if (action === 'handoff.mark') {
1073
+ const prev = board.handoff || {}
1074
+ board.handoff = { ...prev, at: nowMs(), by, session }
1075
+ pushLog(board, '生成并交接给参谋看板:交接单已更新', by, session)
1076
+ return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1077
+ }
1078
+
1079
+ if (action === 'handoff.save') {
1080
+ const prev = board.handoff || {}
1081
+ const reqSource = str(args.source, '')
1082
+ const isChief = by === 'chief' || by === 'DSH 参谋长' || reqSource === 'chief'
1083
+ if (prev.pinned && isChief && asBool(args.force) !== true) {
1084
+ return { ok: false, pinned: true, error: '交接单已被人类固定锁定,参谋长不可覆盖' }
1085
+ }
1086
+ const rawText = args.text !== undefined ? args.text : args.customText
1087
+ const customText = str(rawText, '').slice(0, 16000)
1088
+ const now = nowMs()
1089
+ board.handoff = {
1090
+ ...prev,
1091
+ at: now,
1092
+ by,
1093
+ session: session || prev.session || '',
1094
+ customText,
1095
+ frozenFromAuto: false,
1096
+ updatedAt: now,
1097
+ source: isChief ? 'chief' : 'human',
1098
+ }
1099
+ pushLog(board, isChief ? '✦ 参谋长摘要已同步写入交接单' : '✏️ 人类已手动修订并保存交接单', by, session)
1100
+ return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1101
+ }
1102
+
1103
+ if (action === 'handoff.pin') {
1104
+ const prev = board.handoff || {}
1105
+ const nextPinned = asBool(args.pinned) !== undefined ? asBool(args.pinned) : !Boolean(prev.pinned)
1106
+ const now = nowMs()
1107
+ let nextCustomText = str(prev.customText, '')
1108
+ let nextSource = prev.source || 'auto'
1109
+ let nextFrozenFromAuto = Boolean(prev.frozenFromAuto)
1110
+ let nextUpdatedAt = Number(prev.updatedAt) || 0
1111
+
1112
+ if (nextPinned && !nextCustomText.trim()) {
1113
+ const providedSnap = str(args.snapshotText, '').trim()
1114
+ let autoSnap = providedSnap
1115
+ if (!autoSnap) {
1116
+ try {
1117
+ const eff = resolveEffectiveHandoff(deps.hostState.activeRuntime, session || prev.session || '', board)
1118
+ autoSnap = str((eff && (eff.text || eff.autoText)) || '', '').trim()
1119
+ } catch {}
1120
+ }
1121
+ if (autoSnap) {
1122
+ nextCustomText = autoSnap.slice(0, 16000)
1123
+ nextFrozenFromAuto = true
1124
+ nextSource = prev.source || 'auto'
1125
+ nextUpdatedAt = now
1126
+ }
1127
+ } else if (!nextPinned && prev.frozenFromAuto === true) {
1128
+ nextCustomText = ''
1129
+ nextFrozenFromAuto = false
1130
+ nextSource = 'auto'
1131
+ nextUpdatedAt = now
1132
+ }
1133
+
1134
+ board.handoff = {
1135
+ ...prev,
1136
+ pinned: nextPinned,
1137
+ pinnedAt: nextPinned ? now : 0,
1138
+ pinnedBy: nextPinned ? by : '',
1139
+ customText: nextCustomText,
1140
+ frozenFromAuto: nextFrozenFromAuto,
1141
+ source: nextSource,
1142
+ updatedAt: nextUpdatedAt,
1143
+ }
1144
+ pushLog(
1145
+ board,
1146
+ nextPinned
1147
+ ? (nextFrozenFromAuto ? '📌 交接单已定住锁定(已冻结当前自动渲染快照,禁止参谋长覆写)' : '📌 交接单已定住锁定:参谋长自动更新已禁止覆写')
1148
+ : (prev.frozenFromAuto ? '🔓 交接单已解除定住并恢复自动实时渲染' : '🔓 交接单已解除定住锁定'),
1149
+ by,
1150
+ session,
1151
+ )
1152
+ return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1153
+ }
1154
+
1155
+ if (action === 'handoff.reset') {
1156
+ const prev = board.handoff || {}
1157
+ const keepPin = asBool(args.keepPin) === true
1158
+ board.handoff = {
1159
+ ...prev,
1160
+ at: nowMs(),
1161
+ by,
1162
+ session: session || prev.session || '',
1163
+ customText: '',
1164
+ frozenFromAuto: false,
1165
+ updatedAt: nowMs(),
1166
+ source: 'auto',
1167
+ pinned: keepPin ? Boolean(prev.pinned) : false,
1168
+ pinnedAt: keepPin ? (prev.pinnedAt || 0) : 0,
1169
+ pinnedBy: keepPin ? (prev.pinnedBy || '') : '',
1170
+ }
1171
+ pushLog(board, '↺ 已恢复为自动实时渲染的交接单', by, session)
1172
+ return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1173
+ }
1174
+
1175
+ if (action === 'handoff.setSyncOnDigest') {
1176
+ const prev = board.handoff || {}
1177
+ const enabled = asBool(args.enabled !== undefined ? args.enabled : args.syncOnDigest) === true
1178
+ board.handoff = {
1179
+ ...prev,
1180
+ syncOnDigest: enabled,
1181
+ }
1182
+ return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1183
+ }
1184
+
1185
+ if (action === 'log.add' || action === 'note.add') {
1186
+ // pushLog appends whatever it is given, but the very next load clamps one
1187
+ // entry to 400 characters — so a long handoff line was stored, then silently
1188
+ // cut, and the caller was told the write succeeded as sent.
1189
+ const clips = []
1190
+ const text = clipInto(clips, 'log.text', str(args.text, '').trim(), CAP_LOG_TEXT)
1191
+ if (!text) return { ok: false, error: 'text required' }
1192
+ pushLog(board, text, by, session)
1193
+ return clipped({ ok: true, board: saveBoard(board, file) }, clips)
1194
+ }
1195
+
1196
+ if (action === 'note.write') {
1197
+ const clips = []
1198
+ const id = str(args.noteId !== undefined ? args.noteId : args.id, '')
1199
+ const pinnedNote = asBool(args.pinned) === true
1200
+ const tagList = asList(args.tags)
1201
+ const given = tagList ? normalizeTags(tagList) : undefined
1202
+ // Pinning is a promise about reachability, and every reader of that promise
1203
+ // — anchorLines, the ANCHOR_CAP eviction, the digest a fresh Session gets —
1204
+ // keys off the `anchor` tag, not off this boolean. A write that stored
1205
+ // pinned without the tag described a reach it did not have.
1206
+ const tags = pinnedNote ? normalizeTags((given || []).concat(['anchor'])) : given
1207
+ if (id) {
1208
+ const index = board.notes.findIndex(note => note.id === id)
1209
+ if (index < 0) return { ok: false, error: 'no such note: ' + id }
1210
+ const note = board.notes[index]
1211
+ if (typeof args.title === 'string') note.title = clipInto(clips, 'note.title', args.title, CAP_NOTE_TITLE)
1212
+ if (typeof args.body === 'string') note.body = clipInto(clips, 'note.body', args.body, CAP_NOTE_BODY)
1213
+ if (tags) note.tags = tags
1214
+ note.updatedAt = nowMs()
1215
+ if (!note.title.trim() && !note.body.trim()) {
1216
+ board.notes.splice(index, 1)
1217
+ pushLog(board, '笔记被清空并移除', by, session)
1218
+ return clipped({ ok: true, board: saveBoard(board, file) }, clips)
1219
+ }
1220
+ board.notes = enforceAnchorCap(board.notes)
1221
+ return clipped({ ok: true, note, board: saveBoard(board, file) }, clips)
1222
+ }
1223
+ const rawTitle = clipInto(clips, 'note.title', str(args.title, '').trim(), CAP_NOTE_TITLE)
1224
+ const body = clipInto(clips, 'note.body', str(args.body, ''), CAP_NOTE_BODY)
1225
+ if (!rawTitle && !body.trim()) return { ok: false, error: 'title or body required' }
1226
+ // A note written without a title used to be stored untitled: the panel
1227
+ // rendered it as «(无标题)», dedupeNotes keyed it by id so every such write
1228
+ // added another nameless row, and the same-title merge could never reach it
1229
+ // because there was no title to match. Derive the headline from the first
1230
+ // non-empty line of the body, minus its leading markdown markers, so the
1231
+ // note stays recognisable, mergeable and searchable.
1232
+ const firstLine = body
1233
+ .split('\n')
1234
+ .map(line => line.replace(LEADING_MARKER, '').trim())
1235
+ .find(line => line !== '')
1236
+ const title = rawTitle || (firstLine || '').slice(0, 60)
1237
+ if (title) {
1238
+ const same = board.notes.find(note => note.title === title)
1239
+ if (same) {
1240
+ same.body = body || same.body
1241
+ if (given) same.tags = given
1242
+ if (pinnedNote) {
1243
+ same.pinned = true
1244
+ same.tags = normalizeTags((same.tags || []).concat(['anchor']))
1245
+ }
1246
+ same.updatedAt = nowMs()
1247
+ same.by = by
1248
+ same.session = session || same.session
1249
+ board.notes = enforceAnchorCap(board.notes)
1250
+ return clipped({ ok: true, note: same, board: saveBoard(board, file) }, clips)
1251
+ }
1252
+ }
1253
+ const pinned = pinnedNote ? true : undefined
1254
+ const note = normalizeNote({ id: newId('n'), title, body, tags: tags || [], by, session, pinned })
1255
+ board.notes.unshift(note)
1256
+ board.notes = enforceAnchorCap(board.notes)
1257
+ pushLog(board, '新建笔记:' + (note.title || note.body.slice(0, 24)), by, session)
1258
+ return clipped({ ok: true, note, board: saveBoard(board, file) }, clips)
1259
+ }
1260
+
1261
+ if (action === 'note.read') {
1262
+ const id = str(args.noteId !== undefined ? args.noteId : args.id, '')
1263
+ const note = board.notes.find(n => n.id === id)
1264
+ if (!note) return { ok: false, error: 'no such note: ' + id }
1265
+ // Read-tracking: the caller's session lands in readBy so the next agent
1266
+ // can see who already picked this note up without re-reading it.
1267
+ if (session && !note.readBy.includes(session)) {
1268
+ note.readBy.push(session)
1269
+ saveBoard(board, file)
1270
+ }
1271
+ return { ok: true, note, board }
1272
+ }
1273
+
1274
+ if (action === 'note.remove') {
1275
+ const id = str(args.noteId !== undefined ? args.noteId : args.id, '')
1276
+ const index = board.notes.findIndex(note => note.id === id)
1277
+ if (index < 0) return { ok: false, error: 'no such note: ' + id }
1278
+ const [removed] = board.notes.splice(index, 1)
1279
+ pushLog(board, '删除笔记:' + (removed.title || removed.body.slice(0, 24)), by, session)
1280
+ return { ok: true, board: saveBoard(board, file) }
1281
+ }
1282
+
1283
+ // Memory: written by the host as turns close, and by the human or the model
1284
+ // when something matters enough to survive the next turn.
1285
+ if (action === 'memory.add') {
1286
+ const clips = []
1287
+ const text = clipInto(clips, 'memory.text', str(args.text !== undefined ? args.text : args.body, '').trim(), CAP_MEMORY_TEXT)
1288
+ if (text === '') return { ok: false, error: 'text required' }
1289
+ const added = normalizeMemory([{
1290
+ id: newId('mem'),
1291
+ at: nowMs(),
1292
+ turn: typeof args.turn === 'number' ? args.turn : 0,
1293
+ section: str(args.section, 'other'),
1294
+ title: clipInto(clips, 'memory.title', str(args.title, ''), CAP_MEMORY_TITLE) || text.slice(0, 80),
1295
+ text,
1296
+ tools: [],
1297
+ by: by || 'user',
1298
+ session: session || '',
1299
+ }])[0]
1300
+ appendMemory(board, { ...added, by: by || 'user' })
1301
+ pushLog(board, '记忆 += ' + (added.title || added.text.slice(0, 40)), by, session)
1302
+ return clipped({ ok: true, memory: board.memory.slice(-6), board: saveBoard(board, file) }, clips)
1303
+ }
1304
+
1305
+ if (action === 'memory.remove') {
1306
+ const id = str(args.id !== undefined ? args.id : args.memoryId, '')
1307
+ const index = board.memory.findIndex(item => item.id === id)
1308
+ if (index < 0) return { ok: false, error: 'no such memory: ' + id }
1309
+ const [removed] = board.memory.splice(index, 1)
1310
+ pushLog(board, '记忆移除:' + (removed.title || removed.text.slice(0, 32)), by, session)
1311
+ return { ok: true, board: saveBoard(board, file) }
1312
+ }
1313
+
1314
+ if (action === 'memory.ask') {
1315
+ // A question is not an operation on the board, and this branch runs
1316
+ // unlocked by design (runAction:419), so it must never touch it: anything
1317
+ // written here would live in the loadBoard cache only and be thrown away by
1318
+ // the next caches.delete, while the returned board told the panel it was
1319
+ // saved. Asking leaves no trace, and the board that comes back is byte for
1320
+ // byte the one on disk.
1321
+ const question = str(args.question !== undefined ? args.question : args.text, '')
1322
+ const answer = answerMemory(board, question)
1323
+ return { ok: true, reply: answer.reply, hits: answer.hits, terms: answer.terms, board }
1324
+ }
1325
+
1326
+ return { ok: false, error: 'unknown action: ' + action }
1327
+ }
1328
+
1329
+ function boundaries(runtime, sessionId) {
1330
+ const wd = runtime.get('workingDirectory')
1331
+ const sandboxPolicy = runtime.get('sandboxPolicy')
1332
+ const webApp = runtime.get('webApp')
1333
+ const tools = runtime.get('tools')
1334
+ const file = boardFile()
1335
+ const agent = agentOf(runtime, sessionId)
1336
+ const session = agent && agent.session ? agent.session : undefined
1337
+ const resolvedSessionId = str(agent && agent.id, '') || str(sessionId, '') || null
1338
+ const sessionResolved = !!(agent && agent.session)
1339
+ return {
1340
+ workingDirectory: safe(() => wd.defaultDirectory, process.cwd()),
1341
+ sandboxMode: safe(() => sandboxPolicy.defaultMode, 'unknown'),
1342
+ workspaceRoot: safe(() => sandboxPolicy.workspaceRoot, null),
1343
+ extraWritableRoots: safe(() => sandboxPolicy.additionalWritableRoots, null),
1344
+ profile: process.env.DSH_PROFILE || null,
1345
+ dshHome: process.env.DSH_HOME || null,
1346
+ boardFile: file,
1347
+ boardExists: safe(() => fs.existsSync(file), false),
1348
+ webUrl: safe(() => webApp.getAdvertisedUrl(), null),
1349
+ toolCount: safe(() => tools.definitions().length, null),
1350
+ sessionId: resolvedSessionId,
1351
+ sessionResolved,
1352
+ sessionWorkingDirectory: session ? safe(() => wd.get(session), null) : null,
1353
+ sessionSandboxMode: session ? safe(() => sandboxPolicy.resolve({ session }).mode, null) : null,
1354
+ sessionSandboxOverride: session ? safe(() => sandboxPolicy.overrideOf(session) ?? null, null) : null,
1355
+ liveAgents: safe(() => (runtime.get('agents').list() || []).map(agent => ({
1356
+ id: String(agent.id),
1357
+ canInject: typeof agent.inject === 'function',
1358
+ })), []),
1359
+ pendingTransfer: readPending() ? true : false,
1360
+ pid: process.pid,
1361
+ platform: process.platform,
1362
+ node: process.version,
1363
+ cwd: process.cwd(),
1364
+ }
1365
+ }
1366
+
1367
+ function archiveTarget(runtime, sessionId, optOrId = '') {
1368
+ const opts = optOrId && typeof optOrId === 'object'
1369
+ ? optOrId
1370
+ : { cabinetId: typeof optOrId === 'string' ? optOrId : '' }
1371
+ const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
1372
+ const sid = String(sessionId || '').trim()
1373
+ const rootSid = resolveBoundRootSid(sid)
1374
+ let cabinetId = vaultScope !== 'global' && typeof opts.cabinetId === 'string' ? opts.cabinetId.trim() : ''
1375
+ if (vaultScope !== 'global' && !cabinetId && rootSid) {
1376
+ try {
1377
+ cabinetId = loadBoard(boardFileFor(rootSid)).activeCabinetId || ''
1378
+ } catch {}
1379
+ }
1380
+ return {
1381
+ customSharedBoardFile: boardFile(),
1382
+ cwd: getSessionCwd(runtime, rootSid || (sid !== 'global' ? sid : '')),
1383
+ vaultScope,
1384
+ ...(vaultScope !== 'global' && rootSid ? { rootSessionId: rootSid } : {}),
1385
+ ...(vaultScope !== 'global' && cabinetId ? { cabinetId } : {}),
1386
+ }
1387
+ }
1388
+
1389
+ function composeHandoffFromNarrative({ board, narrativeText = '', cluster = [] } = {}) {
1390
+ const b = board || emptyBoard()
1391
+ const lines = ['# 交接单(参谋长提炼同步版)', '']
1392
+ if (b.objective) {
1393
+ lines.push('## 总目标', `- ${b.objective}`, '')
1394
+ }
1395
+ if (b.cursor && (b.cursor.step || b.cursor.next || b.cursor.blocked)) {
1396
+ lines.push('## 当前断点', `- 当前步骤:${b.cursor.step || '无'}`, b.cursor.next ? `- 下一步:${b.cursor.next}` : '', b.cursor.blocked ? `- 阻塞点:${b.cursor.blocked}` : '', '')
1397
+ }
1398
+ if (narrativeText) {
1399
+ lines.push('## 参谋长态势研判与进展摘要', narrativeText.trim(), '')
1400
+ }
1401
+ const openSteps = (b.plan || []).filter(s => s && !s.done)
1402
+ if (openSteps.length) {
1403
+ lines.push('## 待推进计划', ...openSteps.slice(0, 8).map((s, i) => `${i + 1}. ${s.text}`), '')
1404
+ }
1405
+ const openTasks = (b.tasks || []).filter(t => t && t.status !== 'done')
1406
+ if (openTasks.length) {
1407
+ lines.push('## 未完任务', ...openTasks.slice(0, 8).map(t => `- [${t.status}] #${t.id} ${t.title}${t.note ? `(${String(t.note).slice(0, 100)})` : ''}`), '')
1408
+ }
1409
+ const fb = (b.bounds && b.bounds.forbidden) || []
1410
+ const al = (b.bounds && b.bounds.allowed) || []
1411
+ const nt = (b.bounds && b.bounds.notes) || []
1412
+ if (fb.length || al.length || nt.length) {
1413
+ lines.push('## 生效红线与工作边界')
1414
+ if (fb.length) lines.push(...fb.slice(0, 6).map(x => `- 🚫 禁止:${x}`))
1415
+ if (al.length) lines.push(...al.slice(0, 4).map(x => `- ✅ 必做:${x}`))
1416
+ if (nt.length) lines.push(...nt.slice(0, 4).map(x => `- 📌 注意:${x}`))
1417
+ lines.push('')
1418
+ }
1419
+ if (Array.isArray(cluster) && cluster.length > 1) {
1420
+ lines.push(`## 当前协同网络`, `- 已联通协同群组共 ${cluster.length} 个独立会话。`, '')
1421
+ }
1422
+ return lines.filter((l, i, arr) => !(l === '' && arr[i - 1] === '')).join('\n').slice(0, 12000)
1423
+ }
1424
+
1425
+ function resolveEffectiveHandoff(runtime, sessionId, board, extraTeamTasks = undefined) {
1426
+ const b = board || emptyBoard()
1427
+ const h = b.handoff || {}
1428
+ const rootSid = sessionId ? (resolveRootSessionId(sessionId) || sessionId) : ''
1429
+ const customText = typeof h.customText === 'string' ? h.customText.trim() : ''
1430
+ const pinned = Boolean(h.pinned)
1431
+ const syncOnDigest = Boolean(h.syncOnDigest)
1432
+
1433
+ const teamTasks = extraTeamTasks !== undefined
1434
+ ? extraTeamTasks
1435
+ : fetchTeamTasks(runtime, sessionId ? { id: sessionId } : null)
1436
+ const takenOutArchives = rootSid ? collectTakenOutAndFlipped(runtime, rootSid, b.activeCabinetId) : []
1437
+ const autoText = renderHandoff(b, boundaries(runtime, sessionId), 5200, sessionId, {
1438
+ teamTasks,
1439
+ takenOutArchives,
1440
+ })
1441
+
1442
+ const effectiveText = customText ? h.customText : autoText
1443
+ let chiefNarrativeAt = 0
1444
+ let chiefNarrativeText = ''
1445
+ try {
1446
+ const st = loadChiefState()
1447
+ const ws = st && st.workspaces && st.workspaces[rootSid || 'global']
1448
+ if (ws && ws.narrative && ws.narrative.text) {
1449
+ chiefNarrativeText = ws.narrative.text
1450
+ chiefNarrativeAt = Number(ws.narrative.at) || 0
1451
+ }
1452
+ } catch {}
1453
+
1454
+ const updatedAt = Number(h.updatedAt) || Number(h.at) || 0
1455
+ const hasRichWork = Boolean(b.objective || (b.plan && b.plan.length) || (b.tasks && b.tasks.length) || (b.memory && b.memory.length))
1456
+ const isIncomplete = !effectiveText.trim() || (!customText && !b.objective && !(b.tasks && b.tasks.length) && !(b.plan && b.plan.length))
1457
+ const isStale = !pinned && Boolean(
1458
+ hasRichWork && (
1459
+ (chiefNarrativeText && h.source !== 'human' && chiefNarrativeAt > updatedAt + 2000)
1460
+ || (Number(b.updatedAt) > updatedAt + 60_000 && !customText)
1461
+ ),
1462
+ )
1463
+
1464
+ return {
1465
+ text: effectiveText,
1466
+ autoText,
1467
+ source: customText ? (h.source || 'human') : 'auto',
1468
+ isCustom: Boolean(customText),
1469
+ pinned,
1470
+ pinnedAt: Number(h.pinnedAt) || 0,
1471
+ pinnedBy: h.pinnedBy || '',
1472
+ updatedAt,
1473
+ handoffAt: Number(h.at) || 0,
1474
+ syncOnDigest,
1475
+ isIncomplete,
1476
+ isStale,
1477
+ hasNarrativeUpdate: Boolean(chiefNarrativeText && chiefNarrativeAt > updatedAt + 2000),
1478
+ }
1479
+ }
1480
+
1481
+ /** Combine Session-Cabinet mounted items with explicitly flipped precipitated entries (NEVER reads Global Cabinet!). */
1482
+ function collectTakenOutAndFlipped(runtime, rootId, cabinetId = '') {
1483
+ if (!rootId) return []
1484
+ const targetOpt = archiveTarget(runtime, rootId, { cabinetId, vaultScope: 'session' })
1485
+ const working = getTakenOutArchivesForSession(rootId, targetOpt).map(e => ({
1486
+ ...e,
1487
+ _deskScope: 'session',
1488
+ folderLabel: `本局桌面/${e.folder || '档案'}`,
1489
+ title: `[桌面强调·本局] ${e.title}`,
1490
+ }))
1491
+ const globalTargetOpt = archiveTarget(runtime, rootId, { cabinetId: '', vaultScope: 'global' })
1492
+ const takenGlobal = getTakenOutGlobalForSession(rootId, globalTargetOpt).map(e => ({
1493
+ ...e,
1494
+ _deskScope: 'global',
1495
+ folderLabel: `全局桌面/${e.folder || '经验'}`,
1496
+ title: `[桌面强调·全局] ${e.title}`,
1497
+ }))
1498
+ const state = loadChiefState()
1499
+ const ws = state && state.workspaces && state.workspaces[rootId]
1500
+ const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
1501
+ let mappedFlipped = []
1502
+ if (flippedIds.length) {
1503
+ const projectKey = resolveProjectKey(targetOpt.cwd)
1504
+ const flippedEntries = getFlippedOutPrecipitatedForSession(projectKey, rootId, true, targetOpt)
1505
+ mappedFlipped = flippedEntries.map(e => ({
1506
+ ...e,
1507
+ _deskScope: 'precipitated',
1508
+ folder: e.category || 'contracts',
1509
+ folderLabel: `沉淀桌面/${e.category || '经验'}`,
1510
+ title: `[桌面强调·沉淀] ${e.title}`,
1511
+ }))
1512
+ }
1513
+ return [...working, ...takenGlobal, ...mappedFlipped]
1514
+ }
1515
+
1516
+ /** Collect digest-safe archive context for Lead/Subagent prompt: ONLY desk-spotlight items across all 3 vaults (sealed items NEVER leak to Lead), plus Smart Compaction flag & posture. */
1517
+ function collectDigestArchiveContext(runtime, rootId, cabinetId = '') {
1518
+ const takenOutArchives = rootId ? collectTakenOutAndFlipped(runtime, rootId, cabinetId) : []
1519
+ const sessionArchiveBriefs = []
1520
+ let smartCompactActive = false
1521
+ let chiefPermissionMode = DEFAULT_CHIEF_PERMISSION_MODE
1522
+ if (rootId) {
1523
+ try {
1524
+ const st = loadChiefState()
1525
+ const cfg = resolveWorkspaceConfig(st, rootId)
1526
+ const ws = st && st.workspaces && st.workspaces[rootId]
1527
+ const tm = (cfg && cfg.tacticalModes) || {}
1528
+ smartCompactActive = Boolean(tm.smartCompact)
1529
+ chiefPermissionMode = normalizePermissionMode(cfg && cfg.permissionMode, {
1530
+ requireAck: true,
1531
+ hasChiefRiskAck: hasValidChiefRiskAck(ws),
1532
+ })
1533
+ } catch {}
1534
+ }
1535
+ return { takenOutArchives, sessionArchiveBriefs, smartCompactActive, chiefPermissionMode }
1536
+ }
1537
+
1538
+ /* ------------------------------------------------------------------- auto sync */
1539
+
1540
+ /** todo_write → plan. Skipped when the plan already says the same thing. */
1541
+ function syncPlanFromTodos(args, sessionId) {
1542
+ const steps = planFromTodos(args)
1543
+ if (!steps) return
1544
+ const file = boardFileFor(sessionId)
1545
+ withBoardLock(file, () => {
1546
+ const board = loadBoard(file)
1547
+ if (planSignature(board.plan) === planSignature(steps)) return
1548
+ board.plan = steps
1549
+ saveBoard(board, file)
1550
+ })
1551
+ }
1552
+
1553
+ /** create_goal / update_goal → objective. */
1554
+ function syncObjective(name, args, sessionId) {
1555
+ if (isObjectiveLockedByIntervention(sessionId)) return
1556
+ const objective = objectiveFromGoal(name, args)
1557
+ if (!objective) return
1558
+ const file = boardFileFor(sessionId)
1559
+ withBoardLock(file, () => {
1560
+ const board = loadBoard(file)
1561
+ const wantGoalMode = name === 'create_goal'
1562
+ if (board.objective === objective && (!wantGoalMode || board.mode === 'goal')) return
1563
+ const previous = board.objective
1564
+ board.objective = objective.slice(0, 2000)
1565
+ board.objectiveBy = String(sessionId || '')
1566
+ board.objectiveAt = nowMs()
1567
+ if (wantGoalMode) {
1568
+ board.mode = 'goal'
1569
+ if (board.goalApproval && board.goalApproval.status !== 'pending') board.goalApproval = null
1570
+ }
1571
+ board.objectiveUpdatedAt = board.objectiveAt
1572
+ pushLog(board, '长期目标改为:' + objective.slice(0, 60) + (previous && previous !== objective ? '(原:' + previous.slice(0, 40) + ')' : ''), 'agent', sessionId)
1573
+ saveBoard(board, file)
1574
+ })
1575
+ }
1576
+
1577
+ /** Put one packet into exactly one place, because the operator asked for it.
1578
+ *
1579
+ * Shape matters more than anything else here. The queue in front of an agent
1580
+ * records what it was handed, and the session log stores that record verbatim
1581
+ * (`agent/inbox/spliced`). A bare string there makes the whole log unloadable
1582
+ * ("requires message objects"), and a message without a producer-owned
1583
+ * `source.kind` makes the client crash while it resolves submission
1584
+ * insertions. So the payload is always a complete message: id, role, content,
1585
+ * and a source kind this package owns.
1586
+ */
1587
+ const HANDOFF_SOURCE = { kind: 'dsh-chief-handoff' }
1588
+
1589
+ function buildHandoffMessage(text) {
1590
+ deps.hostState.handoffSeq += 1
1591
+ return {
1592
+ id: 'handoff-' + Date.now().toString(36) + '-' + deps.hostState.handoffSeq.toString(36),
1593
+ role: 'user',
1594
+ content: [{ type: 'text', text }],
1595
+ source: { ...HANDOFF_SOURCE },
1596
+ }
1597
+ }
1598
+
1599
+ async function injectInto(agent, text) {
1600
+ if (!agent || typeof agent.inject !== 'function') {
1601
+ return { ok: false, error: '这个 agent 没有 inject 方法' }
1602
+ }
1603
+ const message = buildHandoffMessage(text)
1604
+ const shapes = [message, { content: message.content, source: message.source, role: message.role, id: message.id }]
1605
+ for (const shape of shapes) {
1606
+ try {
1607
+ const result = agent.inject(shape)
1608
+ if (result && typeof result.then === 'function') await result
1609
+ return { ok: true }
1610
+ } catch {}
1611
+ }
1612
+ return { ok: false, error: 'inject 不接受完整消息形状(纯文本会写坏会话日志,不试)' }
1613
+ }
1614
+
1615
+ /**
1616
+ * System-level handover & state deployment to a target Chief workspace (`一键部署参谋`).
1617
+ * Copies active objective, mode, plan steps, unfinished tasks (scrubbing stale `doing` / child handles),
1618
+ * cursor, bounds, and Chief facts/narrative/chat — while optionally copying working cabinet archives
1619
+ * per `archiveTransferPolicy` ('none' | 'mounted' | 'drawer' | 'all') and strictly NEVER leaking precipitated cold vault.
1620
+ */
1621
+ function deployStateToTargetChief(runtime, {
1622
+ fromSessionId = '',
1623
+ toSessionId = '',
1624
+ archiveTransferPolicy = 'none',
1625
+ archiveDrawer = '',
1626
+ toCabinetId = '',
1627
+ customNote = '',
1628
+ } = {}) {
1629
+ const fromRoot = resolveRootSessionId(fromSessionId) || String(fromSessionId || '').trim()
1630
+ const toRoot = resolveRootSessionId(toSessionId) || String(toSessionId || '').trim()
1631
+ if (!fromRoot || !toRoot || fromRoot === toRoot) {
1632
+ return { ok: false, error: '跨会话移交需要两个不同的会话 ID' }
1633
+ }
1634
+
1635
+ const srcBoard = boardForSession(boardFileFor(fromRoot))
1636
+ const destFile = boardFileFor(toRoot)
1637
+ let copiedTaskCount = 0
1638
+ let copiedStepCount = 0
1639
+
1640
+ withBoardLock(destFile, () => {
1641
+ const dest = loadBoard(destFile)
1642
+ if (srcBoard.objective) {
1643
+ dest.objective = srcBoard.objective
1644
+ dest.objectiveBy = srcBoard.objectiveBy || fromRoot
1645
+ dest.objectiveAt = srcBoard.objectiveAt || nowMs()
1646
+ dest.objectiveUpdatedAt = nowMs()
1647
+ }
1648
+ dest.mode = srcBoard.mode === 'goal' ? 'goal' : 'plan'
1649
+ dest.goalApproval = null
1650
+
1651
+ if (Array.isArray(srcBoard.plan) && srcBoard.plan.length > 0) {
1652
+ dest.plan = srcBoard.plan.map(step => ({
1653
+ id: step.id || newId('s'),
1654
+ text: step.text,
1655
+ done: Boolean(step.done),
1656
+ }))
1657
+ copiedStepCount = dest.plan.length
1658
+ }
1659
+
1660
+ const srcTasks = Array.isArray(srcBoard.tasks) ? srcBoard.tasks : []
1661
+ const unfinished = srcTasks.filter(t => t && t.status !== 'done')
1662
+ const unfinishedIds = new Set(unfinished.map(t => t.id))
1663
+ const existingIds = new Set((dest.tasks || []).map(t => t.id))
1664
+ for (const rawTask of unfinished) {
1665
+ if (existingIds.has(rawTask.id)) continue
1666
+ const remainingBlockers = (rawTask.blockedBy || []).filter(bid => unfinishedIds.has(bid))
1667
+ const droppedDoneCount = (rawTask.blockedBy || []).length - remainingBlockers.length
1668
+ dest.tasks.push(normalizeTask({
1669
+ ...rawTask,
1670
+ status: rawTask.status === 'doing' ? 'todo' : rawTask.status,
1671
+ session: '',
1672
+ subagent: '',
1673
+ blockedBy: remainingBlockers,
1674
+ note: droppedDoneCount > 0
1675
+ ? [rawTask.note, `[接力已自动解除 ${droppedDoneCount} 项已完成前置依赖]`].filter(Boolean).join(' ')
1676
+ : rawTask.note,
1677
+ updatedAt: nowMs(),
1678
+ }))
1679
+ copiedTaskCount += 1
1680
+ }
1681
+
1682
+ if (srcBoard.cursor && (srcBoard.cursor.step || srcBoard.cursor.next || srcBoard.cursor.blocked)) {
1683
+ dest.cursor = {
1684
+ ...srcBoard.cursor,
1685
+ at: nowMs(),
1686
+ by: 'deploy',
1687
+ session: fromRoot,
1688
+ }
1689
+ }
1690
+
1691
+ // Merge local non-pinned bounds from source session board into destination session board
1692
+ const srcLocal = srcBoard.localBounds || { allowed: [], forbidden: [], notes: [] }
1693
+ const destBounds = normalizeBounds(dest.bounds)
1694
+ for (const col of BOUND_FIELDS) {
1695
+ const merged = new Set(destBounds[col] || [])
1696
+ for (const item of (srcLocal[col] || [])) merged.add(item)
1697
+ destBounds[col] = [...merged].slice(0, BOUND_CAP)
1698
+ }
1699
+ dest.bounds = destBounds
1700
+
1701
+ // Carry non-anchor handoff context notes selectively if target has room
1702
+ dest.handoff = {
1703
+ at: nowMs(),
1704
+ by: 'deploy',
1705
+ session: fromRoot,
1706
+ customText: '',
1707
+ pinned: false,
1708
+ pinnedAt: 0,
1709
+ pinnedBy: '',
1710
+ updatedAt: 0,
1711
+ source: 'auto',
1712
+ syncOnDigest: false,
1713
+ }
1714
+ pushLog(
1715
+ dest,
1716
+ `🚀 已系统级移交部署自会话 ${fromRoot.slice(0, 12)}:计划 ${copiedStepCount} 步、未完任务 ${copiedTaskCount} 项`,
1717
+ 'deploy',
1718
+ toRoot,
1719
+ )
1720
+ saveBoard(dest, destFile)
1721
+ })
1722
+
1723
+ const chiefRes = deployChiefWorkspaceState(makeChiefDeps(runtime), {
1724
+ fromRootId: fromRoot,
1725
+ toRootId: toRoot,
1726
+ fromTitle: sessionName(runtime, fromRoot) || fromRoot,
1727
+ customText: customNote,
1728
+ objective: srcBoard.objective || '',
1729
+ })
1730
+
1731
+ let archiveCopyRes = { ok: true, policy: 'none', copiedCount: 0 }
1732
+ const policy = ['none', 'mounted', 'drawer', 'all'].includes(archiveTransferPolicy)
1733
+ ? archiveTransferPolicy
1734
+ : 'none'
1735
+ if (policy !== 'none') {
1736
+ archiveCopyRes = copyArchivesBetweenSessionsOrCabinets({
1737
+ fromRootSessionId: fromRoot,
1738
+ toRootSessionId: toRoot,
1739
+ fromCwd: getSessionCwd(runtime, fromRoot),
1740
+ toCwd: getSessionCwd(runtime, toRoot),
1741
+ fromCabinetId: srcBoard.activeCabinetId || '',
1742
+ toCabinetId: toCabinetId || loadBoard(boardFileFor(toRoot)).activeCabinetId || '',
1743
+ policy,
1744
+ drawer: archiveDrawer,
1745
+ customSharedBoardFile: boardFile(),
1746
+ })
1747
+ }
1748
+
1749
+ return {
1750
+ ok: true,
1751
+ fromSessionId: fromRoot,
1752
+ toSessionId: toRoot,
1753
+ copiedTaskCount,
1754
+ copiedStepCount,
1755
+ chiefDeployed: chiefRes,
1756
+ archiveTransfer: archiveCopyRes,
1757
+ }
1758
+ }
1759
+
1760
+ async function transferChief(runtime, args, sessionId) {
1761
+ const passed = args && typeof args === 'object' ? args : {}
1762
+ const target = typeof passed.target === 'string' ? passed.target.trim() : 'new'
1763
+ const deployChief = asBool(passed.deployChief) !== false
1764
+ const archiveTransferPolicy = ['none', 'mounted', 'drawer', 'all'].includes(str(passed.archiveTransferPolicy, 'none'))
1765
+ ? str(passed.archiveTransferPolicy, 'none')
1766
+ : 'none'
1767
+ const archiveDrawer = str(passed.archiveDrawer, '')
1768
+ const toCabinetId = str(passed.toCabinetId, '')
1769
+ const customNote = str(passed.customNote, '')
1770
+
1771
+ const board = boardForSession(boardFileFor(sessionId))
1772
+ const rootSid = resolveRootSessionId(sessionId) || sessionId
1773
+ const packet = resolveEffectiveHandoff(runtime, sessionId, board).text
1774
+ const by = typeof passed.by === 'string' && passed.by ? passed.by : 'user'
1775
+
1776
+ if (!target || target === 'new' || target === 'latest') {
1777
+ if (!writePending({ at: nowMs(), by, session: sessionId, text: packet })) {
1778
+ return { ok: false, error: '待领取文件写入失败' }
1779
+ }
1780
+ if (deployChief && rootSid) {
1781
+ writePendingDeploy({
1782
+ at: nowMs(),
1783
+ by,
1784
+ fromSessionId: rootSid,
1785
+ archiveTransferPolicy,
1786
+ archiveDrawer,
1787
+ toCabinetId,
1788
+ customNote,
1789
+ })
1790
+ }
1791
+ const owner = boardFileFor(sessionId)
1792
+ withBoardLock(owner, () => {
1793
+ const next = loadBoard(owner)
1794
+ pushLog(next, '交接单与参谋接力包已投放:等下一个新会话自动部署领取', by, sessionId)
1795
+ saveBoard(next, owner)
1796
+ })
1797
+ return { ok: true, mode: 'pending', deployQueued: deployChief, text: packet }
1798
+ }
1799
+
1800
+ if (target === 'create') {
1801
+ const controller = runtime.get('sessionController')
1802
+ const parked = writePending({ at: nowMs(), by, session: sessionId, text: packet })
1803
+ if (!parked) return { ok: false, error: '待领取文件写入失败' }
1804
+ if (deployChief && rootSid) {
1805
+ writePendingDeploy({
1806
+ at: nowMs(),
1807
+ by,
1808
+ fromSessionId: rootSid,
1809
+ archiveTransferPolicy,
1810
+ archiveDrawer,
1811
+ toCabinetId,
1812
+ customNote,
1813
+ })
1814
+ }
1815
+ if (!controller || typeof controller.create !== 'function') {
1816
+ return { ok: false, error: '这个部署没有 sessionController,交接单已放进待领取', mode: 'pending', text: packet }
1817
+ }
1818
+ const matchedWorkspaceId = resolveWorkspaceIdForSession(runtime, rootSid || sessionId)
1819
+ const srcCwd = getSessionCwd(runtime, rootSid || sessionId)
1820
+ const fallbackCwdReq = srcCwd && !isInternalProfileCwd(srcCwd) ? { cwd: srcCwd } : {}
1821
+ const createReq = matchedWorkspaceId ? { workspaceId: matchedWorkspaceId } : fallbackCwdReq
1822
+
1823
+ let created
1824
+ try {
1825
+ created = await controller.create(createReq)
1826
+ } catch (error) {
1827
+ if (createReq.workspaceId) {
1828
+ try {
1829
+ created = await controller.create(fallbackCwdReq)
1830
+ } catch (fallbackErr) {
1831
+ return {
1832
+ ok: false,
1833
+ error: '唤起新会话失败:' + String((fallbackErr && fallbackErr.message) || fallbackErr),
1834
+ mode: 'pending',
1835
+ text: packet,
1836
+ }
1837
+ }
1838
+ } else {
1839
+ return {
1840
+ ok: false,
1841
+ error: '唤起新会话失败:' + String((error && error.message) || error),
1842
+ mode: 'pending',
1843
+ text: packet,
1844
+ }
1845
+ }
1846
+ }
1847
+ const createdId = str(created && created.sessionId, '')
1848
+ if (!createdId) return { ok: false, error: '新会话没有返回 id', mode: 'pending', text: packet }
1849
+
1850
+ let deployResult = null
1851
+ if (deployChief && rootSid && readPendingDeploy()) {
1852
+ clearPendingDeploy()
1853
+ deployResult = deployStateToTargetChief(runtime, {
1854
+ fromSessionId: rootSid,
1855
+ toSessionId: createdId,
1856
+ archiveTransferPolicy,
1857
+ archiveDrawer,
1858
+ toCabinetId,
1859
+ customNote,
1860
+ })
1861
+ }
1862
+
1863
+ const owner = boardFileFor(sessionId)
1864
+ if (!readPending()) {
1865
+ withBoardLock(owner, () => {
1866
+ const next = loadBoard(owner)
1867
+ pushLog(next, '交接单与参谋已由新会话 ' + createdId.replace(/^session-/, '').slice(0, 8) + ' 领取部署', by, sessionId)
1868
+ saveBoard(next, owner)
1869
+ })
1870
+ return { ok: true, mode: 'created', sessionId: createdId, delivered: true, deployResult, text: packet }
1871
+ }
1872
+ const agents = runtime.get('agents')
1873
+ const fresh = agents && typeof agents.get === 'function' ? agents.get(createdId) : undefined
1874
+ const delivered = fresh ? await injectInto(fresh, packet) : { ok: false, error: '新会话还没有活的 agent,交接单留在待领取' }
1875
+ if (delivered.ok) clearPending()
1876
+ withBoardLock(owner, () => {
1877
+ const next = loadBoard(owner)
1878
+ pushLog(
1879
+ next,
1880
+ (delivered.ok ? '交接单与参谋已部署至新会话 ' : '新会话已建(交接单仍待领取):') + createdId.replace(/^session-/, '').slice(0, 8),
1881
+ by,
1882
+ sessionId,
1883
+ )
1884
+ saveBoard(next, owner)
1885
+ })
1886
+ return { ok: delivered.ok, mode: delivered.ok ? 'created' : 'pending', sessionId: createdId, deployResult, text: packet }
1887
+ }
1888
+
1889
+ let deployResult = null
1890
+ if (deployChief && rootSid && target !== rootSid) {
1891
+ deployResult = deployStateToTargetChief(runtime, {
1892
+ fromSessionId: rootSid,
1893
+ toSessionId: target,
1894
+ archiveTransferPolicy,
1895
+ archiveDrawer,
1896
+ toCabinetId,
1897
+ customNote,
1898
+ })
1899
+ }
1900
+
1901
+ const agents = runtime.get('agents')
1902
+ const agent = agents && typeof agents.get === 'function' ? agents.get(target) : undefined
1903
+ if (!agent) {
1904
+ writePending({ at: nowMs(), by, session: sessionId, text: packet, failedTarget: target })
1905
+ return {
1906
+ ok: Boolean(deployResult && deployResult.ok),
1907
+ error: deployResult && deployResult.ok ? '' : '目标会话没有活的 agent:已改成待领取,下次新会话可取',
1908
+ mode: 'pending',
1909
+ deployResult,
1910
+ text: packet,
1911
+ }
1912
+ }
1913
+ const delivered = await injectInto(agent, packet)
1914
+ const owner = boardFileFor(sessionId)
1915
+ withBoardLock(owner, () => {
1916
+ const next = loadBoard(owner)
1917
+ pushLog(
1918
+ next,
1919
+ (delivered.ok ? '交接单与参谋已投放到会话 ' : '投放失败(' + delivered.error + '):') + String(target).replace(/^session-/, '').slice(0, 8),
1920
+ by,
1921
+ sessionId,
1922
+ )
1923
+ saveBoard(next, owner)
1924
+ })
1925
+ if (!delivered.ok) {
1926
+ writePending({ at: nowMs(), by, session: sessionId, text: packet, failedTarget: target })
1927
+ return { ok: false, error: delivered.error, mode: 'pending', deployResult, text: packet }
1928
+ }
1929
+ return { ok: true, mode: 'injected', target, deployResult, text: packet }
1930
+ }
1931
+
1932
+ return {
1933
+ forcesShared,
1934
+ isObjectiveLockedByIntervention,
1935
+ runAction,
1936
+ runActionUnlocked,
1937
+ boundaries,
1938
+ archiveTarget,
1939
+ composeHandoffFromNarrative,
1940
+ resolveEffectiveHandoff,
1941
+ collectTakenOutAndFlipped,
1942
+ collectDigestArchiveContext,
1943
+ syncPlanFromTodos,
1944
+ syncObjective,
1945
+ buildHandoffMessage,
1946
+ injectInto,
1947
+ deployStateToTargetChief,
1948
+ transferChief,
1949
+ }
1950
+ }