dsh-chief 1.5.0 → 1.7.0

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