dsh-chief 1.2.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/api-routes.js ADDED
@@ -0,0 +1,1291 @@
1
+ /**
2
+ * api-routes.js
3
+ *
4
+ * Same-origin HTTP route table and request guards for the DSH Chief browser panel.
5
+ */
6
+
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import { renderDigest } from './digest.js'
10
+ import { memorySections, renderMemoryDigest } from './memory.js'
11
+ import {
12
+ loadChiefState,
13
+ resolveWorkspaceConfig,
14
+ getLinkedCluster,
15
+ setPeerLink,
16
+ listChiefModels,
17
+ deliverCrossMessage,
18
+ getChiefView,
19
+ recommendAndSetCompactThreshold,
20
+ askOrCommandChief,
21
+ consolidateBoundsWithChief,
22
+ organizeArchivesWithChief,
23
+ harvestTurnDetailsToArchive,
24
+ precipitateExperienceWithChief,
25
+ distillSessionArchivesToGlobal,
26
+ updateWorkspaceFlippedIds,
27
+ proposeBoundToChief,
28
+ handleSuggestionDecision,
29
+ executeBatchSuggestions,
30
+ updateChiefConfig,
31
+ suggestCoreObjectiveWithChief,
32
+ relayArchivesWithChief,
33
+ mutateChiefFact,
34
+ handleApprovalDecision,
35
+ handleElevationDecision,
36
+ } from './chief.js'
37
+ import { getChiefActiveWork } from './chief-state.js'
38
+ import {
39
+ resolveProjectKey,
40
+ getArchiveMeta,
41
+ getThreeTierArchiveCounts,
42
+ listArchiveHeaders,
43
+ getArchiveDetail,
44
+ mutateArchive,
45
+ getTakenOutArchivesForSession,
46
+ getTakenOutGlobalForSession,
47
+ getFlippedOutPrecipitatedForSession,
48
+ getPrecipitatedDetail,
49
+ mutatePrecipitated,
50
+ copyPrecipitatedToVault,
51
+ } from './archives.js'
52
+ import {
53
+ DEFAULT_CHIEF_PERMISSION_MODE,
54
+ HUMAN_BOUNDS_CONFIRM_TOKEN,
55
+ listGuardWalls,
56
+ } from './chief-executor.js'
57
+ import {
58
+ API,
59
+ BACKEND_BUILD,
60
+ BODY_LIMIT,
61
+ emptyBoard,
62
+ normalizeBoundFieldName,
63
+ guardCount,
64
+ pushLog,
65
+ safe,
66
+ } from './board-schema.js'
67
+
68
+ export function createApiRoutes(deps) {
69
+
70
+ const archiveTarget = (...args) => deps.archiveTarget(...args)
71
+ const boardFile = (...args) => deps.boardFile(...args)
72
+ const boardFileFor = (...args) => deps.boardFileFor(...args)
73
+ const boardForSession = (...args) => deps.boardForSession(...args)
74
+ const boundaries = (...args) => deps.boundaries(...args)
75
+ const collectDigestArchiveContext = (...args) => deps.collectDigestArchiveContext(...args)
76
+ const executeSubagentAction = (...args) => deps.executeSubagentAction(...args)
77
+ const fetchTeamTasks = (...args) => deps.fetchTeamTasks(...args)
78
+ const getSessionContextBreakdown = (...args) => deps.getSessionContextBreakdown(...args)
79
+ const linkedPeersForSession = (...args) => deps.linkedPeersForSession(...args)
80
+ const loadBoard = (...args) => deps.loadBoard(...args)
81
+ const makeChiefDeps = (...args) => deps.makeChiefDeps(...args)
82
+ const probeSubagentSupport = (...args) => deps.probeSubagentSupport(...args)
83
+ const readPending = (...args) => deps.readPending(...args)
84
+ const refreshSubagentTree = (...args) => deps.refreshSubagentTree(...args)
85
+ const resolveAgentIdentity = (...args) => deps.resolveAgentIdentity(...args)
86
+ const resolveEffectiveHandoff = (...args) => deps.resolveEffectiveHandoff(...args)
87
+ const resolveRootSessionId = (...args) => deps.resolveRootSessionId(...args)
88
+ const runAction = (...args) => deps.runAction(...args)
89
+ const saveBoard = (...args) => deps.saveBoard(...args)
90
+ const sessionName = (...args) => deps.sessionName(...args)
91
+ const transcriptTimes = (...args) => deps.transcriptTimes(...args)
92
+ const transferChief = (...args) => deps.transferChief(...args)
93
+ const withBoardLock = (...args) => deps.withBoardLock(...args)
94
+
95
+ /* ---------------------------------------------------------------------- routes */
96
+
97
+ function sendJson(res, status, value) {
98
+ const body = JSON.stringify(value)
99
+ res.statusCode = status
100
+ res.setHeader('content-type', 'application/json; charset=utf-8')
101
+ res.setHeader('cache-control', 'no-store')
102
+ res.end(body)
103
+ }
104
+
105
+ function readBody(req) {
106
+ return new Promise((resolve, reject) => {
107
+ const chunks = []
108
+ let size = 0
109
+ req.on('data', chunk => {
110
+ size += chunk.length
111
+ if (size > BODY_LIMIT) {
112
+ reject(new Error('body too large'))
113
+ req.destroy()
114
+ return
115
+ }
116
+ chunks.push(chunk)
117
+ })
118
+ req.on('end', () => {
119
+ const text = Buffer.concat(chunks).toString('utf8').trim()
120
+ if (!text) return resolve({})
121
+ try {
122
+ resolve(JSON.parse(text))
123
+ } catch (error) {
124
+ reject(error)
125
+ }
126
+ })
127
+ req.on('error', reject)
128
+ })
129
+ }
130
+
131
+ function resolveArchiveHttpScope(raw) {
132
+ const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
133
+ if (s === 'global') return 'global'
134
+ if (s === 'precipitated' || s === 'cold' || s === 'vault') return 'precipitated'
135
+ return 'session'
136
+ }
137
+
138
+ function resolveBoundRootSid(sessionId = '') {
139
+ const raw = String(sessionId || '').trim()
140
+ if (!raw || raw === 'global') return ''
141
+ const root = String(resolveRootSessionId(raw) || raw).trim()
142
+ return (!root || root === 'global') ? '' : root
143
+ }
144
+
145
+ function collectDeskItemsForUi(runtime, rootId, cabinetId = '') {
146
+ if (!rootId) return []
147
+ const targetOpt = archiveTarget(runtime, rootId, { cabinetId, vaultScope: 'session' })
148
+ const out = []
149
+ try {
150
+ for (const it of getTakenOutArchivesForSession(rootId, targetOpt)) {
151
+ out.push({ id: it.id, scope: 'session', title: it.title, summary: it.summary || '', folder: it.folder || 'inbox', paperclip: it.paperclip || 'silver' })
152
+ }
153
+ } catch {}
154
+ try {
155
+ const gOpt = archiveTarget(runtime, rootId, { cabinetId: '', vaultScope: 'global' })
156
+ for (const it of getTakenOutGlobalForSession(rootId, gOpt)) {
157
+ out.push({ id: it.id, scope: 'global', title: it.title, summary: it.summary || '', folder: it.folder || 'coords', paperclip: it.paperclip || 'silver' })
158
+ }
159
+ } catch {}
160
+ try {
161
+ const st = loadChiefState()
162
+ const ws = st && st.workspaces && st.workspaces[rootId]
163
+ const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
164
+ if (flippedIds.length) {
165
+ const pk = resolveProjectKey(targetOpt.cwd)
166
+ for (const it of getFlippedOutPrecipitatedForSession(pk, rootId, true, targetOpt)) {
167
+ out.push({ id: it.id, scope: 'precipitated', title: it.title, summary: it.summary || '', folder: it.category || 'contracts', paperclip: 'gold' })
168
+ }
169
+ }
170
+ } catch {}
171
+ return out
172
+ }
173
+
174
+ function routeTable(runtime) {
175
+ const guard = (req, res) => {
176
+ const connection = runtime.get('connection')
177
+ if (connection && typeof connection.requestRejection === 'function') {
178
+ try {
179
+ const rejection = connection.requestRejection({ headers: req.headers })
180
+ if (rejection) {
181
+ sendJson(res, rejection, { ok: false, error: rejection === 401 ? 'unauthorized' : 'forbidden' })
182
+ return false
183
+ }
184
+ } catch (err) {
185
+ console.warn('[dsh-chief] request guard check failed; failing closed:', err && err.message ? err.message : err)
186
+ sendJson(res, 403, { ok: false, error: 'forbidden (guard check failed)' })
187
+ return false
188
+ }
189
+ }
190
+ return true
191
+ }
192
+
193
+ return [
194
+ {
195
+ path: API + '/snapshot',
196
+ handler: async (req, res) => {
197
+ if (!guard(req, res)) return
198
+ try {
199
+ let sessionId = ''
200
+ try {
201
+ sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
202
+ } catch {}
203
+ const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
204
+ const subagents = sessionId ? await refreshSubagentTree(runtime, sessionId, board) : []
205
+ const agentIdentity = sessionId ? resolveAgentIdentity(runtime, sessionId) : null
206
+ const secState = loadChiefState()
207
+ const rootSid = resolveRootSessionId(sessionId) || sessionId || 'global'
208
+ const cluster = getLinkedCluster(secState, rootSid)
209
+ let pendingSuggestions = 0
210
+ let factsCount = 0
211
+ let mailboxCount = 0
212
+ for (const cid of cluster) {
213
+ const ws = secState.workspaces && secState.workspaces[cid]
214
+ if (!ws) continue
215
+ if (Array.isArray(ws.suggestions)) pendingSuggestions += ws.suggestions.filter(s => s.status === 'pending').length
216
+ if (Array.isArray(ws.facts)) factsCount += ws.facts.length
217
+ if (Array.isArray(ws.mailbox)) mailboxCount += ws.mailbox.length
218
+ }
219
+ let followModelRef = ''
220
+ try {
221
+ const agentsSvc = runtime && runtime.get('agents')
222
+ const ag = agentsSvc && typeof agentsSvc.get === 'function' ? (agentsSvc.get(sessionId) || agentsSvc.get(rootSid)) : null
223
+ const hdr = ag && ag.session && typeof ag.session.requestHeader === 'function'
224
+ ? ag.session.requestHeader()
225
+ : (ag && ag.session && ag.session.header ? ag.session.header : null)
226
+ const hcfg = hdr && hdr.config ? hdr.config : hdr
227
+ if (hcfg && hcfg.provider && hcfg.model && !String(hcfg.provider).startsWith('local-agent')) {
228
+ followModelRef = `${hcfg.provider}/${hcfg.model}`
229
+ } else {
230
+ const defSel = runtime && runtime.get('agentDefaultModel')?.currentSelection?.()
231
+ if (defSel && defSel.provider && defSel.model && !String(defSel.provider).startsWith('local-agent')) {
232
+ followModelRef = `${defSel.provider}/${defSel.model}`
233
+ }
234
+ }
235
+ } catch {}
236
+ const effCfg = resolveWorkspaceConfig(secState, rootSid)
237
+ let pinnedModelRef = effCfg.modelRef || ''
238
+ if (pinnedModelRef) {
239
+ try {
240
+ const llmSvc = runtime && runtime.get('llm')
241
+ if (llmSvc && typeof llmSvc.listProviders === 'function') {
242
+ const provs = new Set((llmSvc.listProviders() || []).map(p => p && p.id).filter(Boolean))
243
+ const pName = pinnedModelRef.split('/')[0]
244
+ if (provs.size > 0 && !provs.has(pName)) pinnedModelRef = ''
245
+ }
246
+ } catch {}
247
+ }
248
+ const rootWs = secState.workspaces && secState.workspaces[rootSid]
249
+ const tacticalModes = effCfg.tacticalModes || {}
250
+ const flippedIds = (rootWs && Array.isArray(rootWs.flippedPrecipitatedIds)) ? rootWs.flippedPrecipitatedIds.slice() : []
251
+ const boundRootSid = resolveBoundRootSid(sessionId)
252
+ const sessionArchOpt = archiveTarget(runtime, boundRootSid, { cabinetId: board.activeCabinetId, vaultScope: 'session' })
253
+ const archiveMeta = {
254
+ ...getArchiveMeta(boundRootSid, sessionArchOpt),
255
+ counts: getThreeTierArchiveCounts(boundRootSid, flippedIds, sessionArchOpt),
256
+ }
257
+ const hostCompat = probeSubagentSupport(runtime)
258
+ sendJson(res, 200, {
259
+ ok: true,
260
+ board,
261
+ subagents,
262
+ agentIdentity,
263
+ teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
264
+ boundaries: boundaries(runtime, sessionId),
265
+ hostCompat,
266
+ chiefMeta: {
267
+ backendBuild: BACKEND_BUILD,
268
+ hostCompat,
269
+ paceMode: effCfg.paceMode || 'manual',
270
+ stopped: Boolean(effCfg.stopped || effCfg.paceMode === 'stopped'),
271
+ permissionMode: effCfg.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
272
+ capabilities: effCfg.capabilities || {},
273
+ policyPluginsCount: Array.isArray(effCfg.policyPlugins) ? effCfg.policyPlugins.length : 0,
274
+ chiefRiskAcknowledged: Boolean(effCfg.chiefRiskVerified),
275
+ pendingApprovalsCount: ((rootWs && Array.isArray(rootWs.pendingApprovals)) ? rootWs.pendingApprovals : []).filter(a => a && a.status === 'pending').length,
276
+ hasPendingElevation: Boolean(rootWs && rootWs.pendingElevation && rootWs.pendingElevation.status === 'pending'),
277
+ auditLog: ((rootWs && Array.isArray(rootWs.auditLog)) ? rootWs.auditLog : []).slice(-50).reverse(),
278
+ autoPilot: Boolean(effCfg.autoPilot),
279
+ tacticalModes,
280
+ runtimeGuard: (rootWs && rootWs.runtimeGuard) || {},
281
+ flippedCount: flippedIds.length,
282
+ modelRef: pinnedModelRef,
283
+ followModelRef,
284
+ resolvedModelRef: pinnedModelRef || followModelRef || '',
285
+ pendingSuggestions,
286
+ factsCount,
287
+ mailboxCount,
288
+ linkedPeersCount: Math.max(0, cluster.length - 1),
289
+ activeWork: getChiefActiveWork(rootSid),
290
+ contextUsage: sessionId ? getSessionContextBreakdown(runtime, sessionId) : null,
291
+ },
292
+ archiveMeta,
293
+ guardWalls: listGuardWalls({ cwd: sessionArchOpt.cwd }),
294
+ })
295
+ } catch (error) {
296
+ sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
297
+ }
298
+ },
299
+ },
300
+ {
301
+ path: API + '/digest',
302
+ handler: async (req, res) => {
303
+ if (!guard(req, res)) return
304
+ try {
305
+ let sessionId = ''
306
+ try {
307
+ sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
308
+ } catch {}
309
+ const board = sessionId ? loadBoard(boardFileFor(sessionId)) : emptyBoard()
310
+ const fullBoard = sessionId ? boardForSession(boardFileFor(sessionId)) : board
311
+ const subagents = sessionId ? await refreshSubagentTree(runtime, sessionId, fullBoard) : []
312
+ const agentIdentity = sessionId ? resolveAgentIdentity(runtime, sessionId) : null
313
+ const rootSid = resolveRootSessionId(sessionId) || sessionId
314
+ const linked = linkedPeersForSession(runtime, rootSid)
315
+ const archCtx = collectDigestArchiveContext(runtime, rootSid, fullBoard.activeCabinetId)
316
+ sendJson(res, 200, {
317
+ ok: true,
318
+ digest: renderDigest(fullBoard, {
319
+ subagents,
320
+ agentIdentity,
321
+ teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
322
+ takenOutArchives: archCtx.takenOutArchives,
323
+ sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
324
+ smartCompactActive: archCtx.smartCompactActive,
325
+ chiefPermissionMode: archCtx.chiefPermissionMode,
326
+ linkedPeersCount: linked.linkedPeersCount,
327
+ linkedPeersProgress: linked.linkedPeersProgress,
328
+ }),
329
+ sessions: board.sessions || {},
330
+ updatedAt: board.updatedAt,
331
+ })
332
+ } catch (error) {
333
+ sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
334
+ }
335
+ },
336
+ },
337
+ {
338
+ path: API + '/memory',
339
+ handler: (req, res) => {
340
+ if (!guard(req, res)) return
341
+ let sessionId = ''
342
+ try {
343
+ sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
344
+ } catch {}
345
+ const board = sessionId ? loadBoard(boardFileFor(sessionId)) : emptyBoard()
346
+ sendJson(res, 200, {
347
+ ok: true,
348
+ sections: memorySections(board, 8),
349
+ count: (board.memory || []).length,
350
+ digest: renderMemoryDigest(board, 400),
351
+ settings: board.settings || {},
352
+ updatedAt: board.updatedAt,
353
+ })
354
+ },
355
+ },
356
+ {
357
+ path: API + '/transfer',
358
+ handler: async (req, res) => {
359
+ if (!guard(req, res)) return
360
+ try {
361
+ const body = await readBody(req)
362
+ const result = await transferChief(runtime, body, typeof body.session === 'string' ? body.session : '')
363
+ sendJson(res, result.ok ? 200 : 400, result)
364
+ } catch (error) {
365
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
366
+ }
367
+ },
368
+ },
369
+ {
370
+ path: API + '/sessions',
371
+ handler: (req, res) => {
372
+ if (!guard(req, res)) return
373
+ let sessionId = ''
374
+ try {
375
+ sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
376
+ } catch {}
377
+ const agents = runtime.get('agents')
378
+ const own = loadBoard(boardFileFor(sessionId))
379
+ const shared = loadBoard()
380
+ const fresher = (a, b) => ((a && a.lastSeen) || 0) >= ((b && b.lastSeen) || 0) ? a : b
381
+ const heartbeat = id => {
382
+ const a = (own.sessions || {})[id]
383
+ const b = (shared.sessions || {})[id]
384
+ return fresher(a, b) || {}
385
+ }
386
+ const settings = shared.settings || {}
387
+ const list = agents && typeof agents.list === 'function' ? agents.list() : []
388
+ const archived = safe(() => runtime.get('workspaceRegistry').archivedSessionIds, [])
389
+ const retired = Array.isArray(archived) ? archived : []
390
+ const live = list.filter(agent => {
391
+ const id = String(agent.id)
392
+ return id === sessionId || !retired.includes(id)
393
+ })
394
+ const touched = transcriptTimes()
395
+ sendJson(res, 200, {
396
+ ok: true,
397
+ sessions: live.map(agent => {
398
+ const id = String(agent.id)
399
+ const row = heartbeat(id)
400
+ const seen = row.lastSeen || touched.get(id) || 0
401
+ return {
402
+ id,
403
+ name: sessionName(runtime, agent),
404
+ turns: row.turns || 0,
405
+ lastSeen: seen,
406
+ }
407
+ }),
408
+ archived: retired.length,
409
+ pending: readPending() ? { at: readPending().at, by: readPending().by } : null,
410
+ autoInject: !(settings.autoInject === false),
411
+ guardIdle: !(settings.guardIdle === false),
412
+ guardMaxPerSession: guardCount(settings.guardMaxPerSession, 3, 0, 20),
413
+ guardShortAnswer: guardCount(settings.guardShortAnswer, 600, 0, 10000),
414
+ })
415
+ },
416
+ },
417
+ {
418
+ path: API + '/handoff',
419
+ handler: (req, res) => {
420
+ if (!guard(req, res)) return
421
+ let sessionId = ''
422
+ try {
423
+ sessionId = new URL(req.url || '/', 'http://127.0.0.1').searchParams.get('session') || ''
424
+ } catch {}
425
+ const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
426
+ const pending = readPending()
427
+ const hInfo = resolveEffectiveHandoff(runtime, sessionId, board)
428
+ sendJson(res, 200, {
429
+ ok: true,
430
+ text: hInfo.text,
431
+ autoText: hInfo.autoText,
432
+ source: hInfo.source,
433
+ isCustom: hInfo.isCustom,
434
+ pinned: hInfo.pinned,
435
+ pinnedAt: hInfo.pinnedAt,
436
+ pinnedBy: hInfo.pinnedBy,
437
+ updatedAt: hInfo.updatedAt,
438
+ handoffAt: hInfo.handoffAt,
439
+ syncOnDigest: hInfo.syncOnDigest,
440
+ isIncomplete: hInfo.isIncomplete,
441
+ isStale: hInfo.isStale,
442
+ hasNarrativeUpdate: hInfo.hasNarrativeUpdate,
443
+ autoInject: !((board.settings || {}).autoInject === false),
444
+ guardIdle: !((board.settings || {}).guardIdle === false),
445
+ pending: pending ? { at: pending.at, by: pending.by, failedTarget: pending.failedTarget || '' } : null,
446
+ })
447
+ },
448
+ },
449
+ {
450
+ path: API + '/action',
451
+ handler: async (req, res) => {
452
+ if (!guard(req, res)) return
453
+ try {
454
+ const body = await readBody(req)
455
+ const sessionId = body && typeof body.session === 'string' ? body.session : ''
456
+ const actName = body && typeof body.action === 'string' ? body.action : ''
457
+ if (actName === 'bounds.propose') {
458
+ const propRes = proposeBoundToChief(makeChiefDeps(runtime), {
459
+ sessionId,
460
+ by: typeof body.by === 'string' ? body.by : 'operator',
461
+ field: normalizeBoundFieldName(body.field) || 'forbidden',
462
+ item: typeof body.item === 'string' ? body.item : (typeof body.text === 'string' ? body.text : ''),
463
+ items: Array.isArray(body.items) ? body.items : undefined,
464
+ reason: typeof body.reason === 'string' ? body.reason : '',
465
+ })
466
+ const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
467
+ const subagents = sessionId ? await refreshSubagentTree(runtime, sessionId, board) : []
468
+ sendJson(res, propRes.ok ? 200 : 400, {
469
+ ...propRes,
470
+ board,
471
+ subagents,
472
+ boundaries: boundaries(runtime, sessionId),
473
+ })
474
+ return
475
+ }
476
+ if (actName === 'task.dispatch' || actName === 'team.steer' || actName === 'team.interrupt') {
477
+ const subResult = await executeSubagentAction(runtime, body, null)
478
+ sendJson(res, subResult.ok ? 200 : 400, {
479
+ ...subResult,
480
+ boundaries: boundaries(runtime, sessionId),
481
+ })
482
+ return
483
+ }
484
+ const result = runAction({
485
+ ...(body && typeof body === 'object' ? body : {}),
486
+ _callerOrigin: 'human_ui',
487
+ _humanConfirmToken: HUMAN_BOUNDS_CONFIRM_TOKEN,
488
+ })
489
+ const mergedBoard = result.ok && result.board && sessionId
490
+ ? boardForSession(boardFileFor(sessionId))
491
+ : result.board
492
+ const subagents = sessionId && mergedBoard ? await refreshSubagentTree(runtime, sessionId, mergedBoard) : []
493
+ let actionCwd = process.cwd()
494
+ try { actionCwd = archiveTarget(runtime, sessionId, { vaultScope: 'session' }).cwd || actionCwd } catch {}
495
+ sendJson(res, result.ok ? 200 : 400, {
496
+ ...result,
497
+ ...(mergedBoard ? { board: mergedBoard } : {}),
498
+ ...(Array.isArray(result.guardWalls) ? {} : { guardWalls: listGuardWalls({ cwd: actionCwd }) }),
499
+ subagents,
500
+ boundaries: boundaries(runtime, sessionId),
501
+ })
502
+ } catch (error) {
503
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
504
+ }
505
+ },
506
+ },
507
+ {
508
+ path: API + '/chief/view',
509
+ handler: async (req, res) => {
510
+ if (!guard(req, res)) return
511
+ try {
512
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
513
+ let sessionId = url.searchParams.get('session') || ''
514
+ let regenerate = url.searchParams.get('regenerate') === '1'
515
+ const qSync = url.searchParams.get('syncHandoff')
516
+ let syncHandoff = qSync === '1' || qSync === 'true' ? true : (qSync === '0' || qSync === 'false' ? false : undefined)
517
+ if (req.method === 'POST') {
518
+ const body = await readBody(req).catch(() => ({}))
519
+ if (typeof body.session === 'string' && body.session) sessionId = body.session
520
+ if (body.regenerate === true) regenerate = true
521
+ if (typeof body.syncHandoff === 'boolean') syncHandoff = body.syncHandoff
522
+ }
523
+ const view = await getChiefView(makeChiefDeps(runtime), sessionId, { regenerate, autoSummarize: !regenerate, syncHandoff })
524
+ if (view && view.handoffSyncResult && view.handoffSyncResult.synced && sessionId) {
525
+ sendJson(res, 200, { ...view, board: boardForSession(boardFileFor(sessionId)) })
526
+ return
527
+ }
528
+ sendJson(res, 200, view)
529
+ } catch (error) {
530
+ sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
531
+ }
532
+ },
533
+ },
534
+ {
535
+ path: API + '/chief/ask',
536
+ handler: async (req, res) => {
537
+ if (!guard(req, res)) return
538
+ try {
539
+ const body = await readBody(req)
540
+ const sessionId = typeof body.session === 'string' ? body.session : ''
541
+ const out = await askOrCommandChief(makeChiefDeps(runtime), {
542
+ sessionId,
543
+ text: typeof body.text === 'string' ? body.text : '',
544
+ forcedTarget: typeof body.target === 'string' ? body.target : '',
545
+ forcedMode: typeof body.mode === 'string' ? body.mode : 'steer',
546
+ images: Array.isArray(body.images) ? body.images : [],
547
+ })
548
+ const board = out.ok && sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
549
+ sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
550
+ } catch (error) {
551
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
552
+ }
553
+ },
554
+ },
555
+ {
556
+ path: API + '/chief/relay-archives',
557
+ handler: async (req, res) => {
558
+ if (!guard(req, res)) return
559
+ try {
560
+ const body = await readBody(req)
561
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
562
+ const rootSid = resolveRootSessionId(sessionId) || sessionId || 'global'
563
+ const out = await relayArchivesWithChief(makeChiefDeps(runtime), {
564
+ sessionId: rootSid,
565
+ items: Array.isArray(body?.items) ? body.items : [],
566
+ instruction: typeof body?.instruction === 'string' ? body.instruction : '',
567
+ target: typeof body?.target === 'string' ? body.target : 'lead',
568
+ mode: typeof body?.mode === 'string' ? body.mode : 'steer',
569
+ cabinetId: typeof body?.cabinetId === 'string' ? body.cabinetId : '',
570
+ })
571
+ sendJson(res, out && out.ok === false ? 400 : 200, out)
572
+ } catch (error) {
573
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
574
+ }
575
+ },
576
+ },
577
+ {
578
+ path: API + '/chief/relay',
579
+ handler: async (req, res) => {
580
+ if (!guard(req, res)) return
581
+ try {
582
+ const body = await readBody(req)
583
+ const sessionId = typeof body.session === 'string' ? body.session : ''
584
+ const out = await deliverCrossMessage(makeChiefDeps(runtime), {
585
+ fromSession: sessionId,
586
+ fromLabel: typeof body.by === 'string' && body.by ? body.by : 'DSH 参谋长',
587
+ target: typeof body.target === 'string' ? body.target : 'lead',
588
+ subject: typeof body.subject === 'string' ? body.subject : '',
589
+ text: typeof body.text === 'string' ? body.text : '',
590
+ mode: typeof body.mode === 'string' ? body.mode : 'steer',
591
+ images: Array.isArray(body.images) ? body.images : [],
592
+ })
593
+ const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
594
+ sendJson(res, out.ok ? 200 : 400, { ...out, view })
595
+ } catch (error) {
596
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
597
+ }
598
+ },
599
+ },
600
+ {
601
+ path: API + '/chief/models',
602
+ handler: async (req, res) => {
603
+ if (!guard(req, res)) return
604
+ try {
605
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
606
+ const fresh = url.searchParams.get('fresh') === '1'
607
+ const sessionId = url.searchParams.get('session') || ''
608
+ const catalog = await listChiefModels(makeChiefDeps(runtime), fresh, sessionId)
609
+ sendJson(res, 200, { ok: true, ...catalog })
610
+ } catch (error) {
611
+ sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
612
+ }
613
+ },
614
+ },
615
+ {
616
+ path: API + '/chief/config',
617
+ handler: async (req, res) => {
618
+ if (!guard(req, res)) return
619
+ try {
620
+ const body = await readBody(req)
621
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
622
+ const rootSid = resolveRootSessionId(sessionId) || sessionId || 'global'
623
+ const updated = updateChiefConfig({ ...(body || {}), sessionId: rootSid })
624
+ const wantsInterventionOn = Boolean(body && body.tacticalModes && body.tacticalModes.intervention === true)
625
+ const coreObjDraft = typeof body?.coreObjective === 'string' ? body.coreObjective.trim() : ''
626
+ const targetSessionForBoard = sessionId || (rootSid !== 'global' ? rootSid : '')
627
+ if (updated && updated.ok !== false && wantsInterventionOn && coreObjDraft && targetSessionForBoard) {
628
+ runAction({
629
+ action: 'objective.set',
630
+ objective: coreObjDraft,
631
+ session: targetSessionForBoard,
632
+ by: 'operator',
633
+ _fromInterventionSetup: true,
634
+ })
635
+ }
636
+ if (updated && (updated.emergencyStopped || (updated.config && (updated.config.stopped || updated.config.paceMode === 'stopped')))) {
637
+ if (deps.hostState.activeAutoContinue && typeof deps.hostState.activeAutoContinue.cancelSession === 'function') {
638
+ deps.hostState.activeAutoContinue.cancelSession(sessionId, 'chief stopped')
639
+ if (rootSid && rootSid !== sessionId) deps.hostState.activeAutoContinue.cancelSession(rootSid, 'chief stopped')
640
+ }
641
+ }
642
+ const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
643
+ const latestBoard = targetSessionForBoard ? boardForSession(boardFileFor(targetSessionForBoard)) : null
644
+ sendJson(res, updated && updated.ok === false ? 400 : 200, {
645
+ ...updated,
646
+ ...(latestBoard ? { board: latestBoard } : {}),
647
+ view,
648
+ })
649
+ } catch (error) {
650
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
651
+ }
652
+ },
653
+ },
654
+ {
655
+ path: API + '/chief/approval',
656
+ handler: async (req, res) => {
657
+ if (!guard(req, res)) return
658
+ try {
659
+ const body = await readBody(req)
660
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
661
+ const out = await handleApprovalDecision(makeChiefDeps(runtime), {
662
+ sessionId,
663
+ approvalId: typeof body?.id === 'string' ? body.id : '',
664
+ decision: body?.decision === 'approve' ? 'approve' : 'reject',
665
+ })
666
+ const board = out.ok && sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
667
+ sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
668
+ } catch (error) {
669
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
670
+ }
671
+ },
672
+ },
673
+ {
674
+ path: API + '/chief/elevation',
675
+ handler: async (req, res) => {
676
+ if (!guard(req, res)) return
677
+ try {
678
+ const body = await readBody(req)
679
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
680
+ const out = await handleElevationDecision(makeChiefDeps(runtime), {
681
+ sessionId,
682
+ elevationId: typeof body?.id === 'string' ? body.id : '',
683
+ decision: body?.decision === 'approve' ? 'approve' : 'reject',
684
+ targetMode: typeof body?.targetMode === 'string' ? body.targetMode : '',
685
+ confirmedChiefRisk: Boolean(body?.confirmedChiefRisk),
686
+ })
687
+ const board = sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
688
+ sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
689
+ } catch (error) {
690
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
691
+ }
692
+ },
693
+ },
694
+ {
695
+ path: API + '/chief/suggest-objective',
696
+ handler: async (req, res) => {
697
+ if (!guard(req, res)) return
698
+ try {
699
+ const body = await readBody(req).catch(() => ({}))
700
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
701
+ const out = await suggestCoreObjectiveWithChief(makeChiefDeps(runtime), {
702
+ sessionId,
703
+ draft: typeof body?.draft === 'string' ? body.draft : '',
704
+ mode: typeof body?.mode === 'string' ? body.mode : 'auto',
705
+ previousSuggestions: Array.isArray(body?.previousSuggestions) ? body.previousSuggestions : [],
706
+ })
707
+ sendJson(res, out && out.ok === false ? 400 : 200, out)
708
+ } catch (error) {
709
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
710
+ }
711
+ },
712
+ },
713
+ {
714
+ path: API + '/chief/recommend-compact',
715
+ handler: async (req, res) => {
716
+ if (!guard(req, res)) return
717
+ try {
718
+ const body = await readBody(req).catch(() => ({}))
719
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
720
+ const out = await recommendAndSetCompactThreshold(makeChiefDeps(runtime), { sessionId })
721
+ sendJson(res, out && out.ok === false ? 400 : 200, out)
722
+ } catch (error) {
723
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
724
+ }
725
+ },
726
+ },
727
+ {
728
+ path: API + '/chief/link',
729
+ handler: async (req, res) => {
730
+ if (!guard(req, res)) return
731
+ try {
732
+ const body = await readBody(req)
733
+ const sessionId = typeof body.session === 'string' ? body.session : ''
734
+ const peerSession = typeof body.peerSession === 'string' ? body.peerSession : ''
735
+ const rootA = resolveRootSessionId(sessionId) || sessionId
736
+ const rootB = resolveRootSessionId(peerSession) || peerSession
737
+ const linked = Boolean(body.linked)
738
+ const out = setPeerLink(rootA, rootB, linked)
739
+ if (!out.ok) {
740
+ sendJson(res, 400, out)
741
+ return
742
+ }
743
+ const view = await getChiefView(makeChiefDeps(runtime), rootA, { autoSummarize: false })
744
+ sendJson(res, 200, { ...out, view })
745
+ } catch (error) {
746
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
747
+ }
748
+ },
749
+ },
750
+ {
751
+ path: API + '/chief/suggestion',
752
+ handler: async (req, res) => {
753
+ if (!guard(req, res)) return
754
+ try {
755
+ const body = await readBody(req)
756
+ const sessionId = typeof body.session === 'string' ? body.session : ''
757
+ const isBatch = body.decision === 'execute_batch' || body.batch === true
758
+ const out = isBatch
759
+ ? await executeBatchSuggestions(makeChiefDeps(runtime), {
760
+ sessionId,
761
+ ids: Array.isArray(body.ids) ? body.ids : [],
762
+ includeGoalApproval: Boolean(body.includeGoalApproval),
763
+ pinGlobalDefault: typeof body.pinGlobal === 'boolean'
764
+ ? body.pinGlobal
765
+ : (typeof body.pinGlobalDefault === 'boolean' ? body.pinGlobalDefault : undefined),
766
+ })
767
+ : await handleSuggestionDecision(makeChiefDeps(runtime), {
768
+ sessionId,
769
+ suggestionId: typeof body.id === 'string' ? body.id : '',
770
+ decision: body.decision === 'approve' ? 'approve' : 'dismiss',
771
+ editedText: typeof body.text === 'string' ? body.text : '',
772
+ boundField: typeof body.boundField === 'string' ? body.boundField : '',
773
+ pinGlobal: typeof body.pinGlobal === 'boolean' ? body.pinGlobal : undefined,
774
+ })
775
+ const board = out.ok && sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
776
+ sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
777
+ } catch (error) {
778
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
779
+ }
780
+ },
781
+ },
782
+ {
783
+ path: API + '/chief/consolidate-bounds',
784
+ handler: async (req, res) => {
785
+ if (!guard(req, res)) return
786
+ try {
787
+ const body = await readBody(req)
788
+ const sessionId = typeof body.session === 'string' ? body.session : ''
789
+ const out = await consolidateBoundsWithChief(makeChiefDeps(runtime), {
790
+ sessionId,
791
+ field: typeof body.field === 'string' ? body.field : '',
792
+ items: Array.isArray(body.items) ? body.items : [],
793
+ instruction: typeof body.instruction === 'string' ? body.instruction : '',
794
+ })
795
+ const board = sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
796
+ sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
797
+ } catch (error) {
798
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
799
+ }
800
+ },
801
+ },
802
+ {
803
+ path: API + '/chief/fact',
804
+ handler: async (req, res) => {
805
+ if (!guard(req, res)) return
806
+ try {
807
+ const body = await readBody(req)
808
+ const sessionId = typeof body.session === 'string' ? body.session : ''
809
+ const out = mutateChiefFact(makeChiefDeps(runtime), {
810
+ sessionId,
811
+ op: typeof body.op === 'string' ? body.op : 'add',
812
+ id: typeof body.id === 'string' ? body.id : '',
813
+ text: typeof body.text === 'string' ? body.text : '',
814
+ category: typeof body.category === 'string' ? body.category : 'discipline',
815
+ pinned: Boolean(body.pinned),
816
+ })
817
+ if (!out.ok) {
818
+ sendJson(res, 400, out)
819
+ return
820
+ }
821
+ const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
822
+ sendJson(res, 200, { ...out, view })
823
+ } catch (error) {
824
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
825
+ }
826
+ },
827
+ },
828
+ {
829
+ path: API + '/archives',
830
+ handler: async (req, res) => {
831
+ if (!guard(req, res)) return
832
+ try {
833
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
834
+ if (req.method === 'GET' || !req.method) {
835
+ const sessionId = url.searchParams.get('session') || ''
836
+ const rootSid = resolveBoundRootSid(sessionId)
837
+ const query = url.searchParams.get('q') || ''
838
+ const folder = url.searchParams.get('folder') || ''
839
+ const paperclip = url.searchParams.get('paperclip') || ''
840
+ const reqScope = resolveArchiveHttpScope(url.searchParams.get('scope') || url.searchParams.get('vaultScope') || '')
841
+ const workingScope = reqScope === 'global' ? 'global' : 'session'
842
+ const cabinetId = workingScope === 'global' ? '' : (url.searchParams.get('cabinetId') || '')
843
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: workingScope })
844
+ const st = loadChiefState()
845
+ const ws = rootSid && st.workspaces ? st.workspaces[rootSid] : null
846
+ const flippedIds = (ws && Array.isArray(ws.flippedPrecipitatedIds)) ? ws.flippedPrecipitatedIds.slice() : []
847
+ const out = listArchiveHeaders(rootSid, {
848
+ query,
849
+ folder,
850
+ paperclip,
851
+ vaultScope: workingScope,
852
+ includePrecipitated: true,
853
+ flippedIds,
854
+ }, targetOpt)
855
+ sendJson(res, 200, {
856
+ ...out,
857
+ requestedScope: reqScope,
858
+ flippedPrecipitatedIds: flippedIds,
859
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
860
+ counts: out.counts || getThreeTierArchiveCounts(rootSid, flippedIds, targetOpt),
861
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
862
+ })
863
+ return
864
+ }
865
+
866
+ const body = await readBody(req)
867
+ const sessionId = typeof body.session === 'string' ? body.session : ''
868
+ const rootSid = resolveBoundRootSid(sessionId)
869
+ const op = typeof body.op === 'string' ? body.op : 'save'
870
+ const reqScope = resolveArchiveHttpScope(body.vaultScope || body.scope || '')
871
+ const workingScope = reqScope === 'global' ? 'global' : 'session'
872
+ const cabinetId = workingScope === 'global' ? '' : (typeof body.cabinetId === 'string' ? body.cabinetId : '')
873
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: workingScope })
874
+ const projectKey = resolveProjectKey(targetOpt.cwd)
875
+
876
+ if (['flipOut', 'sealBack', 'deletePrecipitated', 'updatePrecipitated'].includes(op)) {
877
+ const pid = typeof body.id === 'string' ? body.id : (typeof body.precipitatedId === 'string' ? body.precipitatedId : '')
878
+ const pRes = mutatePrecipitated(projectKey, {
879
+ ...body,
880
+ id: pid,
881
+ precipitatedId: pid,
882
+ op,
883
+ rootSessionId: rootSid,
884
+ }, targetOpt)
885
+ if (!pRes.ok) {
886
+ sendJson(res, 400, pRes)
887
+ return
888
+ }
889
+ if (rootSid) {
890
+ if (op === 'flipOut' && pid) updateWorkspaceFlippedIds(rootSid, { flippedId: pid })
891
+ else if ((op === 'sealBack' || op === 'deletePrecipitated') && pid) updateWorkspaceFlippedIds(rootSid, { sealId: pid })
892
+ }
893
+ const stAfter = loadChiefState()
894
+ const wsAfter = rootSid && stAfter.workspaces ? stAfter.workspaces[rootSid] : null
895
+ const flippedAfter = (wsAfter && Array.isArray(wsAfter.flippedPrecipitatedIds)) ? wsAfter.flippedPrecipitatedIds.slice() : []
896
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedAfter }, targetOpt)
897
+ sendJson(res, 200, {
898
+ ...pRes,
899
+ archives,
900
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
901
+ counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedAfter, targetOpt),
902
+ flippedPrecipitatedIds: flippedAfter,
903
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
904
+ })
905
+ return
906
+ }
907
+
908
+ if (op === 'pullPrecipitated') {
909
+ const pid = typeof body.id === 'string' ? body.id : (typeof body.precipitatedId === 'string' ? body.precipitatedId : '')
910
+ const targetScope = resolveArchiveHttpScope(body.targetScope || body.toScope || 'session') === 'global' ? 'global' : 'session'
911
+ const copyRes = copyPrecipitatedToVault(projectKey, {
912
+ ...body,
913
+ id: pid,
914
+ precipitatedId: pid,
915
+ targetScope,
916
+ rootSessionId: rootSid,
917
+ }, targetOpt)
918
+ if (!copyRes.ok) {
919
+ sendJson(res, 400, copyRes)
920
+ return
921
+ }
922
+ const stAfter = loadChiefState()
923
+ const wsAfter = rootSid && stAfter.workspaces ? stAfter.workspaces[rootSid] : null
924
+ const flippedAfter = (wsAfter && Array.isArray(wsAfter.flippedPrecipitatedIds)) ? wsAfter.flippedPrecipitatedIds.slice() : []
925
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedAfter }, targetOpt)
926
+ sendJson(res, 200, {
927
+ ...copyRes,
928
+ archives,
929
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
930
+ counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedAfter, targetOpt),
931
+ flippedPrecipitatedIds: flippedAfter,
932
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
933
+ })
934
+ return
935
+ }
936
+
937
+ if (op === 'precipitateNotes') {
938
+ // Sweep active board.notes (session / rootSession / matched shared notes) into active working cabinet
939
+ const NOTE_SWEEP_SECRET_RE = /(?:sk-[a-zA-Z0-9_-]{16,}|ghp_[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|Bearer\s+[A-Za-z0-9._~+/=-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----|-----BEGIN [A-Z ]*PRIVATE KEY-----)/g
940
+ const noteIds = Array.isArray(body.noteIds) && body.noteIds.length > 0
941
+ ? new Set(body.noteIds.map(String))
942
+ : null
943
+ let sweptCount = 0
944
+ const sweptIds = new Set()
945
+ const savedFolders = new Set()
946
+ let lastCabId = ''
947
+
948
+ const saveNoteIntoArchive = (note) => {
949
+ const paperclip = (note.pinned || (note.tags || []).includes('anchor')) ? 'gold' : undefined
950
+ const basePayload = {
951
+ op: 'save',
952
+ vaultScope: workingScope,
953
+ sourceNoteId: note.id,
954
+ title: note.title,
955
+ body: note.body,
956
+ tags: note.tags,
957
+ paperclip,
958
+ by: note.by || 'user',
959
+ rootSessionId: rootSid,
960
+ }
961
+ let saved = mutateArchive(basePayload, targetOpt)
962
+ if (!saved.ok && typeof saved.error === 'string' && /秘钥|凭据|密钥|SECRET|Token/i.test(saved.error)) {
963
+ const redactedTitle = String(note.title || '').replace(NOTE_SWEEP_SECRET_RE, '[REDACTED]')
964
+ const redactedBody = String(note.body || '').replace(NOTE_SWEEP_SECRET_RE, '[REDACTED]')
965
+ saved = mutateArchive({
966
+ ...basePayload,
967
+ title: redactedTitle,
968
+ body: redactedBody,
969
+ }, targetOpt)
970
+ }
971
+ return saved
972
+ }
973
+
974
+ const sweepFromFile = (targetFile, { allowUnfiltered = true } = {}) => {
975
+ if (!targetFile || !fs.existsSync(targetFile)) return
976
+ withBoardLock(targetFile, () => {
977
+ const b = loadBoard(targetFile)
978
+ if (!Array.isArray(b.notes) || !b.notes.length) return
979
+ const keep = []
980
+ let fileSwept = 0
981
+ let changed = false
982
+ for (const note of b.notes) {
983
+ if (!note || !note.id) {
984
+ keep.push(note)
985
+ continue
986
+ }
987
+ if (sweptIds.has(note.id)) {
988
+ changed = true
989
+ continue
990
+ }
991
+ if (noteIds) {
992
+ if (!noteIds.has(note.id)) {
993
+ keep.push(note)
994
+ continue
995
+ }
996
+ } else if (!allowUnfiltered && (note.pinned || (Array.isArray(note.tags) && note.tags.includes('anchor')))) {
997
+ keep.push(note)
998
+ continue
999
+ }
1000
+ const saved = saveNoteIntoArchive(note)
1001
+ if (saved.ok) {
1002
+ sweptCount += 1
1003
+ fileSwept += 1
1004
+ changed = true
1005
+ sweptIds.add(note.id)
1006
+ if (saved.item && saved.item.folder) savedFolders.add(saved.item.folder)
1007
+ const cab = (saved.meta && saved.meta.activeCabinetId) || saved.activeCabinetId || saved.cabinetId || ''
1008
+ if (cab) lastCabId = cab
1009
+ } else {
1010
+ keep.push(note)
1011
+ }
1012
+ }
1013
+ if (changed) {
1014
+ b.notes = keep
1015
+ if (fileSwept > 0) {
1016
+ pushLog(b, `🗄️ 已将 ${fileSwept} 篇便签收纳进「${workingScope === 'global' ? '全局' : '本会话'}档案柜」`, 'operator', sessionId)
1017
+ }
1018
+ saveBoard(b, targetFile)
1019
+ }
1020
+ })
1021
+ }
1022
+
1023
+ if (sessionId) {
1024
+ const candidateFiles = []
1025
+ const addFile = (f, allowUnfiltered) => {
1026
+ if (!f) return
1027
+ const norm = path.resolve(f)
1028
+ if (!candidateFiles.some(x => x.norm === norm)) {
1029
+ candidateFiles.push({ file: f, norm, allowUnfiltered })
1030
+ }
1031
+ }
1032
+ addFile(boardFileFor(sessionId), true)
1033
+ if (rootSid && rootSid !== sessionId) addFile(boardFileFor(rootSid), true)
1034
+ for (const cand of candidateFiles) {
1035
+ sweepFromFile(cand.file, { allowUnfiltered: cand.allowUnfiltered })
1036
+ }
1037
+ if ((noteIds && sweptIds.size < noteIds.size) || sweptCount === 0) {
1038
+ sweepFromFile(boardFile(), { allowUnfiltered: false })
1039
+ }
1040
+ } else {
1041
+ sweepFromFile(boardFile(), { allowUnfiltered: true })
1042
+ }
1043
+
1044
+ if (rootSid && workingScope !== 'global' && lastCabId) {
1045
+ const bFile = boardFileFor(rootSid)
1046
+ withBoardLock(bFile, () => {
1047
+ const b = loadBoard(bFile)
1048
+ if (!b.activeCabinetId) {
1049
+ b.activeCabinetId = lastCabId
1050
+ saveBoard(b, bFile)
1051
+ }
1052
+ })
1053
+ }
1054
+
1055
+ const finalOpt = archiveTarget(runtime, rootSid || sessionId, {
1056
+ cabinetId: lastCabId || cabinetId,
1057
+ vaultScope: workingScope,
1058
+ })
1059
+ const stNow = loadChiefState()
1060
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
1061
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
1062
+ const board = sessionId ? boardForSession(boardFileFor(sessionId)) : boardForSession(boardFile())
1063
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedNow }, finalOpt)
1064
+ sendJson(res, 200, {
1065
+ ok: true,
1066
+ sweptCount,
1067
+ savedFolders: [...savedFolders],
1068
+ board,
1069
+ archives,
1070
+ deskItems: collectDeskItemsForUi(runtime, rootSid, lastCabId || cabinetId || ''),
1071
+ counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedNow, finalOpt),
1072
+ archiveMeta: getArchiveMeta(rootSid, finalOpt),
1073
+ })
1074
+ return
1075
+ }
1076
+
1077
+ const out = mutateArchive({
1078
+ ...body,
1079
+ vaultScope: workingScope,
1080
+ op,
1081
+ rootSessionId: rootSid,
1082
+ }, targetOpt)
1083
+ if (!out.ok) {
1084
+ sendJson(res, 400, out)
1085
+ return
1086
+ }
1087
+ const isCrossCopy = op === 'copyToGlobal' || op === 'copyToSession'
1088
+ const usedCabId = out.activeCabinetId || out.cabinetId || ''
1089
+ if (rootSid && workingScope !== 'global' && !isCrossCopy && usedCabId && op !== 'listCabinets') {
1090
+ const bFile = boardFileFor(rootSid)
1091
+ withBoardLock(bFile, () => {
1092
+ const b = loadBoard(bFile)
1093
+ if (op === 'switchCabinet' || op === 'createCabinet' || !b.activeCabinetId) {
1094
+ b.activeCabinetId = usedCabId
1095
+ saveBoard(b, bFile)
1096
+ }
1097
+ })
1098
+ }
1099
+ const stNow = loadChiefState()
1100
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
1101
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
1102
+ const finalOpt = isCrossCopy
1103
+ ? targetOpt
1104
+ : archiveTarget(runtime, rootSid || sessionId, { cabinetId: out.activeCabinetId || cabinetId || out.cabinetId, vaultScope: workingScope })
1105
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedNow }, finalOpt)
1106
+ const board = sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
1107
+ sendJson(res, 200, {
1108
+ ...out,
1109
+ archives,
1110
+ deskItems: collectDeskItemsForUi(runtime, rootSid, out.activeCabinetId || cabinetId || out.cabinetId || ''),
1111
+ diffSummary: out.diffSummary || archives.diffSummary,
1112
+ counts: out.counts || archives.counts || getThreeTierArchiveCounts(rootSid, flippedNow, finalOpt),
1113
+ ...(board ? { board } : {}),
1114
+ archiveMeta: getArchiveMeta(rootSid, finalOpt),
1115
+ })
1116
+ } catch (error) {
1117
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
1118
+ }
1119
+ },
1120
+ },
1121
+ {
1122
+ path: API + '/archives/detail',
1123
+ handler: (req, res) => {
1124
+ if (!guard(req, res)) return
1125
+ try {
1126
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
1127
+ const id = url.searchParams.get('id') || ''
1128
+ const sessionId = url.searchParams.get('session') || ''
1129
+ const reqScope = resolveArchiveHttpScope(url.searchParams.get('scope') || url.searchParams.get('vaultScope') || '')
1130
+ const cabinetId = reqScope === 'global' ? '' : (url.searchParams.get('cabinetId') || '')
1131
+ const isPrecip = url.searchParams.get('precipitated') === '1' || url.searchParams.get('precipitated') === 'true' || reqScope === 'precipitated'
1132
+ const rootSid = resolveBoundRootSid(sessionId)
1133
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: reqScope === 'global' ? 'global' : 'session' })
1134
+ const out = isPrecip
1135
+ ? getPrecipitatedDetail(resolveProjectKey(targetOpt.cwd), id, rootSid, targetOpt)
1136
+ : getArchiveDetail(id, rootSid, targetOpt)
1137
+ sendJson(res, out.ok ? 200 : 404, out)
1138
+ } catch (error) {
1139
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
1140
+ }
1141
+ },
1142
+ },
1143
+ {
1144
+ path: API + '/archives/organize',
1145
+ handler: async (req, res) => {
1146
+ if (!guard(req, res)) return
1147
+ try {
1148
+ const body = await readBody(req)
1149
+ const sessionId = typeof body.session === 'string' ? body.session : ''
1150
+ const rootSid = resolveBoundRootSid(sessionId)
1151
+ const vaultScope = resolveArchiveHttpScope(body.vaultScope || body.scope) === 'global' ? 'global' : 'session'
1152
+ const cabinetId = vaultScope === 'global' ? '' : (typeof body.cabinetId === 'string' ? body.cabinetId : '')
1153
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope })
1154
+ const out = await organizeArchivesWithChief(makeChiefDeps(runtime), {
1155
+ sessionId: rootSid || 'global',
1156
+ vaultScope,
1157
+ cabinetId,
1158
+ ids: Array.isArray(body.ids) ? body.ids : [],
1159
+ folder: typeof body.folder === 'string' ? body.folder : '',
1160
+ scope: typeof body.scope === 'string' ? body.scope : 'unorganized',
1161
+ instruction: typeof body.instruction === 'string' ? body.instruction : '',
1162
+ })
1163
+ const stNow = loadChiefState()
1164
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
1165
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
1166
+ sendJson(res, out.ok ? 200 : 400, {
1167
+ ...out,
1168
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
1169
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
1170
+ })
1171
+ } catch (error) {
1172
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
1173
+ }
1174
+ },
1175
+ },
1176
+ {
1177
+ path: API + '/archives/distill-to-global',
1178
+ handler: async (req, res) => {
1179
+ if (!guard(req, res)) return
1180
+ try {
1181
+ const body = await readBody(req)
1182
+ const sessionId = typeof body.session === 'string' ? body.session : ''
1183
+ const rootSid = resolveBoundRootSid(sessionId)
1184
+ if (!rootSid) {
1185
+ sendJson(res, 400, { ok: false, error: '当前未绑定具体会话,无法从本会话档案柜提炼' })
1186
+ return
1187
+ }
1188
+ const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
1189
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: 'session' })
1190
+ const out = await distillSessionArchivesToGlobal(makeChiefDeps(runtime), {
1191
+ sessionId: rootSid,
1192
+ cabinetId,
1193
+ ids: Array.isArray(body.ids) ? body.ids : null,
1194
+ folder: typeof body.folder === 'string' ? body.folder : '',
1195
+ clearSource: Boolean(body.clearSource),
1196
+ instruction: typeof body.instruction === 'string' ? body.instruction : '',
1197
+ })
1198
+ const stNow = loadChiefState()
1199
+ const wsNow = stNow.workspaces ? stNow.workspaces[rootSid] : null
1200
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
1201
+ sendJson(res, out.ok ? 200 : 400, {
1202
+ ...out,
1203
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
1204
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
1205
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
1206
+ })
1207
+ } catch (error) {
1208
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
1209
+ }
1210
+ },
1211
+ },
1212
+ {
1213
+ path: API + '/archives/harvest',
1214
+ handler: async (req, res) => {
1215
+ if (!guard(req, res)) return
1216
+ try {
1217
+ const body = await readBody(req)
1218
+ const sessionId = typeof body.session === 'string' ? body.session : ''
1219
+ const rootSid = resolveBoundRootSid(sessionId)
1220
+ const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
1221
+ const vaultScope = 'session'
1222
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope })
1223
+ const out = await harvestTurnDetailsToArchive(makeChiefDeps(runtime), {
1224
+ sessionId: rootSid,
1225
+ vaultScope,
1226
+ cabinetId,
1227
+ trigger: 'manual',
1228
+ focusHint: typeof body.focusHint === 'string' ? body.focusHint : '',
1229
+ })
1230
+ const stNow = loadChiefState()
1231
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
1232
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
1233
+ sendJson(res, out.ok ? 200 : 400, {
1234
+ ...out,
1235
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
1236
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
1237
+ })
1238
+ } catch (error) {
1239
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
1240
+ }
1241
+ },
1242
+ },
1243
+ {
1244
+ path: API + '/archives/precipitate',
1245
+ handler: async (req, res) => {
1246
+ if (!guard(req, res)) return
1247
+ try {
1248
+ const body = await readBody(req)
1249
+ const sessionId = typeof body.session === 'string' ? body.session : ''
1250
+ const rootSid = resolveRootSessionId(sessionId) || sessionId
1251
+ const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
1252
+ const vaultScope = resolveArchiveHttpScope(body.vaultScope || body.scope) === 'global' ? 'global' : 'session'
1253
+ if (vaultScope !== 'global') {
1254
+ sendJson(res, 400, { ok: false, error: '实行三级梯度制度:本会话档案请先升级入「🌐 全局档案柜」,再从全局档案柜沉淀为冷档案' })
1255
+ return
1256
+ }
1257
+ const targetOpt = archiveTarget(runtime, rootSid || sessionId, { cabinetId, vaultScope })
1258
+ const out = await precipitateExperienceWithChief(makeChiefDeps(runtime), {
1259
+ sessionId: rootSid,
1260
+ vaultScope,
1261
+ op: typeof body.op === 'string' ? body.op : 'cabinet',
1262
+ cabinetId,
1263
+ folder: typeof body.folder === 'string' ? body.folder : '',
1264
+ ids: Array.isArray(body.ids) ? body.ids : [],
1265
+ clearSource: Boolean(body.clearSource),
1266
+ })
1267
+ const stNow = loadChiefState()
1268
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
1269
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
1270
+ sendJson(res, out.ok ? 200 : 400, {
1271
+ ...out,
1272
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
1273
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
1274
+ })
1275
+ } catch (error) {
1276
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
1277
+ }
1278
+ },
1279
+ },
1280
+ ]
1281
+ }
1282
+
1283
+ return {
1284
+ sendJson,
1285
+ readBody,
1286
+ resolveArchiveHttpScope,
1287
+ resolveBoundRootSid,
1288
+ collectDeskItemsForUi,
1289
+ routeTable,
1290
+ }
1291
+ }