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