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/chief-state.js CHANGED
@@ -1,2523 +1,1996 @@
1
- /**
2
- * chief-state.js
3
- *
4
- * State, configuration, persistence, workspace lifecycle, and shared pure helpers for DSH Chief.
5
- */
6
-
7
- import fs from 'node:fs'
8
- import path from 'node:path'
9
- import os from 'node:os'
10
- import crypto from 'node:crypto'
11
- import { threadId } from 'node:worker_threads'
12
- import {
13
- resolveProjectKey,
14
- loadArchiveStore,
15
- loadGlobalVaultRaw,
16
- getChiefMountedGlobalForSession,
17
- getTakenOutGlobalForSession,
18
- collectSealedWatchSummary,
19
- getFlippedOutPrecipitatedForSession,
20
- } from './archives.js'
21
- import {
22
- DEFAULT_CHIEF_PERMISSION_MODE,
23
- CHIEF_PERMISSION_META,
24
- normalizePermissionMode,
25
- permissionRank,
26
- auditJsonlPath as safetyAuditJsonlPath,
27
- normalizeAuditRecord,
28
- appendAuditJsonlRecord,
29
- resolveRoleCapabilities,
30
- buildCapabilityScope,
31
- validatePolicyPluginList,
32
- } from './safety/index.js'
33
-
34
- const APPROVALS_CAP = 30
35
-
36
- const AUDIT_LOG_CAP = 80
37
-
38
- const RESUME_TASKS_CAP = 20
39
-
40
- const TASK_LEDGER_CAP = 30
41
-
42
- const DEFAULT_RESUME_TTL_MS = 30 * 60 * 1000
43
-
44
- const STATE_VERSION = 1
45
-
46
- const activeResumingTaskIds = new Set()
47
-
48
- export function markTaskResumingActive(taskId) {
49
- const id = String(taskId || '').trim()
50
- if (id) activeResumingTaskIds.add(id)
51
- }
52
-
53
- export function unmarkTaskResumingActive(taskId) {
54
- const id = String(taskId || '').trim()
55
- if (id) activeResumingTaskIds.delete(id)
56
- }
57
-
58
- export const FACTS_CAP = 120
59
-
60
- export const FACT_TEXT_MAX = 260
61
-
62
- export const CHAT_CAP = 36
63
-
64
- export const MAIL_CAP = 80
65
-
66
- export const SUGGESTIONS_CAP = 6
67
-
68
- export const MODEL_TIMEOUT_MS = 90_000
69
-
70
- export const CATALOG_TTL_MS = 10_000
71
-
72
- export const REVIEW_DELAY_MS = 2_800
73
-
74
- export const AUTO_SUMMARY_COOLDOWN_MS = 5 * 60_000
75
-
76
- export const SMART_REVIEW_COOLDOWN_MS = 3 * 60_000
77
-
78
- export const AUTO_REVIEW_COOLDOWN_MS = 90_000
79
-
80
- // Thinking models spend several thousand output tokens on internal reasoning before emitting text;
81
- // small caps (e.g. 2k-4k) starve the visible answer to empty string.
82
- export const SUMMARY_MAX_TOKENS = 16_384
83
-
84
- export const SUMMARY_RETRY_MAX_TOKENS = 32_768
85
-
86
- export const CHIEF_UPDATE_SOURCE = 'dsh-chief-update'
87
-
88
- export const CHIEF_RELAY_SOURCE = 'dsh-chief-relay'
89
-
90
- export const CHIEF_INQUIRY_SOURCE = 'dsh-chief-inquiry'
91
-
92
- export const CHIEF_EXEC_REQ_SOURCE = 'dsh-chief-execution-request'
93
-
94
- export const CHAT_OPPORTUNISTIC_SUMMARY_COOLDOWN_MS = 60_000
95
-
96
- export const CHIEF_RUN_MODES = ['off', 'patrol', 'managed']
97
-
98
- export const DEFAULT_MANAGED_IDLE_TIMEOUT_MS = 15 * 60 * 1000
99
-
100
- export const CHIEF_THINKING_EFFORTS = ['auto', 'off', 'low', 'medium', 'high', 'xhigh']
101
-
102
- export function normalizeRunMode(raw, fallbackCfg = null) {
103
- const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
104
- if (s === 'off' || s === 'patrol' || s === 'managed') return s
105
- if (s === 'stopped' || s === 'manual') return 'off'
106
- if (s === 'smart') return 'patrol'
107
- if (s === 'auto' || s === 'autopilot') return 'managed'
108
- if (fallbackCfg && typeof fallbackCfg === 'object') {
109
- if (fallbackCfg.stopped || fallbackCfg.paceMode === 'stopped') return 'off'
110
- if (fallbackCfg.autoPilot || fallbackCfg.paceMode === 'auto') return 'managed'
111
- if (fallbackCfg.paceMode === 'smart') return 'patrol'
112
- }
113
- return 'off'
114
- }
115
-
116
- export function normalizeThinkingEffort(raw) {
117
- const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
118
- if (CHIEF_THINKING_EFFORTS.includes(s)) return s
119
- return 'auto'
120
- }
121
-
122
- function normalizeTeamEffortMode(raw) {
123
- return String(raw || '').trim().toLowerCase() === 'manual' ? 'manual' : 'auto'
124
- }
125
-
126
- export function normalizeLockedModelEfforts(raw) {
127
- const out = {}
128
- if (!raw || typeof raw !== 'object') return out
129
- for (const [k, v] of Object.entries(raw)) {
130
- const cleanKey = String(k || '').trim().slice(0, 64)
131
- if (!cleanKey) continue
132
- if (v === true) out[cleanKey] = true
133
- }
134
- return out
135
- }
136
-
137
- const EFFORT_ORDER_LADDER = ['off', 'low', 'medium', 'high', 'xhigh']
138
-
139
- export function resolveAlignedModelEffort(desiredEffort, supportedEfforts = []) {
140
- const list = Array.isArray(supportedEfforts)
141
- ? supportedEfforts.map(e => (typeof e === 'string' ? e : (e && e.id ? String(e.id) : ''))).filter(Boolean)
142
- : []
143
- if (!list.length) return undefined
144
- const want = String(desiredEffort || '').trim().toLowerCase()
145
- if (!want || want === 'auto') {
146
- if (list.includes('medium')) return 'medium'
147
- return list[Math.floor(list.length / 2)] || list[0]
148
- }
149
- if (list.includes(want)) return want
150
- const wantIdx = EFFORT_ORDER_LADDER.indexOf(want)
151
- if (wantIdx < 0) return list[0]
152
- for (let d = 1; d < EFFORT_ORDER_LADDER.length; d += 1) {
153
- if (wantIdx - d >= 0 && list.includes(EFFORT_ORDER_LADDER[wantIdx - d])) {
154
- return EFFORT_ORDER_LADDER[wantIdx - d]
155
- }
156
- if (wantIdx + d < EFFORT_ORDER_LADDER.length && list.includes(EFFORT_ORDER_LADDER[wantIdx + d])) {
157
- return EFFORT_ORDER_LADDER[wantIdx + d]
158
- }
159
- }
160
- return list[0]
161
- }
162
-
163
- export function touchWorkspaceActivity(sessionId) {
164
- const sid = String(sessionId || '').trim()
165
- if (!sid || sid === 'global') return false
166
- try {
167
- mutateChiefState((state) => {
168
- const ws = ensureWorkspace(state, sid)
169
- if (!ws.runtimeGuard || typeof ws.runtimeGuard !== 'object') ws.runtimeGuard = {}
170
- ws.runtimeGuard.lastActivityAt = Date.now()
171
- })
172
- return true
173
- } catch {
174
- return false
175
- }
176
- }
177
-
178
- const SECRET_PATTERN = /(?: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-----)/
179
-
180
- let dshAttachmentModulePromise = null
181
-
182
- async function loadDshAttachment() {
183
- if (!dshAttachmentModulePromise) {
184
- dshAttachmentModulePromise = import('@deepseek-ai/dsh-attachment').catch(() => null)
185
- }
186
- return dshAttachmentModulePromise
187
- }
188
-
189
- const CHIEF_MAX_IMAGES = 4
190
-
191
- const CHIEF_IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
192
-
193
- function normalizeUploadedImage(raw, idx = 0) {
194
- if (!raw || typeof raw !== 'object') return null
195
- let mediaType = String(raw.mediaType || raw.mimeType || raw.type || '').trim().toLowerCase()
196
- let data = String(raw.data || raw.base64 || '').trim()
197
- const dataUrlMatch = data.match(/^data:([^;]+);base64,(.+)$/is)
198
- if (dataUrlMatch) {
199
- if (!mediaType) mediaType = dataUrlMatch[1].trim().toLowerCase()
200
- data = dataUrlMatch[2].trim()
201
- }
202
- if (mediaType === 'image/jpg') mediaType = 'image/jpeg'
203
- data = data.replace(/\s+/g, '')
204
- if (!CHIEF_IMAGE_MEDIA_TYPES.has(mediaType) || !data) return null
205
- const ext = mediaType === 'image/jpeg' ? 'jpg' : (mediaType.split('/')[1] || 'png')
206
- const name = typeof raw.name === 'string' && raw.name.trim()
207
- ? clamp(raw.name.trim(), 80)
208
- : `chief-image-${idx + 1}.${ext}`
209
- return { name, mediaType, data }
210
- }
211
-
212
- export function resolveSessionWorkspaceCwd(deps, sessionId) {
213
- const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || sessionId
214
- try {
215
- if (deps && typeof deps.getSessionCwd === 'function') {
216
- const c = deps.getSessionCwd(rootId) || deps.getSessionCwd(sessionId)
217
- if (c && fs.existsSync(c)) return c
218
- }
219
- if (deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function') {
220
- const b = deps.boardForSession(deps.boardFileFor(rootId))
221
- const sess = b && b.sessions && (b.sessions[rootId] || b.sessions[sessionId])
222
- if (sess && sess.cwd && fs.existsSync(sess.cwd)) return sess.cwd
223
- }
224
- } catch {}
225
- return process.cwd()
226
- }
227
-
228
- export function archiveTargetForRoot(deps, rootId, extra = '') {
229
- const opts = extra && typeof extra === 'object' ? extra : { cabinetId: String(extra || '') }
230
- const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
231
- const sharedFile = deps && (typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile)
232
- const cwd = resolveSessionWorkspaceCwd(deps, rootId)
233
- let cab = opts.cabinetId ? String(opts.cabinetId).trim() : ''
234
- if (vaultScope !== 'global' && !cab && deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function' && rootId && rootId !== 'global') {
235
- try {
236
- const b = deps.boardForSession(deps.boardFileFor(rootId))
237
- if (b && typeof b.activeCabinetId === 'string') cab = b.activeCabinetId.trim()
238
- } catch {}
239
- }
240
- return {
241
- customSharedBoardFile: sharedFile || '',
242
- cwd,
243
- vaultScope,
244
- ...(vaultScope !== 'global' && rootId && rootId !== 'global' ? { rootSessionId: String(rootId).trim() } : {}),
245
- ...(cab ? { cabinetId: cab } : {}),
246
- }
247
- }
248
-
249
- /**
250
- * Chief-of-Staff visibility matrix (Three-Tier Hook Architecture):
251
- * - Session Working Cabinet: Chief can always read session items + `recentlyUnpinnedWatch`.
252
- * - Global Vault: Unorganized global items (without hooks) are 0-token invisible to Chief!
253
- * Organized global items expose ONLY lightweight `globalHookIndex` (`hasHook: true`),
254
- * until Chief explicitly pulls/mounts them (`chiefMountedSessions` / `chiefPulledSessions`).
255
- * - Precipitated Cold Vault: 100% invisible to Chief (0 disk read, 0 hook leak) unless User explicitly `flippedOut`!
256
- */
257
- export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null) {
258
- const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
259
- const sessionTarget = sid ? archiveTargetForRoot(deps, sid, { vaultScope: 'session' }) : null
260
- const globalTarget = archiveTargetForRoot(deps, sid || 'global', { vaultScope: 'global' })
261
- const baseOpt = sessionTarget || globalTarget
262
- const projectKey = resolveProjectKey(baseOpt.cwd)
263
-
264
- let deskSessionItems = []
265
- let deskGlobalItems = []
266
- let deskFlippedItems = []
267
- let mountedGlobalItems = []
268
- let sessionItems = []
269
- let recentlyUnpinnedWatch = []
270
- let globalHookIndex = []
271
- let sealedWatch = { sessionSealed: [], globalSealed: [], precipSealed: [] }
272
-
273
- try {
274
- if (sessionTarget) {
275
- const stSess = loadArchiveStore(sessionTarget)
276
- const allSess = Array.isArray(stSess.items) ? stSess.items : []
277
- deskSessionItems = allSess.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).slice(0, 6)
278
- sessionItems = allSess.slice(0, 16).map(it => ({
279
- id: it.id,
280
- title: it.title,
281
- folder: it.folder,
282
- summary: it.summary,
283
- paperclip: it.paperclip,
284
- hasHook: Boolean(it.hasHook),
285
- hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
286
- hookCue: it.hookCue || '',
287
- takenOut: Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid),
288
- points: Array.isArray(it.points) ? it.points.slice(0, 3) : [],
289
- }))
290
- recentlyUnpinnedWatch = Array.isArray(stSess.recentlyUnpinnedWatch) ? stSess.recentlyUnpinnedWatch.slice() : []
291
- }
292
- } catch {}
293
- try {
294
- const gStore = loadGlobalVaultRaw(globalTarget)
295
- const gAll = Array.isArray(gStore && gStore.items) ? gStore.items : []
296
- if (sid) {
297
- deskGlobalItems = getTakenOutGlobalForSession(sid, globalTarget).slice(0, 6)
298
- mountedGlobalItems = getChiefMountedGlobalForSession(sid, globalTarget).slice(0, 6)
299
- // Also include entries Chief pulled in this session
300
- const pulledSet = new Set(mountedGlobalItems.map(x => x.id))
301
- for (const g of gAll) {
302
- if (g && Array.isArray(g.chiefPulledSessions) && g.chiefPulledSessions.includes(sid) && !pulledSet.has(g.id)) {
303
- mountedGlobalItems.push(g)
304
- pulledSet.add(g.id)
305
- if (mountedGlobalItems.length >= 6) break
306
- }
307
- }
308
- }
309
- globalHookIndex = gAll
310
- .filter(it =>
311
- it
312
- && it.hasHook === true
313
- && (!sid || (!Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid)))
314
- && (!sid || (!Array.isArray(it.chiefMountedSessions) || !it.chiefMountedSessions.includes(sid)))
315
- && (!sid || (!Array.isArray(it.chiefPulledSessions) || !it.chiefPulledSessions.includes(sid)))
316
- )
317
- .slice(0, 12)
318
- .map(it => ({
319
- id: it.id,
320
- title: it.title,
321
- folder: it.folder,
322
- paperclip: it.paperclip,
323
- hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
324
- hookCue: it.hookCue || '',
325
- }))
326
- } catch {}
327
- try {
328
- if (sid) {
329
- const st = stateSnapshot || loadChiefState()
330
- const ws = st && st.workspaces && st.workspaces[sid]
331
- const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
332
- if (flippedIds.length > 0) {
333
- deskFlippedItems = getFlippedOutPrecipitatedForSession(projectKey, sid, true, baseOpt).slice(0, 6)
334
- }
335
- }
336
- } catch {}
337
- try {
338
- sealedWatch = collectSealedWatchSummary(sid, projectKey, baseOpt, { limitPerVault: 8 })
339
- } catch {}
340
-
341
- return {
342
- deskSessionItems,
343
- deskGlobalItems,
344
- deskFlippedItems,
345
- mountedGlobalItems,
346
- sessionItems,
347
- recentlyUnpinnedWatch,
348
- globalHookIndex,
349
- sealedWatch,
350
- sessionTarget,
351
- globalTarget,
352
- }
353
- }
354
-
355
- /** Persist raw uploaded images onto local workspace `.dsh-chief/uploads/` so any agent can inspect raw files even when LLM vision is unavailable. */
356
- export function persistChiefImagesToWorkspace(deps, sessionId, rawImages) {
357
- const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
358
- if (!list.length) return []
359
- const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
360
- if (!normalized.length) return []
361
-
362
- const cwd = resolveSessionWorkspaceCwd(deps, sessionId)
363
- const uploadDir = path.join(cwd, '.dsh-chief', 'uploads')
364
- fs.mkdirSync(uploadDir, { recursive: true })
365
-
366
- const d = new Date()
367
- const stamp = [
368
- d.getFullYear(),
369
- String(d.getMonth() + 1).padStart(2, '0'),
370
- String(d.getDate()).padStart(2, '0'),
371
- ].join('') + '-' + [
372
- String(d.getHours()).padStart(2, '0'),
373
- String(d.getMinutes()).padStart(2, '0'),
374
- String(d.getSeconds()).padStart(2, '0'),
375
- ].join('')
376
-
377
- const saved = []
378
- for (let idx = 0; idx < normalized.length; idx += 1) {
379
- const img = normalized[idx]
380
- const ext = img.mediaType === 'image/jpeg' ? 'jpg' : (img.mediaType.split('/')[1] || 'png')
381
- const baseRaw = path.basename(String(img.name || `image-${idx + 1}`), path.extname(String(img.name || '')))
382
- const safeName = baseRaw.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || `image-${idx + 1}`
383
- const fileName = `${stamp}-${idx + 1}-${safeName}.${ext}`
384
- const absPath = path.join(uploadDir, fileName)
385
- const buf = Buffer.from(img.data, 'base64')
386
- fs.writeFileSync(absPath, buf)
387
- saved.push({
388
- index: idx + 1,
389
- path: absPath,
390
- name: img.name || fileName,
391
- mediaType: img.mediaType,
392
- bytes: buf.length,
393
- })
394
- }
395
- return saved
396
- }
397
-
398
- export async function admitChiefImages(deps, rawImages) {
399
- const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
400
- if (!list.length) return []
401
- const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
402
- if (!normalized.length) {
403
- throw new Error('上传的图片格式不受支持(仅支持 PNG / JPEG / WebP / GIF Base64)')
404
- }
405
-
406
- if (deps && typeof deps.admitImagesOverride === 'function') {
407
- const refs = await deps.admitImagesOverride(normalized)
408
- return (Array.isArray(refs) ? refs : []).filter(Boolean).map(attachment => ({ type: 'image', attachment }))
409
- }
410
-
411
- const attachmentsSvc = deps && typeof deps.getAttachments === 'function'
412
- ? deps.getAttachments()
413
- : (deps && deps.runtime && typeof deps.runtime.get === 'function' ? deps.runtime.get('attachments') : null)
414
- if (!attachmentsSvc) {
415
- throw new Error('当前 DSH 运行环境未挂载 attachments 图片服务,无法处理图片上传')
416
- }
417
-
418
- const attMod = await loadDshAttachment()
419
- if (attMod && typeof attMod.admitEncodedImages === 'function') {
420
- const refs = await attMod.admitEncodedImages(attachmentsSvc, normalized)
421
- return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
422
- }
423
-
424
- if (typeof attachmentsSvc.saveImages === 'function') {
425
- const payload = normalized.map(img => ({
426
- data: Uint8Array.from(Buffer.from(img.data, 'base64')),
427
- mediaType: img.mediaType,
428
- name: img.name,
429
- }))
430
- const refs = await attachmentsSvc.saveImages(payload)
431
- return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
432
- }
433
-
434
- throw new Error('attachments 服务缺少 saveImages / admitEncodedImages 接口')
435
- }
436
-
437
- let idSeq = 0
438
-
439
- export function nextId(prefix) {
440
- idSeq = (idSeq + 1) % 1000000
441
- return prefix + '-' + Date.now().toString(36) + '-' + idSeq.toString(36)
442
- }
443
-
444
- export function clamp(value, max) {
445
- const text = String(value == null ? '' : value).replace(/\s+/g, ' ').trim()
446
- if (text.length <= max) return text
447
- return text.slice(0, Math.max(0, max - 1)) + '…'
448
- }
449
-
450
- export function cleanMultiline(value, max) {
451
- const text = String(value == null ? '' : value).replace(/\r/g, '').trim()
452
- if (text.length <= max) return text
453
- return text.slice(0, Math.max(0, max - 1)) + '…'
454
- }
455
-
456
- export function secretLike(text) {
457
- return SECRET_PATTERN.test(String(text || ''))
458
- }
459
-
460
- function chiefDir() {
461
- const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
462
- return path.join(home, 'chief')
463
- }
464
-
465
- function stateFilePath() {
466
- return path.join(chiefDir(), 'chief-state.json')
467
- }
468
-
469
- export function auditJsonlPath() {
470
- return safetyAuditJsonlPath()
471
- }
472
-
473
- function canonicalSortJsonValue(val) {
474
- if (val === null || val === undefined) return null
475
- if (Array.isArray(val)) return val.map(v => canonicalSortJsonValue(v))
476
- if (typeof val === 'object') {
477
- const out = {}
478
- for (const k of Object.keys(val).sort()) {
479
- const v = val[k]
480
- if (v !== undefined) out[k] = canonicalSortJsonValue(v)
481
- }
482
- return out
483
- }
484
- return val
485
- }
486
-
487
- export function computeApprovalPayloadHash(kind = 'tool', payload = {}) {
488
- const canonical = JSON.stringify(canonicalSortJsonValue({
489
- kind: String(kind || 'tool'),
490
- payload: payload && typeof payload === 'object' ? payload : {},
491
- }))
492
- return crypto.createHash('sha256').update(canonical).digest('hex')
493
- }
494
-
495
- function normalizeChiefRiskAck(raw) {
496
- if (!raw || typeof raw !== 'object' || raw.acknowledged !== true) return null
497
- const at = Number(raw.at) || 0
498
- if (at <= 0) return null
499
- return {
500
- acknowledged: true,
501
- at,
502
- by: clamp(raw.by || 'operator', 40),
503
- version: clamp(raw.version || '1.2.1', 20),
504
- }
505
- }
506
-
507
- export function hasValidChiefRiskAck(ws) {
508
- return Boolean(ws && ws.chiefRiskAck && ws.chiefRiskAck.acknowledged === true && Number(ws.chiefRiskAck.at) > 0)
509
- }
510
-
511
- function normalizePendingApproval(raw) {
512
- if (!raw || typeof raw !== 'object') return null
513
- const opLabel = clamp(raw.operationLabel || raw.operation || '', 80)
514
- if (!opLabel) return null
515
- const validStatuses = ['pending', 'approved', 'rejected', 'executed', 'failed', 'expired']
516
- const status = validStatuses.includes(raw.status) ? raw.status : 'pending'
517
- const validKinds = ['tool', 'relay', 'compact', 'auto_continue', 'archive_op', 'model_effort']
518
- const kind = validKinds.includes(raw.kind) ? raw.kind : 'tool'
519
- const validCategories = ['workspace_file', 'system_command', 'main_workflow', 'subagent_workflow']
520
- const category = validCategories.includes(raw.category) ? raw.category : 'workspace_file'
521
- const payload = raw.payload && typeof raw.payload === 'object' ? raw.payload : {}
522
- const payloadHash = typeof raw.payloadHash === 'string' && raw.payloadHash.trim()
523
- ? raw.payloadHash.trim()
524
- : computeApprovalPayloadHash(kind, payload)
525
- const taskId = clamp(raw.taskId || raw.resumeTaskId || '', 80)
526
- const capabilityScope = raw.capabilityScope && typeof raw.capabilityScope === 'object'
527
- ? raw.capabilityScope
528
- : buildCapabilityScope({
529
- kind,
530
- tool: payload.tool || kind,
531
- args: payload.args || {},
532
- cwd: payload.cwd || '',
533
- target: payload.target || '',
534
- })
535
- return {
536
- id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('apr'),
537
- status,
538
- category,
539
- operationLabel: opLabel,
540
- targetLabel: clamp(raw.targetLabel || raw.target || '', 120),
541
- reason: clamp(raw.reason || '', 240),
542
- impact: clamp(raw.impact || '', 220),
543
- preview: cleanMultiline(raw.preview || '', 420),
544
- kind,
545
- payload,
546
- payloadHash,
547
- capabilityScope,
548
- taskId,
549
- resumeTaskId: taskId,
550
- expiresAt: Math.max(0, Number(raw.expiresAt) || 0),
551
- dedupeKey: clamp(raw.dedupeKey || '', 120),
552
- by: clamp(raw.by || 'chief', 40),
553
- createdAt: Number(raw.createdAt) || Date.now(),
554
- resolvedAt: Number(raw.resolvedAt) || 0,
555
- resolvedBy: clamp(raw.resolvedBy || '', 40),
556
- resultMessage: clamp(raw.resultMessage || '', 260),
557
- }
558
- }
559
-
560
- function normalizePendingElevation(raw) {
561
- if (!raw || typeof raw !== 'object') return null
562
- if (raw.status && raw.status !== 'pending') return null
563
- const targetMode = normalizePermissionMode(raw.targetMode)
564
- if (targetMode === 'advisor') return null
565
- const createdAt = Number(raw.createdAt) || Date.now()
566
- const taskId = clamp(raw.taskId || raw.resumeTaskId || '', 80)
567
- return {
568
- id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('elv'),
569
- status: 'pending',
570
- fromMode: normalizePermissionMode(raw.fromMode || 'advisor'),
571
- targetMode,
572
- reason: clamp(raw.reason || '当前任务需要更高参谋权限才能继续执行', 260),
573
- requestedActionSummary: clamp(raw.requestedActionSummary || '', 220),
574
- requestedCapabilities: Array.isArray(raw.requestedCapabilities)
575
- ? raw.requestedCapabilities.map(c => clamp(c, 60)).filter(Boolean).slice(0, 12)
576
- : [],
577
- taskId,
578
- resumeTaskId: taskId,
579
- expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
580
- by: clamp(raw.by || 'chief', 40),
581
- createdAt,
582
- }
583
- }
584
-
585
- const VALID_TASK_LEDGER_STATUSES = [
586
- 'proposed',
587
- 'awaiting_elevation',
588
- 'awaiting_approval',
589
- 'awaiting_inquiry',
590
- 'dispatched',
591
- 'running',
592
- 'resuming',
593
- 'verifying',
594
- 'completed',
595
- 'interrupted',
596
- 'rejected',
597
- 'cancelled',
598
- 'expired',
599
- 'failed',
600
- ]
601
-
602
- function normalizeTaskLedgerEntry(raw) {
603
- if (!raw || typeof raw !== 'object') return null
604
- const spec = raw.resumeSpec && typeof raw.resumeSpec === 'object' ? raw.resumeSpec : {}
605
- const originalText = cleanMultiline(spec.originalText || raw.originalText || '', 2000)
606
- if (!originalText) return null
607
- const status = VALID_TASK_LEDGER_STATUSES.includes(raw.status) ? raw.status : 'awaiting_approval'
608
- const createdAt = Number(raw.createdAt) || Date.now()
609
- const updatedAt = Number(raw.updatedAt) || createdAt
610
- const taskId = typeof (raw.taskId || raw.id) === 'string' && (raw.taskId || raw.id)
611
- ? String(raw.taskId || raw.id)
612
- : nextId('rtask')
613
- const validKinds = ['approval_resume', 'elevation_resume', 'tool_execution', 'inquiry', 'auto_continue']
614
- const kind = validKinds.includes(raw.kind)
615
- ? raw.kind
616
- : (raw.elevationId || status === 'awaiting_elevation' ? 'elevation_resume' : 'approval_resume')
617
- const forcedTarget = clamp(spec.forcedTarget !== undefined ? spec.forcedTarget : (raw.forcedTarget || ''), 64)
618
- const forcedModeRaw = spec.forcedMode !== undefined ? spec.forcedMode : raw.forcedMode
619
- const forcedMode = ['steer', 'followup', 'silent'].includes(forcedModeRaw) ? forcedModeRaw : 'steer'
620
- const rawImages = Array.isArray(spec.savedImagePaths) ? spec.savedImagePaths : raw.savedImagePaths
621
- const savedImagePaths = Array.isArray(rawImages)
622
- ? rawImages.slice(0, 4).filter(p => p && typeof p.path === 'string').map(p => ({
623
- index: Number(p.index) || 1,
624
- path: String(p.path),
625
- name: clamp(p.name || '', 80),
626
- mediaType: clamp(p.mediaType || '', 40),
627
- bytes: Math.max(0, Number(p.bytes) || 0),
628
- }))
629
- : []
630
- const rawCompleted = Array.isArray(spec.completedActions) ? spec.completedActions : raw.completedActions
631
- const completedActions = Array.isArray(rawCompleted)
632
- ? rawCompleted.map(x => clamp(x, 220)).filter(Boolean).slice(-12)
633
- : []
634
- const retryCount = Math.max(0, Math.min(4, Math.round(Number(raw.retryCount !== undefined ? raw.retryCount : raw.resumeDepth) || 0)))
635
- const capabilityScope = raw.capabilityScope && typeof raw.capabilityScope === 'object' ? raw.capabilityScope : null
636
- const payloadHash = typeof raw.payloadHash === 'string' ? raw.payloadHash.trim() : ''
637
- return {
638
- id: taskId,
639
- taskId,
640
- kind,
641
- status,
642
- capabilityScope,
643
- payloadHash,
644
- resumeSpec: {
645
- originalText,
646
- forcedTarget,
647
- forcedMode,
648
- savedImagePaths,
649
- completedActions,
650
- },
651
- originalText,
652
- forcedTarget,
653
- forcedMode,
654
- savedImagePaths,
655
- completedActions,
656
- pendingApprovalIds: Array.isArray(raw.pendingApprovalIds)
657
- ? [...new Set(raw.pendingApprovalIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 12)
658
- : [],
659
- elevationId: clamp(raw.elevationId || '', 80),
660
- inquiryId: clamp(raw.inquiryId || '', 80),
661
- lastReceipt: cleanMultiline(raw.lastReceipt || '', 300),
662
- retryCount,
663
- resumeDepth: retryCount,
664
- createdAt,
665
- updatedAt,
666
- expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
667
- resolvedAt: Math.max(0, Number(raw.resolvedAt) || 0),
668
- }
669
- }
670
-
671
- export function recoverTaskLedgerEntriesOnDiskLoad(entries, now = Date.now()) {
672
- if (!Array.isArray(entries)) return []
673
- return entries.map((entry) => {
674
- if (!entry || typeof entry !== 'object') return entry
675
- const tid = entry.taskId || entry.id
676
- if (
677
- (entry.status === 'running' || entry.status === 'resuming' || entry.status === 'verifying')
678
- && !activeResumingTaskIds.has(tid)
679
- ) {
680
- return {
681
- ...entry,
682
- status: 'interrupted',
683
- updatedAt: now,
684
- lastReceipt: entry.lastReceipt || '检测到上次运行中断,已安全降级为 interrupted 等待人工确认续跑',
685
- }
686
- }
687
- if (
688
- (entry.status === 'proposed' || entry.status === 'awaiting_approval' || entry.status === 'awaiting_elevation' || entry.status === 'awaiting_inquiry')
689
- && entry.expiresAt > 0
690
- && now > entry.expiresAt
691
- ) {
692
- return {
693
- ...entry,
694
- status: 'expired',
695
- updatedAt: now,
696
- resolvedAt: entry.resolvedAt || now,
697
- }
698
- }
699
- return entry
700
- })
701
- }
702
-
703
- function normalizeAuditEntry(raw) {
704
- return normalizeAuditRecord(raw, DEFAULT_CHIEF_PERMISSION_MODE)
705
- }
706
-
707
- export function pushAuditToWs(ws, entry = {}, sessionId = '') {
708
- if (!ws || typeof ws !== 'object') return null
709
- if (!Array.isArray(ws.auditLog)) ws.auditLog = []
710
- const norm = normalizeAuditEntry(entry)
711
- if (!norm) return null
712
- ws.auditLog.push(norm)
713
- if (ws.auditLog.length > AUDIT_LOG_CAP) ws.auditLog = ws.auditLog.slice(-AUDIT_LOG_CAP)
714
- appendAuditJsonlRecord(norm, sessionId)
715
- return norm
716
- }
717
-
718
- function emptyWorkspace() {
719
- const sharedLedger = []
720
- return {
721
- config: null,
722
- chiefRiskAck: null,
723
- pendingApprovals: [],
724
- pendingElevation: null,
725
- taskLedger: sharedLedger,
726
- resumeTasks: sharedLedger,
727
- auditLog: [],
728
- facts: [],
729
- narrative: { hash: '', text: '', at: 0, byModel: '', clusterSig: '' },
730
- suggestions: [],
731
- inquiries: [],
732
- chat: [],
733
- mailbox: [],
734
- seenMailAt: {},
735
- seenFactsAt: {},
736
- reviewCursors: {},
737
- runtimeGuard: {
738
- lastCompactedSeq: 0,
739
- lastCompactedAt: 0,
740
- interventionTurns: 0,
741
- lastDigestHash: '',
742
- unchangedCount: 0,
743
- cooldownUntil: 0,
744
- circuitBroken: false,
745
- circuitReason: '',
746
- hazardAlert: null,
747
- lastGoalAchievedSig: '',
748
- autoPilotStartedAt: 0,
749
- autoPilotHadTurn: false,
750
- managedStartedAt: 0,
751
- lastActivityAt: 0,
752
- lastDreamRoamAt: 0,
753
- lastAutoArchiveOrgAt: 0,
754
- },
755
- flippedPrecipitatedIds: [],
756
- }
757
- }
758
-
759
- export function normalizeFact(raw) {
760
- if (!raw || typeof raw !== 'object') return null
761
- const text = clamp(raw.text, FACT_TEXT_MAX)
762
- if (!text || secretLike(text)) return null
763
- const validCategories = ['discipline', 'architecture', 'progress', 'preference', 'team']
764
- const category = validCategories.includes(raw.category) ? raw.category : 'discipline'
765
- const peerRootIds = Array.isArray(raw.peerRootIds)
766
- ? [...new Set(raw.peerRootIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 16)
767
- : []
768
- return {
769
- id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('fact'),
770
- text,
771
- category,
772
- by: clamp(raw.by || 'chief', 36),
773
- source: clamp(raw.source || '', 60),
774
- originRootId: typeof raw.originRootId === 'string' ? raw.originRootId.trim() : '',
775
- ...(peerRootIds.length ? { peerRootIds } : {}),
776
- pinned: Boolean(raw.pinned),
777
- addedAt: Number(raw.addedAt) || Date.now(),
778
- updatedAt: Number(raw.updatedAt) || Number(raw.addedAt) || Date.now(),
779
- }
780
- }
781
-
782
- export function normalizeSuggestion(raw) {
783
- if (!raw || typeof raw !== 'object') return null
784
- const title = clamp(raw.title, 90)
785
- if (!title) return null
786
- const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice', 'guard_wall', 'wall_removal', 'archive_op', 'model_effort'].includes(raw.kind) ? raw.kind : 'relay'
787
- const boundField = ['forbidden', 'allowed', 'notes'].includes(raw.boundField) ? raw.boundField : 'forbidden'
788
- const replaces = Array.isArray(raw.replaces)
789
- ? raw.replaces.map(x => String(x || '').trim()).filter(Boolean).slice(0, 20)
790
- : []
791
- const wallSpec = raw.wallSpec && typeof raw.wallSpec === 'object' ? { ...raw.wallSpec } : null
792
- const wallRemovalSpec = raw.wallRemovalSpec && typeof raw.wallRemovalSpec === 'object' ? { ...raw.wallRemovalSpec } : null
793
- const archiveSpec = (raw.archiveSpec && typeof raw.archiveSpec === 'object')
794
- ? { ...raw.archiveSpec }
795
- : ((raw.archiveOp && typeof raw.archiveOp === 'object') ? { ...raw.archiveOp } : null)
796
- const effortSpec = (raw.effortSpec && typeof raw.effortSpec === 'object')
797
- ? { ...raw.effortSpec }
798
- : ((raw.effortOp && typeof raw.effortOp === 'object') ? { ...raw.effortOp } : null)
799
- return {
800
- id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('sug'),
801
- kind,
802
- boundField,
803
- replaces,
804
- pinGlobal: Boolean(raw.pinGlobal),
805
- ...(wallSpec ? { wallSpec } : {}),
806
- ...(wallRemovalSpec ? { wallRemovalSpec } : {}),
807
- ...(archiveSpec ? { archiveSpec } : {}),
808
- ...(effortSpec ? { effortSpec } : {}),
809
- fromAgent: clamp(raw.fromAgent || '', 48),
810
- title,
811
- reason: clamp(raw.reason || '', 220),
812
- target: clamp(raw.target || (kind === 'bound' ? 'bounds' : (kind === 'guard_wall' || kind === 'wall_removal') ? 'guard_walls' : kind === 'goal_approval' ? 'board' : kind === 'archive_op' ? 'archive' : kind === 'model_effort' ? 'lead' : 'lead'), 64),
813
- targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : kind === 'guard_wall' ? '物理驻墙' : kind === 'wall_removal' ? '物理驻墙拆墙申请' : kind === 'goal_approval' ? '目标结项批示' : kind === 'advice' ? '参谋进言' : kind === 'archive_op' ? '档案与桌面调配' : kind === 'model_effort' ? '模型思考强度调节' : '主对话'), 40),
814
- mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : (kind === 'advice' ? 'followup' : 'steer'),
815
- draftText: cleanMultiline(raw.draftText || '', 600),
816
- evidence: cleanMultiline(raw.evidence || '', 600),
817
- missing: clamp(raw.missing || '', 300),
818
- boardOp: raw.boardOp && typeof raw.boardOp === 'object' ? raw.boardOp : null,
819
- popup: Boolean(raw.popup || kind === 'advice' || kind === 'wall_removal'),
820
- urgency: ['normal', 'high'].includes(raw.urgency) ? raw.urgency : (kind === 'wall_removal' ? 'high' : 'normal'),
821
- status: ['pending', 'applied', 'dismissed'].includes(raw.status) ? raw.status : 'pending',
822
- createdAt: Number(raw.createdAt) || Date.now(),
823
- }
824
- }
825
-
826
- export function normalizeInquiryItem(raw) {
827
- if (!raw || typeof raw !== 'object') return null
828
- const question = cleanMultiline(raw.question || raw.text || '', 600)
829
- if (!question) return null
830
- const status = ['pending', 'delivered', 'answered', 'expired'].includes(raw.status) ? raw.status : 'pending'
831
- const inquiryId = typeof (raw.inquiryId || raw.id) === 'string' && (raw.inquiryId || raw.id)
832
- ? String(raw.inquiryId || raw.id)
833
- : nextId('inq')
834
- return {
835
- id: inquiryId,
836
- inquiryId,
837
- taskId: clamp(raw.taskId || '', 80),
838
- target: clamp(raw.target || 'lead', 64),
839
- question,
840
- context: clamp(raw.context || '', 220),
841
- answer: cleanMultiline(raw.answer || '', 1200),
842
- status,
843
- by: clamp(raw.by || 'chief', 40),
844
- answeredBy: clamp(raw.answeredBy || '', 40),
845
- createdAt: Number(raw.createdAt) || Date.now(),
846
- deliveredAt: Number(raw.deliveredAt) || 0,
847
- answeredAt: Number(raw.answeredAt) || 0,
848
- expiresAt: Number(raw.expiresAt) || ((Number(raw.createdAt) || Date.now()) + DEFAULT_RESUME_TTL_MS),
849
- }
850
- }
851
-
852
- export function normalizeMail(raw) {
853
- if (!raw || typeof raw !== 'object') return null
854
- const imageCount = Math.max(0, Math.round(Number(raw.imageCount) || 0))
855
- const text = cleanMultiline(raw.text, 1500) || (imageCount > 0 ? `[附图 ×${imageCount}]` : '')
856
- if (!text) return null
857
- const participantRoots = Array.isArray(raw.participantRoots)
858
- ? [...new Set(raw.participantRoots.map(x => String(x || '').trim()).filter(Boolean))].sort().slice(0, 24)
859
- : []
860
- const validChannels = ['internal', 'pair', 'multi', 'broadcast']
861
- const channelType = validChannels.includes(raw.channelType) ? raw.channelType : ''
862
- return {
863
- id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('mail'),
864
- from: clamp(raw.from || 'agent', 48),
865
- fromSession: String(raw.fromSession || ''),
866
- fromRootId: String(raw.fromRootId || ''),
867
- to: clamp(raw.to || 'lead', 64),
868
- toSession: String(raw.toSession || ''),
869
- toRootId: String(raw.toRootId || ''),
870
- ...(participantRoots.length ? { participantRoots } : {}),
871
- ...(channelType ? { channelType } : {}),
872
- ...(raw.broadcastId ? { broadcastId: String(raw.broadcastId) } : {}),
873
- subject: clamp(raw.subject || '', 80),
874
- text,
875
- ...(imageCount > 0 ? { imageCount } : {}),
876
- mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : 'steer',
877
- deliveredPhysical: Boolean(raw.deliveredPhysical),
878
- readBy: Array.isArray(raw.readBy) ? raw.readBy.map(String).slice(0, 32) : [],
879
- at: Number(raw.at) || Date.now(),
880
- }
881
- }
882
-
883
- function normalizeWorkspace(raw) {
884
- const src = raw && typeof raw === 'object' ? raw : {}
885
- const base = emptyWorkspace()
886
- base.facts = (Array.isArray(src.facts) ? src.facts : []).map(normalizeFact).filter(Boolean).slice(-FACTS_CAP)
887
- if (src.narrative && typeof src.narrative === 'object') {
888
- base.narrative = {
889
- hash: String(src.narrative.hash || ''),
890
- text: String(src.narrative.text || ''),
891
- at: Number(src.narrative.at) || 0,
892
- byModel: String(src.narrative.byModel || ''),
893
- clusterSig: String(src.narrative.clusterSig || ''),
894
- }
895
- }
896
- base.suggestions = (Array.isArray(src.suggestions) ? src.suggestions : [])
897
- .map(normalizeSuggestion)
898
- .filter(Boolean)
899
- .slice(-SUGGESTIONS_CAP * 2)
900
- base.inquiries = (Array.isArray(src.inquiries) ? src.inquiries : [])
901
- .map(normalizeInquiryItem)
902
- .filter(Boolean)
903
- .slice(-24)
904
- base.chat = (Array.isArray(src.chat) ? src.chat : [])
905
- .filter(item => item && typeof item === 'object' && typeof item.text === 'string')
906
- .slice(-CHAT_CAP)
907
- .map(item => {
908
- const imageCount = Math.max(0, Math.round(Number(item.imageCount) || 0))
909
- const kind = item.kind === 'receipt' ? 'receipt' : (item.kind === 'qa' ? 'qa' : '')
910
- const resumeTaskId = item.resumeTaskId ? String(item.resumeTaskId) : ''
911
- const thinkingEffort = typeof item.thinkingEffort === 'string' && item.thinkingEffort ? item.thinkingEffort : ''
912
- const thinkingEffortMode = item.thinkingEffortMode === 'auto' || item.thinkingEffortMode === 'manual' ? item.thinkingEffortMode : ''
913
- return {
914
- id: String(item.id || nextId('chat')),
915
- role: item.role === 'user' ? 'user' : 'chief',
916
- text: cleanMultiline(item.text, 2000),
917
- target: item.target ? String(item.target) : '',
918
- ...(kind ? { kind } : {}),
919
- ...(resumeTaskId ? { resumeTaskId } : {}),
920
- ...(thinkingEffort ? { thinkingEffort } : {}),
921
- ...(thinkingEffortMode ? { thinkingEffortMode } : {}),
922
- ...(item.isOneStopReport ? { isOneStopReport: true } : {}),
923
- ...(imageCount > 0 ? { imageCount } : {}),
924
- actions: Array.isArray(item.actions) ? item.actions.slice(0, 8) : [],
925
- at: Number(item.at) || Date.now(),
926
- }
927
- })
928
- base.mailbox = (Array.isArray(src.mailbox) ? src.mailbox : []).map(normalizeMail).filter(Boolean).slice(-MAIL_CAP)
929
- base.seenMailAt = src.seenMailAt && typeof src.seenMailAt === 'object' ? { ...src.seenMailAt } : {}
930
- base.seenFactsAt = src.seenFactsAt && typeof src.seenFactsAt === 'object' ? { ...src.seenFactsAt } : {}
931
- base.reviewCursors = src.reviewCursors && typeof src.reviewCursors === 'object' ? { ...src.reviewCursors } : {}
932
- const rg = src.runtimeGuard && typeof src.runtimeGuard === 'object' ? src.runtimeGuard : {}
933
- base.runtimeGuard = {
934
- lastCompactedSeq: Math.max(0, Math.round(Number(rg.lastCompactedSeq) || 0)),
935
- lastCompactedAt: Math.max(0, Number(rg.lastCompactedAt) || 0),
936
- autoCompactCount: Math.max(0, Math.round(Number(rg.autoCompactCount) || 0)),
937
- pendingSmartCompact: rg.pendingSmartCompact && typeof rg.pendingSmartCompact === 'object'
938
- ? {
939
- at: Number(rg.pendingSmartCompact.at) || Date.now(),
940
- reason: clamp(rg.pendingSmartCompact.reason || '', 240),
941
- by: clamp(rg.pendingSmartCompact.by || 'lead', 40),
942
- }
943
- : null,
944
- interventionTurns: Math.max(0, Math.round(Number(rg.interventionTurns) || 0)),
945
- lastDigestHash: String(rg.lastDigestHash || ''),
946
- unchangedCount: Math.max(0, Math.round(Number(rg.unchangedCount) || 0)),
947
- cooldownUntil: Math.max(0, Number(rg.cooldownUntil) || 0),
948
- circuitBroken: Boolean(rg.circuitBroken),
949
- circuitReason: String(rg.circuitReason || ''),
950
- hazardAlert: rg.hazardAlert && typeof rg.hazardAlert === 'object' && (rg.hazardAlert.reason || rg.hazardAlert.title)
951
- ? {
952
- id: String(rg.hazardAlert.id || ''),
953
- category: clamp(rg.hazardAlert.category || 'irreversible_risk', 40),
954
- title: clamp(rg.hazardAlert.title || '强介入安全煞停', 120),
955
- reason: cleanMultiline(rg.hazardAlert.reason || '', 600),
956
- objective: clamp(rg.hazardAlert.objective || '', 300),
957
- at: Math.max(0, Number(rg.hazardAlert.at) || 0),
958
- }
959
- : null,
960
- lastGoalAchievedSig: String(rg.lastGoalAchievedSig || ''),
961
- autoPilotStartedAt: Math.max(0, Number(rg.autoPilotStartedAt) || 0),
962
- autoPilotHadTurn: Boolean(rg.autoPilotHadTurn),
963
- managedStartedAt: Math.max(0, Number(rg.managedStartedAt) || Number(rg.autoPilotStartedAt) || 0),
964
- lastActivityAt: Math.max(0, Number(rg.lastActivityAt) || 0),
965
- lastDreamRoamAt: Math.max(0, Number(rg.lastDreamRoamAt) || 0),
966
- lastAutoArchiveOrgAt: Math.max(0, Number(rg.lastAutoArchiveOrgAt) || 0),
967
- }
968
- base.chiefRiskAck = normalizeChiefRiskAck(src.chiefRiskAck)
969
- base.pendingApprovals = (Array.isArray(src.pendingApprovals) ? src.pendingApprovals : [])
970
- .map(normalizePendingApproval)
971
- .filter(Boolean)
972
- .slice(-APPROVALS_CAP)
973
- base.pendingElevation = normalizePendingElevation(src.pendingElevation)
974
- const rawLedgerSrc = Array.isArray(src.taskLedger) && src.taskLedger.length > 0
975
- ? src.taskLedger
976
- : (Array.isArray(src.resumeTasks) ? src.resumeTasks : [])
977
- const normalizedLedger = rawLedgerSrc
978
- .map(normalizeTaskLedgerEntry)
979
- .filter(Boolean)
980
- .slice(-TASK_LEDGER_CAP)
981
- base.taskLedger = normalizedLedger
982
- base.resumeTasks = normalizedLedger
983
- base.auditLog = (Array.isArray(src.auditLog) ? src.auditLog : [])
984
- .map(normalizeAuditEntry)
985
- .filter(Boolean)
986
- .slice(-AUDIT_LOG_CAP)
987
- const ackOk = hasValidChiefRiskAck(base)
988
- if (src.config && typeof src.config === 'object') {
989
- const validPaces = ['manual', 'smart', 'auto', 'stopped']
990
- const pm = validPaces.includes(src.config.paceMode) ? src.config.paceMode : undefined
991
- const rawStopped = typeof src.config.stopped === 'boolean' ? src.config.stopped : (pm === 'stopped')
992
- const rm = normalizeRunMode(src.config.runMode, { ...src.config, stopped: rawStopped, paceMode: pm })
993
- const rawPerm = typeof src.config.permissionMode === 'string'
994
- ? normalizePermissionMode(src.config.permissionMode, { requireAck: true, hasChiefRiskAck: ackOk })
995
- : DEFAULT_CHIEF_PERMISSION_MODE
996
- const plugCheck = validatePolicyPluginList(src.config.policyPlugins)
997
- const policyPlugins = plugCheck.ok ? plugCheck.plugins : []
998
- const lockedModelEfforts = normalizeLockedModelEfforts(src.config.lockedModelEfforts)
999
- const managedIdleTimeoutMs = Number.isFinite(Number(src.config.managedIdleTimeoutMs)) && Number(src.config.managedIdleTimeoutMs) >= 50
1000
- ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(src.config.managedIdleTimeoutMs)))
1001
- : DEFAULT_MANAGED_IDLE_TIMEOUT_MS
1002
- base.config = {
1003
- ...(typeof src.config.modelRef === 'string' ? { modelRef: src.config.modelRef.trim() } : {}),
1004
- permissionMode: rawPerm,
1005
- runMode: rm,
1006
- managedIdleTimeoutMs,
1007
- ...(typeof src.config.thinkingEffort === 'string' ? { thinkingEffort: normalizeThinkingEffort(src.config.thinkingEffort) } : {}),
1008
- ...(typeof src.config.teamEffortMode === 'string' ? { teamEffortMode: normalizeTeamEffortMode(src.config.teamEffortMode) } : {}),
1009
- ...(Object.keys(lockedModelEfforts).length ? { lockedModelEfforts } : {}),
1010
- ...(typeof src.config.stopped === 'boolean' || pm === 'stopped' ? { stopped: rawStopped } : {}),
1011
- ...(pm ? { paceMode: pm, autoPilot: !rawStopped && pm === 'auto', autoReview: !rawStopped && pm !== 'manual' } : {}),
1012
- ...(policyPlugins.length > 0 ? { policyPlugins } : {}),
1013
- ...(src.config.tacticalModes && typeof src.config.tacticalModes === 'object'
1014
- ? { tacticalModes: normalizeTacticalModes(src.config.tacticalModes) }
1015
- : {}),
1016
- }
1017
- }
1018
- base.flippedPrecipitatedIds = Array.isArray(src.flippedPrecipitatedIds)
1019
- ? [...new Set(src.flippedPrecipitatedIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 20)
1020
- : []
1021
- return base
1022
- }
1023
-
1024
- export const COMPACT_THRESHOLD_MIN_PCT = 10
1025
-
1026
- export const COMPACT_THRESHOLD_MAX_PCT = 95
1027
-
1028
- export const COMPACT_PCT_WARN_FLOOR = 25
1029
-
1030
- export const COMPACT_TOKEN_HARD_MIN = 8_000
1031
-
1032
- export const COMPACT_TOKEN_WARN_FLOOR = 32_000
1033
-
1034
- /** Format a token threshold cleanly into compact K/M display notation (e.g. `64K`, `1M`). */
1035
- export function formatCompactTokenShort(tokens) {
1036
- const n = Math.max(0, Math.round(Number(tokens) || 0))
1037
- if (n >= 1_000_000 && n % 100_000 === 0) {
1038
- const m = n / 1_000_000
1039
- return (Number.isInteger(m) ? String(m) : m.toFixed(1).replace(/\.0$/, '')) + 'M'
1040
- }
1041
- if (n >= 1_000) {
1042
- const k = n / 1_000
1043
- return (k >= 100 ? String(Math.round(k)) : k.toFixed(1).replace(/\.0$/, '')) + 'K'
1044
- }
1045
- return String(n)
1046
- }
1047
-
1048
- /**
1049
- * Parse custom context size threshold input (`'1M'` -> 1,000,000; `'64K'` -> 64,000; bare `'64'` -> `64K`).
1050
- * Bare numbers without a unit default to K, and values below `32K` attach a low-threshold warning.
1051
- */
1052
- export function parseCompactTokensInput(rawInput) {
1053
- const s = String(rawInput ?? '').trim()
1054
- if (!s) return { ok: false, error: '请输入上下文阈值,例如 64K、1M 或纯数字(无单位默认为 K)' }
1055
- const m = s.match(/^(\d+(?:\.\d+)?)\s*(k|m|t|tokens?)?$/i)
1056
- if (!m) return { ok: false, error: '格式无效:支持如 64K、1M 或纯数字(无单位默认为 K)' }
1057
- const num = Number(m[1])
1058
- if (!Number.isFinite(num) || num <= 0) return { ok: false, error: '上下文阈值必须大于 0' }
1059
- const unit = (m[2] || 'k').toLowerCase()
1060
- let rawTokens = 0
1061
- if (unit === 'm') rawTokens = Math.round(num * 1_000_000)
1062
- else if (unit === 'k') rawTokens = Math.round(num * 1_000)
1063
- else rawTokens = Math.round(num)
1064
- const tokens = Math.max(COMPACT_TOKEN_HARD_MIN, rawTokens)
1065
- const displayInput = formatCompactTokenShort(tokens)
1066
- const lowWarning = tokens < COMPACT_TOKEN_WARN_FLOOR
1067
- ? `当前阈值(${displayInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
1068
- : ''
1069
- return {
1070
- ok: true,
1071
- tokens,
1072
- rawTokens,
1073
- clampedToMin: rawTokens < COMPACT_TOKEN_HARD_MIN,
1074
- displayInput,
1075
- lowWarning,
1076
- }
1077
- }
1078
-
1079
- /** Resolve effective Chief config for a specific root session (isolates `intervention` and `permissionMode` per session). */
1080
- export function resolveWorkspaceConfig(state, sessionId = '') {
1081
- const safeState = state && typeof state === 'object' ? state : {}
1082
- const base = safeState.config && typeof safeState.config === 'object' ? safeState.config : {}
1083
- const baseTactical = normalizeTacticalModes(base.tacticalModes)
1084
- const sid = String(sessionId || '').trim()
1085
- const ws = sid && safeState.workspaces && safeState.workspaces[sid] ? safeState.workspaces[sid] : null
1086
- const wsCfg = ws && ws.config && typeof ws.config === 'object' ? ws.config : null
1087
- const validPaces = ['manual', 'smart', 'auto', 'stopped']
1088
- const basePaceSafe = validPaces.includes(base.paceMode) && !(sid && base.paceMode === 'auto')
1089
- ? base.paceMode
1090
- : 'manual'
1091
- const rawPaceMode = wsCfg && validPaces.includes(wsCfg.paceMode)
1092
- ? wsCfg.paceMode
1093
- : basePaceSafe
1094
- const explicitStopped = wsCfg && typeof wsCfg.stopped === 'boolean'
1095
- ? wsCfg.stopped
1096
- : (typeof base.stopped === 'boolean' ? base.stopped : false)
1097
- const stopped = rawPaceMode === 'stopped' || explicitStopped
1098
- const paceMode = stopped ? 'stopped' : rawPaceMode
1099
- const modelRef = wsCfg && typeof wsCfg.modelRef === 'string'
1100
- ? wsCfg.modelRef.trim()
1101
- : (typeof base.modelRef === 'string' ? base.modelRef.trim() : '')
1102
- const mergedTactical = wsCfg && wsCfg.tacticalModes
1103
- ? normalizeTacticalModes({ ...baseTactical, ...wsCfg.tacticalModes })
1104
- : { ...baseTactical, ...(sid ? { intervention: false } : {}) }
1105
- const ackOk = hasValidChiefRiskAck(ws)
1106
- const rawPerm = (wsCfg && typeof wsCfg.permissionMode === 'string')
1107
- ? wsCfg.permissionMode
1108
- : DEFAULT_CHIEF_PERMISSION_MODE
1109
- const globalPlugCheck = validatePolicyPluginList(base.policyPlugins)
1110
- const wsPlugCheck = validatePolicyPluginList(wsCfg && wsCfg.policyPlugins)
1111
- const policyPlugins = [
1112
- ...(globalPlugCheck.ok ? globalPlugCheck.plugins : []),
1113
- ...(wsPlugCheck.ok ? wsPlugCheck.plugins : []),
1114
- ]
1115
- const resolvedRoleCaps = resolveRoleCapabilities(rawPerm, {
1116
- hasChiefRiskAck: ackOk,
1117
- policyPlugins,
1118
- })
1119
- const permissionMode = resolvedRoleCaps.role
1120
- const chiefRiskVerified = permissionMode === 'chief' ? ackOk : false
1121
- const runMode = stopped
1122
- ? 'off'
1123
- : (wsCfg && typeof wsCfg.runMode === 'string' && CHIEF_RUN_MODES.includes(wsCfg.runMode)
1124
- ? wsCfg.runMode
1125
- : normalizeRunMode(undefined, { stopped, paceMode, autoPilot: paceMode === 'auto' }))
1126
- const thinkingEffort = normalizeThinkingEffort(
1127
- (wsCfg && typeof wsCfg.thinkingEffort === 'string' && wsCfg.thinkingEffort)
1128
- || (typeof base.thinkingEffort === 'string' && base.thinkingEffort)
1129
- || 'auto',
1130
- )
1131
- const teamEffortMode = normalizeTeamEffortMode(
1132
- (wsCfg && typeof wsCfg.teamEffortMode === 'string' && wsCfg.teamEffortMode)
1133
- || (typeof base.teamEffortMode === 'string' && base.teamEffortMode)
1134
- || 'auto',
1135
- )
1136
- const lockedModelEfforts = normalizeLockedModelEfforts(wsCfg && wsCfg.lockedModelEfforts)
1137
- const managedIdleTimeoutMs = wsCfg && Number.isFinite(Number(wsCfg.managedIdleTimeoutMs)) && Number(wsCfg.managedIdleTimeoutMs) >= 50
1138
- ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(wsCfg.managedIdleTimeoutMs)))
1139
- : (Number.isFinite(Number(base.managedIdleTimeoutMs)) && Number(base.managedIdleTimeoutMs) >= 50
1140
- ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(base.managedIdleTimeoutMs)))
1141
- : DEFAULT_MANAGED_IDLE_TIMEOUT_MS)
1142
- return {
1143
- modelRef,
1144
- paceMode,
1145
- runMode,
1146
- managedIdleTimeoutMs,
1147
- thinkingEffort,
1148
- teamEffortMode,
1149
- lockedModelEfforts,
1150
- stopped,
1151
- permissionMode,
1152
- capabilities: resolvedRoleCaps.capabilities,
1153
- policyPlugins,
1154
- chiefRiskVerified,
1155
- autoPilot: !stopped && runMode === 'managed',
1156
- autoReview: !stopped && runMode === 'managed',
1157
- tacticalModes: mergedTactical,
1158
- }
1159
- }
1160
-
1161
- const DEFAULT_TACTICAL_MODES = {
1162
- intervention: false,
1163
- autoCompact: false,
1164
- smartCompact: false,
1165
- compactThresholdMode: 'pct',
1166
- compactThresholdPct: 80,
1167
- compactThresholdTokens: 64_000,
1168
- compactThresholdInput: '64K',
1169
- strictVerify: false,
1170
- redlineSentinel: false,
1171
- conciseBrief: false,
1172
- maxInterventionTurns: 10,
1173
- }
1174
-
1175
- export function normalizeTacticalModes(raw) {
1176
- const src = raw && typeof raw === 'object' ? raw : {}
1177
- const pct = Math.round(Number(src.compactThresholdPct) || DEFAULT_TACTICAL_MODES.compactThresholdPct)
1178
- const mode = src.compactThresholdMode === 'tokens' ? 'tokens' : 'pct'
1179
- const rawTokens = Math.round(Number(src.compactThresholdTokens) || DEFAULT_TACTICAL_MODES.compactThresholdTokens)
1180
- const compactThresholdTokens = Math.max(COMPACT_TOKEN_HARD_MIN, rawTokens)
1181
- const compactThresholdInput = typeof src.compactThresholdInput === 'string' && src.compactThresholdInput.trim()
1182
- ? src.compactThresholdInput.trim()
1183
- : formatCompactTokenShort(compactThresholdTokens)
1184
- const rawTurns = src.maxInterventionTurns
1185
- const isZeroTurns = rawTurns === 0 || rawTurns === '0'
1186
- const parsedTurns = isZeroTurns
1187
- ? 0
1188
- : Math.min(30, Math.max(1, Math.round(Number(rawTurns) || DEFAULT_TACTICAL_MODES.maxInterventionTurns)))
1189
- return {
1190
- intervention: Boolean(src.intervention),
1191
- autoCompact: Boolean(src.autoCompact),
1192
- smartCompact: Boolean(src.smartCompact),
1193
- compactThresholdMode: mode,
1194
- compactThresholdPct: Math.min(COMPACT_THRESHOLD_MAX_PCT, Math.max(COMPACT_THRESHOLD_MIN_PCT, pct)),
1195
- compactThresholdTokens,
1196
- compactThresholdInput,
1197
- strictVerify: Boolean(src.strictVerify),
1198
- redlineSentinel: Boolean(src.redlineSentinel),
1199
- conciseBrief: Boolean(src.conciseBrief),
1200
- maxInterventionTurns: parsedTurns,
1201
- }
1202
- }
1203
-
1204
- function normalizeState(raw) {
1205
- const src = raw && typeof raw === 'object' ? raw : {}
1206
- const cfg = src.config && typeof src.config === 'object' ? src.config : {}
1207
- const links = {}
1208
- if (src.links && typeof src.links === 'object') {
1209
- for (const [k, list] of Object.entries(src.links)) {
1210
- if (!k || !Array.isArray(list)) continue
1211
- const clean = [...new Set(list.map(v => String(v || '').trim()).filter(v => v && v !== k))]
1212
- if (clean.length) links[k] = clean
1213
- }
1214
- }
1215
- const workspaces = {}
1216
- if (src.workspaces && typeof src.workspaces === 'object') {
1217
- for (const [k, ws] of Object.entries(src.workspaces)) {
1218
- if (!k) continue
1219
- workspaces[k] = normalizeWorkspace(ws)
1220
- }
1221
- }
1222
- const validPaces = ['manual', 'smart', 'auto', 'stopped']
1223
- // Default to 'manual' (human-paced, zero background token burn) unless explicitly set to smart/auto
1224
- const rawPace = validPaces.includes(cfg.paceMode) ? cfg.paceMode : 'manual'
1225
- const stopped = rawPace === 'stopped' || Boolean(cfg.stopped)
1226
- const paceMode = stopped ? 'stopped' : rawPace
1227
- const globalPlugRes = validatePolicyPluginList(cfg.policyPlugins)
1228
- return {
1229
- version: STATE_VERSION,
1230
- config: {
1231
- modelRef: typeof cfg.modelRef === 'string' ? cfg.modelRef.trim() : '',
1232
- paceMode,
1233
- runMode: stopped ? 'off' : normalizeRunMode(cfg.runMode, { stopped, paceMode }),
1234
- managedIdleTimeoutMs: Number.isFinite(Number(cfg.managedIdleTimeoutMs)) && Number(cfg.managedIdleTimeoutMs) >= 50
1235
- ? Math.min(2 * 60 * 60 * 1000, Math.round(Number(cfg.managedIdleTimeoutMs)))
1236
- : DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
1237
- thinkingEffort: normalizeThinkingEffort(cfg.thinkingEffort),
1238
- teamEffortMode: normalizeTeamEffortMode(cfg.teamEffortMode),
1239
- stopped,
1240
- permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
1241
- autoPilot: !stopped && paceMode === 'auto',
1242
- autoReview: !stopped && paceMode !== 'manual',
1243
- ...(globalPlugRes.ok && globalPlugRes.plugins.length > 0 ? { policyPlugins: globalPlugRes.plugins } : {}),
1244
- tacticalModes: normalizeTacticalModes(cfg.tacticalModes),
1245
- },
1246
- links,
1247
- workspaces,
1248
- }
1249
- }
1250
-
1251
- export function appendChiefAuditLog(sessionId = 'global', entry = {}) {
1252
- const rootId = String(sessionId || 'global').trim() || 'global'
1253
- return mutateChiefState((state) => {
1254
- const ws = ensureWorkspace(state, rootId)
1255
- return pushAuditToWs(ws, entry, rootId)
1256
- })
1257
- }
1258
-
1259
- export function enqueueApprovalToWs(ws, item = {}) {
1260
- if (!ws || typeof ws !== 'object') return null
1261
- if (!Array.isArray(ws.pendingApprovals)) ws.pendingApprovals = []
1262
- const dKey = clamp(item.dedupeKey || '', 120)
1263
- if (dKey) {
1264
- const existing = ws.pendingApprovals.find(a => a && a.status === 'pending' && a.dedupeKey === dKey)
1265
- if (existing) return existing
1266
- }
1267
- const kind = item.kind || 'tool'
1268
- const payload = item.payload && typeof item.payload === 'object' ? item.payload : {}
1269
- const now = Date.now()
1270
- const norm = normalizePendingApproval({
1271
- ...item,
1272
- status: 'pending',
1273
- dedupeKey: dKey,
1274
- payloadHash: computeApprovalPayloadHash(kind, payload),
1275
- expiresAt: Number(item.expiresAt) || (now + DEFAULT_RESUME_TTL_MS),
1276
- })
1277
- if (!norm) return null
1278
- ws.pendingApprovals.push(norm)
1279
- if (ws.pendingApprovals.length > APPROVALS_CAP) {
1280
- ws.pendingApprovals = ws.pendingApprovals.slice(-APPROVALS_CAP)
1281
- }
1282
- return norm
1283
- }
1284
-
1285
- export function queueChiefApproval(sessionId = 'global', item = {}) {
1286
- const rootId = String(sessionId || 'global').trim() || 'global'
1287
- return mutateChiefState((state) => {
1288
- const ws = ensureWorkspace(state, rootId)
1289
- return enqueueApprovalToWs(ws, item)
1290
- })
1291
- }
1292
-
1293
- export function enqueueElevationToWs(ws, req = {}) {
1294
- if (!ws || typeof ws !== 'object') return null
1295
- const currentMode = normalizePermissionMode(
1296
- ws.config && ws.config.permissionMode ? ws.config.permissionMode : DEFAULT_CHIEF_PERMISSION_MODE,
1297
- { requireAck: true, hasChiefRiskAck: hasValidChiefRiskAck(ws) },
1298
- )
1299
- const targetMode = normalizePermissionMode(req.targetMode || 'strategist')
1300
- if (permissionRank(targetMode) <= permissionRank(currentMode)) return null
1301
- const now = Date.now()
1302
- const norm = normalizePendingElevation({
1303
- fromMode: currentMode,
1304
- targetMode,
1305
- reason: req.reason || 'Agent 申请提升权限以继续当前任务',
1306
- requestedActionSummary: req.requestedActionSummary || '',
1307
- resumeTaskId: req.resumeTaskId || '',
1308
- expiresAt: Number(req.expiresAt) || (now + DEFAULT_RESUME_TTL_MS),
1309
- by: req.by || 'chief',
1310
- })
1311
- if (!norm) return null
1312
- ws.pendingElevation = norm
1313
- pushAuditToWs(ws, {
1314
- mode: currentMode,
1315
- stage: 'permission_gate',
1316
- decision: 'elevation_requested',
1317
- operation: '申请提权',
1318
- target: `${CHIEF_PERMISSION_META[currentMode].level} -> ${CHIEF_PERMISSION_META[targetMode].level}`,
1319
- reason: norm.reason,
1320
- outcome: 'pending',
1321
- by: norm.by,
1322
- }, req.sessionId || '')
1323
- return norm
1324
- }
1325
-
1326
- export function requestChiefElevation(sessionId = 'global', req = {}) {
1327
- const rootId = String(sessionId || 'global').trim() || 'global'
1328
- return mutateChiefState((state) => {
1329
- const ws = ensureWorkspace(state, rootId)
1330
- return enqueueElevationToWs(ws, { ...(req && typeof req === 'object' ? req : {}), sessionId: rootId })
1331
- })
1332
- }
1333
-
1334
- export function upsertTaskLedgerOnWs(ws, rawTask = {}) {
1335
- if (!ws || typeof ws !== 'object') return null
1336
- if (!Array.isArray(ws.taskLedger)) {
1337
- ws.taskLedger = Array.isArray(ws.resumeTasks) ? ws.resumeTasks : []
1338
- }
1339
- ws.resumeTasks = ws.taskLedger
1340
- const lookupId = rawTask.taskId || rawTask.id
1341
- const existingIdx = lookupId ? ws.taskLedger.findIndex(t => t && (t.taskId === lookupId || t.id === lookupId)) : -1
1342
- if (existingIdx >= 0) {
1343
- const prev = ws.taskLedger[existingIdx]
1344
- const merged = normalizeTaskLedgerEntry({
1345
- ...prev,
1346
- ...rawTask,
1347
- updatedAt: Date.now(),
1348
- completedActions: rawTask.appendCompletedAction
1349
- ? [...(prev.completedActions || []), rawTask.appendCompletedAction]
1350
- : (rawTask.completedActions || prev.completedActions),
1351
- pendingApprovalIds: rawTask.pendingApprovalIds || prev.pendingApprovalIds,
1352
- })
1353
- if (merged) ws.taskLedger[existingIdx] = merged
1354
- return merged
1355
- }
1356
- const created = normalizeTaskLedgerEntry(rawTask)
1357
- if (!created) return null
1358
- ws.taskLedger.push(created)
1359
- if (ws.taskLedger.length > TASK_LEDGER_CAP) {
1360
- ws.taskLedger = ws.taskLedger.slice(-TASK_LEDGER_CAP)
1361
- ws.resumeTasks = ws.taskLedger
1362
- }
1363
- return created
1364
- }
1365
-
1366
- export function upsertResumeTaskOnWs(ws, rawTask = {}) {
1367
- return upsertTaskLedgerOnWs(ws, rawTask)
1368
- }
1369
-
1370
- export function enqueueChiefInquiryOnWs(ws, raw = {}) {
1371
- if (!ws || typeof ws !== 'object') return null
1372
- if (!Array.isArray(ws.inquiries)) ws.inquiries = []
1373
- const norm = normalizeInquiryItem(raw)
1374
- if (!norm) return null
1375
- const dup = ws.inquiries.find(
1376
- q => q && (q.status === 'pending' || q.status === 'delivered') && q.question === norm.question && q.target === norm.target,
1377
- )
1378
- if (dup) return dup
1379
- ws.inquiries.push(norm)
1380
- if (ws.inquiries.length > 24) ws.inquiries = ws.inquiries.slice(-24)
1381
- return norm
1382
- }
1383
-
1384
- export function answerChiefInquiry(sessionId = 'global', { inquiryId = '', answer = '', by = 'lead' } = {}) {
1385
- const rootId = String(sessionId || 'global').trim() || 'global'
1386
- const cleanAns = cleanMultiline(answer || '', 1200)
1387
- if (!cleanAns) return { ok: false, error: 'inquiry.reply 需要非空答复文本 (text)' }
1388
- return mutateChiefState((state) => {
1389
- const ws = ensureWorkspace(state, rootId)
1390
- if (!Array.isArray(ws.inquiries)) ws.inquiries = []
1391
- let idx = inquiryId
1392
- ? ws.inquiries.findIndex(q => q && (q.inquiryId === inquiryId || q.id === inquiryId))
1393
- : -1
1394
- if (idx < 0 && !inquiryId) {
1395
- for (let i = ws.inquiries.length - 1; i >= 0; i -= 1) {
1396
- if (ws.inquiries[i] && (ws.inquiries[i].status === 'pending' || ws.inquiries[i].status === 'delivered')) {
1397
- idx = i
1398
- break
1399
- }
1400
- }
1401
- }
1402
- if (idx < 0) return { ok: false, error: `未找到待回复问询:${inquiryId || '最近未答问询'}` }
1403
- const existing = ws.inquiries[idx]
1404
- if (!existing || existing.status === 'answered' || (existing.status !== 'pending' && existing.status !== 'delivered')) {
1405
- const prevId = (existing && existing.inquiryId) || inquiryId
1406
- const prevStatus = (existing && existing.status) || 'unknown'
1407
- pushAuditToWs(ws, {
1408
- mode: resolveWorkspaceConfig(state, rootId).permissionMode,
1409
- stage: 'inquiry_channel',
1410
- rule: 'inquiry_reply_replay_rejected',
1411
- decision: 'rejected',
1412
- operation: '拦截重复问询答复',
1413
- target: prevId,
1414
- reason: `问询 #${prevId} 已结案 (status=${prevStatus}),拒绝重放覆写`,
1415
- outcome: 'rejected',
1416
- by: clamp(by || 'lead', 40),
1417
- }, rootId)
1418
- return {
1419
- ok: false,
1420
- alreadyAnswered: true,
1421
- code: 'inquiry_already_answered',
1422
- error: `问询 #${prevId} 已回复结案,拒绝重复应答`,
1423
- inquiry: existing,
1424
- }
1425
- }
1426
- const now = Date.now()
1427
- const item = {
1428
- ...existing,
1429
- status: 'answered',
1430
- answer: cleanAns,
1431
- answeredBy: clamp(by || 'lead', 40),
1432
- answeredAt: now,
1433
- }
1434
- ws.inquiries[idx] = item
1435
- if (item.taskId) {
1436
- upsertTaskLedgerOnWs(ws, {
1437
- taskId: item.taskId,
1438
- kind: 'inquiry',
1439
- status: 'completed',
1440
- inquiryId: item.inquiryId,
1441
- lastReceipt: `已收到 ${item.answeredBy} 原路答复:${clamp(cleanAns, 120)}`,
1442
- resolvedAt: now,
1443
- })
1444
- }
1445
- ws.chat.push({
1446
- id: nextId('chat'),
1447
- role: 'chief',
1448
- kind: 'receipt',
1449
- text: `- 【⚡ 优先问询回执 #${item.inquiryId}】已收到 \`${item.answeredBy}\` 不中断原路回复:\n- 【问】${item.question}\n- 【答】${cleanAns}`,
1450
- actions: [`问询已回执 #${item.inquiryId}`],
1451
- at: now,
1452
- })
1453
- if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
1454
- pushAuditToWs(ws, {
1455
- mode: resolveWorkspaceConfig(state, rootId).permissionMode,
1456
- stage: 'inquiry_channel',
1457
- rule: 'inquiry_reply',
1458
- decision: 'answered',
1459
- operation: '优先问询原路回复',
1460
- target: item.inquiryId,
1461
- reason: clamp(cleanAns, 140),
1462
- outcome: 'ok',
1463
- by: item.answeredBy,
1464
- }, rootId)
1465
- return { ok: true, inquiry: item }
1466
- })
1467
- }
1468
-
1469
- const STATE_LOCK_WAIT_MS = 10000
1470
-
1471
- const STATE_LOCK_STALE_MS = 15000
1472
-
1473
- const STATE_LOCK_CONTENDED_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY'])
1474
-
1475
- const heldStateLocks = new Set()
1476
-
1477
- const stateLockSleeper = new Int32Array(new SharedArrayBuffer(4))
1478
-
1479
- function sleepStateLockSync(ms) {
1480
- try {
1481
- Atomics.wait(stateLockSleeper, 0, 0, ms)
1482
- } catch {}
1483
- }
1484
-
1485
- /** Cross-process O_EXCL lock around `chief-state.json` read-modify-write cycles (fixes red-team E1). */
1486
- function acquireStateLock(file = stateFilePath()) {
1487
- if (heldStateLocks.has(file)) return () => {}
1488
- const lock = file + '.lock'
1489
- try {
1490
- fs.mkdirSync(path.dirname(lock), { recursive: true })
1491
- } catch {}
1492
- const deadline = Date.now() + STATE_LOCK_WAIT_MS
1493
- for (;;) {
1494
- try {
1495
- const fd = fs.openSync(lock, 'wx')
1496
- try {
1497
- fs.writeSync(fd, `${process.pid}:${threadId}`)
1498
- } catch {}
1499
- fs.closeSync(fd)
1500
- heldStateLocks.add(file)
1501
- return () => {
1502
- heldStateLocks.delete(file)
1503
- try {
1504
- fs.unlinkSync(lock)
1505
- } catch {}
1506
- }
1507
- } catch (error) {
1508
- const code = error && error.code
1509
- if (code === 'ENOENT' && Date.now() < deadline) {
1510
- try {
1511
- fs.mkdirSync(path.dirname(lock), { recursive: true })
1512
- } catch {}
1513
- sleepStateLockSync(2)
1514
- continue
1515
- }
1516
- if (!error || !STATE_LOCK_CONTENDED_CODES.has(code)) {
1517
- heldStateLocks.add(file)
1518
- return () => heldStateLocks.delete(file)
1519
- }
1520
- if (Date.now() >= deadline) {
1521
- try {
1522
- fs.unlinkSync(lock)
1523
- } catch {}
1524
- heldStateLocks.add(file)
1525
- return () => heldStateLocks.delete(file)
1526
- }
1527
- if (code === 'EEXIST') {
1528
- try {
1529
- const stat = fs.statSync(lock)
1530
- if (Date.now() - stat.mtimeMs > STATE_LOCK_STALE_MS) {
1531
- fs.unlinkSync(lock)
1532
- continue
1533
- }
1534
- } catch {}
1535
- }
1536
- sleepStateLockSync(2 + Math.floor(Math.random() * 4))
1537
- }
1538
- }
1539
- }
1540
-
1541
- export function withChiefStateLock(fn) {
1542
- const file = stateFilePath()
1543
- const release = acquireStateLock(file)
1544
- try {
1545
- return fn()
1546
- } finally {
1547
- release()
1548
- }
1549
- }
1550
-
1551
- let cachedState = null
1552
-
1553
- let cachedMtime = 0
1554
-
1555
- function applyColdLoadLedgerRecovery(state) {
1556
- if (!state || !state.workspaces || typeof state.workspaces !== 'object') return false
1557
- let changed = false
1558
- const now = Date.now()
1559
- for (const ws of Object.values(state.workspaces)) {
1560
- if (!ws || !Array.isArray(ws.taskLedger) || ws.taskLedger.length === 0) continue
1561
- const beforeStatuses = ws.taskLedger.map(t => t && t.status)
1562
- const recovered = recoverTaskLedgerEntriesOnDiskLoad(ws.taskLedger, now)
1563
- ws.taskLedger = recovered
1564
- ws.resumeTasks = recovered
1565
- for (let i = 0; i < recovered.length; i += 1) {
1566
- if (recovered[i] && recovered[i].status !== beforeStatuses[i]) {
1567
- changed = true
1568
- }
1569
- }
1570
- }
1571
- return changed
1572
- }
1573
-
1574
- export function loadChiefState({ forceDisk = false } = {}) {
1575
- const file = stateFilePath()
1576
- try {
1577
- const stat = fs.statSync(file)
1578
- if (!forceDisk && cachedState && stat.mtimeMs === cachedMtime) return cachedState
1579
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
1580
- const nextState = normalizeState(parsed)
1581
- applyColdLoadLedgerRecovery(nextState)
1582
- cachedState = nextState
1583
- cachedMtime = stat.mtimeMs
1584
- return cachedState
1585
- } catch {
1586
- if (forceDisk) {
1587
- cachedState = normalizeState({})
1588
- cachedMtime = -1
1589
- return cachedState
1590
- }
1591
- if (!cachedState) cachedState = normalizeState({})
1592
- return cachedState
1593
- }
1594
- }
1595
-
1596
- export function reconcileChiefStateOnBoot() {
1597
- return mutateChiefState((state) => applyColdLoadLedgerRecovery(state))
1598
- }
1599
-
1600
- export function saveChiefState(state) {
1601
- const normalized = normalizeState(state)
1602
- const file = stateFilePath()
1603
- try {
1604
- fs.mkdirSync(path.dirname(file), { recursive: true })
1605
- const tmp = `${file}.${process.pid}.${threadId}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 6)}.tmp`
1606
- fs.writeFileSync(tmp, JSON.stringify(normalized, null, 2), 'utf8')
1607
- let renameErr = null
1608
- for (let attempt = 0; attempt < 8; attempt += 1) {
1609
- try {
1610
- fs.renameSync(tmp, file)
1611
- renameErr = null
1612
- break
1613
- } catch (err) {
1614
- renameErr = err
1615
- const code = err && err.code
1616
- if (code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') break
1617
- sleepStateLockSync(2 + attempt * 2)
1618
- }
1619
- }
1620
- if (renameErr) {
1621
- try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp) } catch {}
1622
- throw renameErr
1623
- }
1624
- try {
1625
- cachedMtime = fs.statSync(file).mtimeMs
1626
- } catch {
1627
- cachedMtime = -1
1628
- }
1629
- } catch {}
1630
- cachedState = normalized
1631
- return normalized
1632
- }
1633
-
1634
- export function mutateChiefState(mutator) {
1635
- return withChiefStateLock(() => {
1636
- const state = loadChiefState({ forceDisk: true })
1637
- const result = mutator(state)
1638
- saveChiefState(state)
1639
- return result
1640
- })
1641
- }
1642
-
1643
- /** Find connected component of linked root sessions (undirected graph). */
1644
- export function getLinkedCluster(state, rootSessionId) {
1645
- const seed = String(rootSessionId || '').trim()
1646
- if (!seed) return ['global']
1647
- const visited = new Set([seed])
1648
- const queue = [seed]
1649
- const links = (state && state.links) || {}
1650
- while (queue.length > 0) {
1651
- const cur = queue.shift()
1652
- const direct = Array.isArray(links[cur]) ? links[cur] : []
1653
- for (const peer of direct) {
1654
- if (peer && !visited.has(peer)) {
1655
- visited.add(peer)
1656
- queue.push(peer)
1657
- }
1658
- }
1659
- for (const [other, list] of Object.entries(links)) {
1660
- if (Array.isArray(list) && list.includes(cur) && !visited.has(other)) {
1661
- visited.add(other)
1662
- queue.push(other)
1663
- }
1664
- }
1665
- }
1666
- return [...visited].sort()
1667
- }
1668
-
1669
- export function computeClusterSig(cluster = []) {
1670
- return [...new Set((Array.isArray(cluster) ? cluster : []).map(x => String(x || '').trim()).filter(Boolean))].sort().join('|')
1671
- }
1672
-
1673
- export function setPeerLink(rootA, rootB, linked) {
1674
- const a = String(rootA || '').trim()
1675
- const b = String(rootB || '').trim()
1676
- if (!a || !b || a === b) return { ok: false, error: '需要两个不同的主会话才能建立协同连接' }
1677
- return mutateChiefState((state) => {
1678
- const affected = new Set([
1679
- ...getLinkedCluster(state, a),
1680
- ...getLinkedCluster(state, b),
1681
- ])
1682
- const setA = new Set(state.links[a] || [])
1683
- const setB = new Set(state.links[b] || [])
1684
- if (linked) {
1685
- setA.add(b)
1686
- setB.add(a)
1687
- } else {
1688
- setA.delete(b)
1689
- setB.delete(a)
1690
- }
1691
- if (setA.size) state.links[a] = [...setA]
1692
- else delete state.links[a]
1693
- if (setB.size) state.links[b] = [...setB]
1694
- else delete state.links[b]
1695
-
1696
- // Topology isolation guard: purge stale narrative caches on EVERY affected session whose cluster changed
1697
- // so detaching from a peer cluster NEVER leaves residual peer context inside Chief's narrative digest!
1698
- const now = Date.now()
1699
- for (const sid of affected) {
1700
- const ws = ensureWorkspace(state, sid)
1701
- const nextCluster = getLinkedCluster(state, sid)
1702
- const nextSig = computeClusterSig(nextCluster)
1703
- if (!ws.narrative || ws.narrative.clusterSig !== nextSig) {
1704
- ws.narrative = { hash: '', text: '', at: 0, byModel: '', clusterSig: nextSig }
1705
- }
1706
- if (!linked) {
1707
- ws.seenFactsAt = { [sid]: now }
1708
- } else {
1709
- ws.seenFactsAt = {}
1710
- }
1711
- }
1712
- return { ok: true, cluster: getLinkedCluster(state, a) }
1713
- })
1714
- }
1715
-
1716
- export function ensureWorkspace(state, rootId) {
1717
- const key = String(rootId || 'global').trim() || 'global'
1718
- if (!state.workspaces[key]) state.workspaces[key] = emptyWorkspace()
1719
- return state.workspaces[key]
1720
- }
1721
-
1722
- function filterFactsForCluster(rawFacts, clusterSet, rootId) {
1723
- return (Array.isArray(rawFacts) ? rawFacts : []).filter((f) => {
1724
- if (!f || !f.text) return false
1725
- if (f.originRootId && !clusterSet.has(f.originRootId)) return false
1726
- if (f.category === 'team' && Array.isArray(f.peerRootIds) && f.peerRootIds.length > 0) {
1727
- // A team fact created during multi-session collaboration stays ONLY if another participant besides rootId remains linked
1728
- const participants = f.originRootId ? [f.originRootId, ...f.peerRootIds] : f.peerRootIds
1729
- const peerStillLinked = participants.some(pid => pid && pid !== rootId && clusterSet.has(pid))
1730
- if (!peerStillLinked) return false
1731
- }
1732
- return true
1733
- })
1734
- }
1735
-
1736
- function annotateMailClusterState(mail, clusterSet) {
1737
- if (!mail || typeof mail !== 'object') return mail
1738
- const fromOut = Boolean(mail.fromRootId && !clusterSet.has(mail.fromRootId))
1739
- const toOut = Boolean(mail.toRootId && mail.toRootId !== 'all' && !clusterSet.has(mail.toRootId))
1740
- const detachedFromCluster = fromOut || toOut
1741
- return detachedFromCluster ? { ...mail, detachedFromCluster: true } : mail
1742
- }
1743
-
1744
- /** Merge facts & mailbox across all linked peer sessions in the federation cluster, isolating detached artifacts. */
1745
- export function clusterView(state, rootId) {
1746
- const cluster = getLinkedCluster(state, rootId)
1747
- const clusterSig = computeClusterSig(cluster)
1748
- const clusterSet = new Set(cluster)
1749
- const primary = ensureWorkspace(state, rootId)
1750
- if (cluster.length <= 1) {
1751
- return {
1752
- cluster,
1753
- clusterSig,
1754
- primary,
1755
- facts: filterFactsForCluster(primary.facts, clusterSet, rootId),
1756
- mailbox: (primary.mailbox || []).map(m => annotateMailClusterState(m, clusterSet)),
1757
- suggestions: primary.suggestions.filter(s => s.status === 'pending'),
1758
- chat: primary.chat,
1759
- narrative: primary.narrative,
1760
- }
1761
- }
1762
- const factMap = new Map()
1763
- const mailMap = new Map()
1764
- for (const sid of cluster) {
1765
- const ws = ensureWorkspace(state, sid)
1766
- for (const f of filterFactsForCluster(ws.facts, clusterSet, rootId)) factMap.set(f.id, f)
1767
- for (const m of ws.mailbox) {
1768
- if (m && m.broadcastId && m.channelType === 'broadcast') {
1769
- mailMap.set('bcast:' + m.broadcastId, annotateMailClusterState(m, clusterSet))
1770
- } else {
1771
- mailMap.set(m.id, annotateMailClusterState(m, clusterSet))
1772
- }
1773
- }
1774
- }
1775
- const facts = [...factMap.values()].sort((a, b) => (a.addedAt || 0) - (b.addedAt || 0)).slice(-FACTS_CAP)
1776
- const mailbox = [...mailMap.values()].sort((a, b) => (a.at || 0) - (b.at || 0)).slice(-MAIL_CAP)
1777
- return {
1778
- cluster,
1779
- clusterSig,
1780
- primary,
1781
- facts,
1782
- mailbox,
1783
- suggestions: primary.suggestions.filter(s => s.status === 'pending'),
1784
- chat: primary.chat,
1785
- narrative: primary.narrative,
1786
- }
1787
- }
1788
-
1789
- /* -------------------------------------------------------------------------- */
1790
- /* Model Catalog & Auxiliary LLM Caller */
1791
- /* -------------------------------------------------------------------------- */
1792
-
1793
- /** Manage which cold precipitated-vault entries are explicitly unsealed/flipped into a single root session. */
1794
- export function updateWorkspaceFlippedIds(sessionId, { flippedId = '', sealId = '', clearAll = false } = {}) {
1795
- const key = String(sessionId || 'global').trim() || 'global'
1796
- return mutateChiefState((state) => {
1797
- const ws = ensureWorkspace(state, key)
1798
- const set = new Set(ws.flippedPrecipitatedIds || [])
1799
- if (clearAll) {
1800
- set.clear()
1801
- } else {
1802
- if (flippedId) set.add(String(flippedId).trim())
1803
- if (sealId) set.delete(String(sealId).trim())
1804
- }
1805
- ws.flippedPrecipitatedIds = [...set].slice(-20)
1806
- return { ok: true, flippedPrecipitatedIds: ws.flippedPrecipitatedIds.slice() }
1807
- })
1808
- }
1809
-
1810
- /** One-click system deployment of Chief state (`facts`, `narrative`, `chat`/`mailbox` bridge) to a target Chief workspace (strictly keeping `flippedPrecipitatedIds = []`). */
1811
- export function deployChiefWorkspaceState(deps, {
1812
- fromRootId = '',
1813
- toRootId = '',
1814
- fromTitle = '',
1815
- customText = '',
1816
- objective = '',
1817
- } = {}) {
1818
- const fromKey = String(fromRootId || 'global').trim() || 'global'
1819
- const toKey = String(toRootId || '').trim()
1820
- if (!toKey) return { ok: false, error: '目标会话 ID 不能为空' }
1821
-
1822
- return mutateChiefState((state) => {
1823
- const fromWs = ensureWorkspace(state, fromKey)
1824
- const toWs = ensureWorkspace(state, toKey)
1825
-
1826
- const existingTexts = new Set(toWs.facts.map(f => f.text.trim()))
1827
- let copiedFacts = 0
1828
- for (const f of fromWs.facts) {
1829
- if (!f || !f.text) continue
1830
- const norm = f.text.trim()
1831
- if (existingTexts.has(norm)) continue
1832
- existingTexts.add(norm)
1833
- toWs.facts.push({
1834
- ...f,
1835
- id: nextId('fact'),
1836
- originRootId: toKey === 'global' ? (f.originRootId || '') : toKey,
1837
- peerRootIds: [],
1838
- source: f.source || `移交自 ${fromTitle || fromKey}`,
1839
- updatedAt: Date.now(),
1840
- })
1841
- copiedFacts += 1
1842
- }
1843
- if (toWs.facts.length > FACTS_CAP) {
1844
- const pinned = toWs.facts.filter(f => f.pinned)
1845
- const rest = toWs.facts.filter(f => !f.pinned).slice(-(FACTS_CAP - pinned.length))
1846
- toWs.facts = [...pinned, ...rest].slice(-FACTS_CAP)
1847
- }
1848
-
1849
- if (fromWs.narrative && fromWs.narrative.text && !toWs.narrative.text) {
1850
- toWs.narrative = {
1851
- ...fromWs.narrative,
1852
- hash: fromWs.narrative.hash || '',
1853
- clusterSig: toKey,
1854
- at: Date.now(),
1855
- }
1856
- }
1857
-
1858
- const briefLines = [
1859
- `- 【跨会话接力部署】本会话参谋状态已自 **${fromTitle || fromKey}** 系统级一键移交部署完成(新对话默认以 **L0 · 顾问模式** 安全启动)。`,
1860
- objective ? `- 【继承总目标】${clamp(objective, 180)}` : '',
1861
- copiedFacts > 0 ? `- 【继承纪律与事实】共继承 **${copiedFacts} 条**核心记忆与纪律。` : '',
1862
- customText ? `- 【附带交接叮嘱】${clamp(customText, 240)}` : '',
1863
- ].filter(Boolean).join('\n')
1864
-
1865
- const mailItem = normalizeMail({
1866
- id: nextId('mail'),
1867
- from: 'DSH 参谋长 (接力部署)',
1868
- fromSession: fromKey,
1869
- to: 'lead',
1870
- toSession: toKey,
1871
- subject: `跨会话参谋部署:自 ${fromTitle || fromKey}`,
1872
- text: briefLines,
1873
- mode: 'silent',
1874
- deliveredPhysical: false,
1875
- at: Date.now(),
1876
- })
1877
- if (mailItem) {
1878
- toWs.mailbox.push(mailItem)
1879
- if (toWs.mailbox.length > MAIL_CAP) toWs.mailbox = toWs.mailbox.slice(-MAIL_CAP)
1880
- }
1881
-
1882
- toWs.chat.push({
1883
- id: nextId('chat'),
1884
- role: 'chief',
1885
- text: briefLines,
1886
- actions: ['系统接力部署', '默认 L0 顾问', ...(copiedFacts > 0 ? [`继承记忆 ×${copiedFacts}`] : [])],
1887
- at: Date.now(),
1888
- })
1889
- if (toWs.chat.length > CHAT_CAP) toWs.chat = toWs.chat.slice(-CHAT_CAP)
1890
-
1891
- // Clone safe workspace chief config (model, effort, tactical preferences), ALWAYS forcing intervention=false, runMode='off' & L0 advisor!
1892
- const fromCfg = resolveWorkspaceConfig(state, fromKey)
1893
- toWs.config = {
1894
- modelRef: fromCfg.modelRef || '',
1895
- paceMode: 'manual',
1896
- runMode: 'off',
1897
- thinkingEffort: fromCfg.thinkingEffort || 'auto',
1898
- teamEffortMode: fromCfg.teamEffortMode || 'auto',
1899
- managedIdleTimeoutMs: fromCfg.managedIdleTimeoutMs || DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
1900
- permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
1901
- autoPilot: false,
1902
- autoReview: false,
1903
- tacticalModes: {
1904
- ...normalizeTacticalModes(fromCfg.tacticalModes),
1905
- intervention: false,
1906
- },
1907
- }
1908
- toWs.chiefRiskAck = null
1909
- toWs.pendingApprovals = []
1910
- toWs.pendingElevation = null
1911
- pushAuditToWs(toWs, {
1912
- mode: DEFAULT_CHIEF_PERMISSION_MODE,
1913
- stage: 'deploy',
1914
- decision: 'reset_to_l0',
1915
- operation: '跨会话接力部署',
1916
- target: toKey,
1917
- reason: '新对话强制从最低档 L0 顾问模式安全启动并清空高权限状态',
1918
- outcome: 'ok',
1919
- by: 'deploy',
1920
- })
1921
- toWs.runtimeGuard.interventionTurns = 0
1922
- toWs.runtimeGuard.unchangedCount = 0
1923
- toWs.runtimeGuard.circuitBroken = false
1924
- toWs.runtimeGuard.circuitReason = ''
1925
-
1926
- // Strictly keep precipitated cold vault isolated at 0-token default in destination session!
1927
- toWs.flippedPrecipitatedIds = []
1928
-
1929
- return {
1930
- ok: true,
1931
- copiedFacts,
1932
- narrativeCopied: Boolean(fromWs.narrative && fromWs.narrative.text),
1933
- flippedPrecipitatedIds: [],
1934
- config: { ...toWs.config, tacticalModes: { ...toWs.config.tacticalModes } },
1935
- }
1936
- })
1937
- }
1938
-
1939
- /* -------------------------------------------------------------------------- */
1940
- /* Chief Command Bar: All-Seeing Strategist + Relay + Bounds + Board Ops */
1941
- /* -------------------------------------------------------------------------- */
1942
-
1943
- export function updateChiefConfig(patch) {
1944
- const safePatch = patch && typeof patch === 'object' ? patch : {}
1945
- const sid = String(safePatch.sessionId || safePatch.session || '').trim() || 'global'
1946
- return mutateChiefState((state) => {
1947
- const ws = ensureWorkspace(state, sid)
1948
- const effBefore = resolveWorkspaceConfig(state, sid)
1949
- const prevTactical = normalizeTacticalModes(effBefore.tacticalModes)
1950
- if (typeof safePatch.ackHazardAlertId === 'string' && safePatch.ackHazardAlertId.trim()) {
1951
- const ackId = safePatch.ackHazardAlertId.trim()
1952
- if (ws && ws.runtimeGuard && ws.runtimeGuard.hazardAlert && (ackId === '*' || ws.runtimeGuard.hazardAlert.id === ackId)) {
1953
- ws.runtimeGuard.hazardAlert = null
1954
- }
1955
- const hasOtherKeys = Object.keys(safePatch).some(
1956
- k => k !== 'sessionId' && k !== 'session' && k !== 'ackHazardAlertId',
1957
- )
1958
- if (!hasOtherKeys) {
1959
- const curCfg = resolveWorkspaceConfig(state, sid)
1960
- return {
1961
- ok: true,
1962
- clearedHazardAlert: true,
1963
- config: { ...curCfg, tacticalModes: { ...curCfg.tacticalModes } },
1964
- runtimeGuard: ws ? { ...ws.runtimeGuard } : null,
1965
- }
1966
- }
1967
- }
1968
-
1969
- if (safePatch.emergencyStopIntervention === true) {
1970
- if (ws) {
1971
- if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effBefore }
1972
- ws.config.tacticalModes = { ...normalizeTacticalModes(ws.config.tacticalModes), intervention: false }
1973
- ws.runtimeGuard.interventionTurns = 0
1974
- ws.runtimeGuard.unchangedCount = 0
1975
- ws.runtimeGuard.circuitBroken = false
1976
- ws.runtimeGuard.circuitReason = ''
1977
- ws.runtimeGuard.hazardAlert = null
1978
- }
1979
- state.config.tacticalModes = { ...normalizeTacticalModes(state.config.tacticalModes), intervention: false }
1980
- const stoppedCfg = resolveWorkspaceConfig(state, sid)
1981
- return {
1982
- ok: true,
1983
- emergencyStopped: true,
1984
- config: { ...stoppedCfg, tacticalModes: { ...stoppedCfg.tacticalModes } },
1985
- runtimeGuard: ws ? { ...ws.runtimeGuard } : null,
1986
- }
1987
- }
1988
-
1989
- // Hard gate on model thinking effort lock mutations (human UI / explicit byUser only)
1990
- const callerBy = typeof safePatch.by === 'string' ? safePatch.by.trim() : ''
1991
- const isHumanBy = !callerBy || /^(?:user|human|operator|ui_panel)$/i.test(callerBy)
1992
- const isHumanLockCaller = safePatch._fromUiPanel === true
1993
- || (safePatch.byUser === true && isHumanBy)
1994
- const wantsLockMutation = safePatch.lockedModelEfforts !== undefined
1995
- || safePatch.toggleLockAgentEffort !== undefined
1996
- || safePatch.teamEffortMode !== undefined
1997
- if (wantsLockMutation && !isHumanLockCaller) {
1998
- pushAuditToWs(ws, {
1999
- mode: effBefore.permissionMode,
2000
- stage: 'model_effort_lock',
2001
- rule: 'effort_lock_human_only',
2002
- decision: 'blocked',
2003
- operation: '修改模型思考强度锁挡',
2004
- target: sid,
2005
- reason: `未授权来源 (${callerBy || 'unknown'}) 试图修改 lockedModelEfforts,仅允许人类面板显式操作`,
2006
- outcome: 'rejected',
2007
- by: clamp(callerBy || 'unknown', 40),
2008
- }, sid)
2009
- return {
2010
- ok: false,
2011
- blocked: true,
2012
- lockedByUser: true,
2013
- code: 'effort_lock_human_only',
2014
- error: '思考强度锁挡 (lockedModelEfforts) 仅允许人类通过面板或显式 byUser 授权修改,已拦截越权变更',
2015
- }
2016
- }
2017
- if (
2018
- typeof safePatch.thinkingEffort === 'string'
2019
- && effBefore.lockedModelEfforts
2020
- && effBefore.lockedModelEfforts.chief === true
2021
- && !isHumanLockCaller
2022
- ) {
2023
- pushAuditToWs(ws, {
2024
- mode: effBefore.permissionMode,
2025
- stage: 'model_effort_lock',
2026
- rule: 'effort_lock_human_only',
2027
- decision: 'blocked',
2028
- operation: '修改参谋长思考强度',
2029
- target: sid,
2030
- reason: `参谋长思考强度已被用户锁定 (lockedModelEfforts.chief),拒绝非人类来源 (${callerBy || 'unknown'}) 修改`,
2031
- outcome: 'rejected',
2032
- by: clamp(callerBy || 'unknown', 40),
2033
- }, sid)
2034
- return {
2035
- ok: false,
2036
- blocked: true,
2037
- lockedByUser: true,
2038
- code: 'effort_lock_human_only',
2039
- error: '参谋长思考强度已被用户锁定 (lockedModelEfforts.chief),仅允许人类显式修改',
2040
- }
2041
- }
2042
-
2043
- // Check explicit Policy Plugin list (restrict-only) BEFORE applying any changes
2044
- let validatedPlugins = null
2045
- if (safePatch.policyPlugins !== undefined) {
2046
- const plugCheck = validatePolicyPluginList(safePatch.policyPlugins)
2047
- if (!plugCheck.ok) {
2048
- pushAuditToWs(ws, {
2049
- mode: effBefore.permissionMode,
2050
- stage: 'policy_plugin',
2051
- rule: plugCheck.code || 'policy_plugin_rejected',
2052
- decision: 'rejected',
2053
- operation: '配置只紧不松策略插件',
2054
- target: sid,
2055
- reason: plugCheck.error,
2056
- outcome: 'rejected',
2057
- by: clamp(safePatch.by || 'operator', 40),
2058
- }, sid)
2059
- return {
2060
- ok: false,
2061
- code: plugCheck.code || 'POLICY_PLUGIN_WEAKENING_FORBIDDEN',
2062
- error: plugCheck.error,
2063
- }
2064
- }
2065
- validatedPlugins = plugCheck.plugins
2066
- }
2067
-
2068
- // Check explicit permission mode transition BEFORE applying any changes
2069
- let normalizedReqPerm = ''
2070
- if (typeof safePatch.permissionMode === 'string' && safePatch.permissionMode.trim()) {
2071
- normalizedReqPerm = normalizePermissionMode(safePatch.permissionMode)
2072
- if (normalizedReqPerm === 'chief' && safePatch.confirmedChiefRisk !== true && !hasValidChiefRiskAck(ws)) {
2073
- pushAuditToWs(ws, {
2074
- mode: effBefore.permissionMode,
2075
- stage: 'permission_gate',
2076
- decision: 'deny_unacknowledged_l3',
2077
- operation: '切换 L3 参谋长模式',
2078
- target: sid,
2079
- reason: '未阅读并勾选确认高权限风险告知(confirmedChiefRisk: true)',
2080
- outcome: 'denied',
2081
- by: 'operator',
2082
- })
2083
- return {
2084
- ok: false,
2085
- requireChiefRiskConfirm: true,
2086
- error: '启用「L3 · 参谋长模式」前必须阅读高权限风险告知并主动勾选确认(confirmedChiefRisk: true)',
2087
- }
2088
- }
2089
- }
2090
-
2091
- const incomingTacticalRaw = safePatch.tacticalModes && typeof safePatch.tacticalModes === 'object'
2092
- ? safePatch.tacticalModes
2093
- : null
2094
- let incomingTactical = incomingTacticalRaw ? { ...incomingTacticalRaw } : null
2095
- if (incomingTactical && incomingTactical.intervention === true && !prevTactical.intervention) {
2096
- if (safePatch.confirmedInterventionRisk !== true) {
2097
- return {
2098
- ok: false,
2099
- error: '开启「接管督导模式」需先确认双项风险免责声明(confirmedInterventionRisk: true)',
2100
- }
2101
- }
2102
- if (ws) {
2103
- ws.runtimeGuard.interventionTurns = 0
2104
- ws.runtimeGuard.unchangedCount = 0
2105
- ws.runtimeGuard.circuitBroken = false
2106
- ws.runtimeGuard.circuitReason = ''
2107
- ws.runtimeGuard.hazardAlert = null
2108
- ws.runtimeGuard.lastGoalAchievedSig = ''
2109
- }
2110
- }
2111
-
2112
- const wantsUnlimitedTurns = Boolean(
2113
- incomingTactical
2114
- && (incomingTactical.maxInterventionTurns === 0 || incomingTactical.maxInterventionTurns === '0')
2115
- )
2116
- if (wantsUnlimitedTurns && prevTactical.maxInterventionTurns !== 0 && safePatch.confirmedUnlimitedTurns !== true) {
2117
- return {
2118
- ok: false,
2119
- error: '切换至「♾️ 无限督导轮次」需先通过作者风险确认弹窗(confirmedUnlimitedTurns: true)',
2120
- }
2121
- }
2122
-
2123
- const wantsAutoPilot = Boolean(
2124
- safePatch.runMode === 'managed'
2125
- || safePatch.paceMode === 'auto'
2126
- || (typeof safePatch.paceMode !== 'string' && typeof safePatch.runMode !== 'string' && safePatch.stopped !== true && safePatch.autoPilot === true)
2127
- )
2128
- if (wantsAutoPilot && effBefore.runMode !== 'managed' && effBefore.paceMode !== 'auto' && safePatch.confirmedAutoPilot !== true) {
2129
- return {
2130
- ok: false,
2131
- requireAutoPilotConfirm: true,
2132
- error: '开启「🤖 托管模式」需先确认本会话自治范围与 5 条件自动休眠保护(confirmedAutoPilot: true)',
2133
- }
2134
- }
2135
- if (ws && wantsAutoPilot && (effBefore.runMode !== 'managed' || effBefore.paceMode !== 'auto')) {
2136
- const now = Date.now()
2137
- ws.runtimeGuard.autoPilotStartedAt = now
2138
- ws.runtimeGuard.managedStartedAt = now
2139
- ws.runtimeGuard.lastActivityAt = now
2140
- ws.runtimeGuard.autoPilotHadTurn = false
2141
- }
2142
-
2143
- let compactLowWarning = ''
2144
- if (incomingTactical && typeof incomingTactical.compactThresholdInput === 'string') {
2145
- const parsedTok = parseCompactTokensInput(incomingTactical.compactThresholdInput)
2146
- if (!parsedTok.ok) {
2147
- return { ok: false, error: parsedTok.error }
2148
- }
2149
- incomingTactical.compactThresholdTokens = parsedTok.tokens
2150
- incomingTactical.compactThresholdInput = parsedTok.displayInput
2151
- compactLowWarning = parsedTok.lowWarning || ''
2152
- } else if (incomingTactical && typeof incomingTactical.compactThresholdTokens === 'number') {
2153
- const safeTok = Math.max(COMPACT_TOKEN_HARD_MIN, Math.round(incomingTactical.compactThresholdTokens))
2154
- incomingTactical.compactThresholdTokens = safeTok
2155
- incomingTactical.compactThresholdInput = formatCompactTokenShort(safeTok)
2156
- if (safeTok < COMPACT_TOKEN_WARN_FLOOR) {
2157
- compactLowWarning = `当前阈值(${incomingTactical.compactThresholdInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
2158
- }
2159
- }
2160
-
2161
- const applyPatchTo = (targetCfg, allowIntervention, allowAutoPilot = allowIntervention, allowPermSync = false, allowLocks = false) => {
2162
- if (typeof safePatch.modelRef === 'string') targetCfg.modelRef = safePatch.modelRef.trim()
2163
- if (typeof safePatch.thinkingEffort === 'string') {
2164
- targetCfg.thinkingEffort = normalizeThinkingEffort(safePatch.thinkingEffort)
2165
- }
2166
- if (allowLocks && typeof safePatch.teamEffortMode === 'string') {
2167
- targetCfg.teamEffortMode = normalizeTeamEffortMode(safePatch.teamEffortMode)
2168
- }
2169
- if (Number.isFinite(Number(safePatch.managedIdleTimeoutMs)) && Number(safePatch.managedIdleTimeoutMs) >= 50) {
2170
- targetCfg.managedIdleTimeoutMs = Math.min(2 * 60 * 60 * 1000, Math.round(Number(safePatch.managedIdleTimeoutMs)))
2171
- }
2172
- if (allowLocks && (
2173
- (safePatch.lockedModelEfforts && typeof safePatch.lockedModelEfforts === 'object')
2174
- || (safePatch.toggleLockAgentEffort && typeof safePatch.toggleLockAgentEffort === 'object')
2175
- )) {
2176
- const curLocks = { ...(targetCfg.lockedModelEfforts || {}) }
2177
- if (safePatch.lockedModelEfforts && typeof safePatch.lockedModelEfforts === 'object') {
2178
- for (const [lk, lv] of Object.entries(safePatch.lockedModelEfforts)) {
2179
- const ck = String(lk || '').trim().slice(0, 64)
2180
- if (!ck) continue
2181
- if (lv === true) curLocks[ck] = true
2182
- else delete curLocks[ck]
2183
- }
2184
- }
2185
- if (safePatch.toggleLockAgentEffort && typeof safePatch.toggleLockAgentEffort === 'object') {
2186
- const lk = String(safePatch.toggleLockAgentEffort.target || 'lead').trim().slice(0, 64)
2187
- if (lk) {
2188
- if (safePatch.toggleLockAgentEffort.locked === true) curLocks[lk] = true
2189
- else delete curLocks[lk]
2190
- }
2191
- }
2192
- targetCfg.lockedModelEfforts = curLocks
2193
- }
2194
- if (allowPermSync && normalizedReqPerm) {
2195
- targetCfg.permissionMode = normalizedReqPerm
2196
- }
2197
- if (typeof safePatch.runMode === 'string' && CHIEF_RUN_MODES.includes(safePatch.runMode)) {
2198
- const nextRun = (!allowAutoPilot && safePatch.runMode === 'managed') ? 'off' : safePatch.runMode
2199
- targetCfg.runMode = nextRun
2200
- targetCfg.stopped = false
2201
- targetCfg.paceMode = nextRun === 'managed' ? 'auto' : (nextRun === 'patrol' ? 'smart' : 'manual')
2202
- targetCfg.autoPilot = nextRun === 'managed' && allowAutoPilot
2203
- targetCfg.autoReview = nextRun === 'managed' && allowAutoPilot
2204
- } else if (typeof safePatch.paceMode === 'string' && ['manual', 'smart', 'auto', 'stopped'].includes(safePatch.paceMode)) {
2205
- const nextPace = (!allowAutoPilot && safePatch.paceMode === 'auto') ? 'manual' : safePatch.paceMode
2206
- targetCfg.paceMode = nextPace
2207
- const isStopped = nextPace === 'stopped'
2208
- targetCfg.stopped = isStopped
2209
- targetCfg.runMode = isStopped ? 'off' : (nextPace === 'auto' ? 'managed' : (nextPace === 'smart' ? 'patrol' : 'off'))
2210
- targetCfg.autoPilot = !isStopped && nextPace === 'auto' && allowAutoPilot
2211
- targetCfg.autoReview = !isStopped && nextPace === 'auto' && allowAutoPilot
2212
- } else if (typeof safePatch.stopped === 'boolean') {
2213
- targetCfg.stopped = safePatch.stopped
2214
- if (safePatch.stopped) {
2215
- targetCfg.paceMode = 'stopped'
2216
- targetCfg.runMode = 'off'
2217
- targetCfg.autoPilot = false
2218
- targetCfg.autoReview = false
2219
- } else {
2220
- if (targetCfg.paceMode === 'stopped') targetCfg.paceMode = 'manual'
2221
- if (!allowAutoPilot && targetCfg.paceMode === 'auto') targetCfg.paceMode = 'manual'
2222
- targetCfg.runMode = normalizeRunMode(targetCfg.runMode, targetCfg)
2223
- targetCfg.autoPilot = targetCfg.paceMode === 'auto' && allowAutoPilot
2224
- targetCfg.autoReview = targetCfg.paceMode === 'auto' && allowAutoPilot
2225
- }
2226
- } else if (typeof safePatch.autoPilot === 'boolean') {
2227
- const nextAuto = Boolean(safePatch.autoPilot && allowAutoPilot)
2228
- targetCfg.stopped = false
2229
- targetCfg.paceMode = nextAuto ? 'auto' : 'manual'
2230
- targetCfg.runMode = nextAuto ? 'managed' : 'off'
2231
- targetCfg.autoPilot = nextAuto
2232
- targetCfg.autoReview = nextAuto
2233
- }
2234
- if (!allowAutoPilot && (targetCfg.paceMode === 'auto' || targetCfg.runMode === 'managed')) {
2235
- targetCfg.paceMode = 'manual'
2236
- targetCfg.runMode = 'off'
2237
- targetCfg.autoPilot = false
2238
- targetCfg.autoReview = false
2239
- }
2240
- if (typeof safePatch.autoReview === 'boolean' && typeof safePatch.paceMode !== 'string' && typeof safePatch.runMode !== 'string' && typeof safePatch.stopped !== 'boolean') {
2241
- targetCfg.autoReview = safePatch.autoReview
2242
- if (!safePatch.autoReview) {
2243
- targetCfg.stopped = false
2244
- targetCfg.paceMode = 'manual'
2245
- targetCfg.runMode = 'off'
2246
- }
2247
- }
2248
- if (incomingTactical) {
2249
- const merged = normalizeTacticalModes({
2250
- ...normalizeTacticalModes(targetCfg.tacticalModes),
2251
- ...incomingTactical,
2252
- })
2253
- if (!allowIntervention) merged.intervention = false
2254
- targetCfg.tacticalModes = merged
2255
- } else if (!allowIntervention && targetCfg.tacticalModes) {
2256
- targetCfg.tacticalModes = { ...normalizeTacticalModes(targetCfg.tacticalModes), intervention: false }
2257
- }
2258
- }
2259
-
2260
- if (!ws.config || typeof ws.config !== 'object') {
2261
- ws.config = {
2262
- modelRef: effBefore.modelRef || '',
2263
- paceMode: effBefore.paceMode || 'manual',
2264
- runMode: effBefore.runMode || 'off',
2265
- thinkingEffort: effBefore.thinkingEffort || 'auto',
2266
- teamEffortMode: effBefore.teamEffortMode || 'auto',
2267
- managedIdleTimeoutMs: effBefore.managedIdleTimeoutMs || DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
2268
- lockedModelEfforts: { ...(effBefore.lockedModelEfforts || {}) },
2269
- permissionMode: effBefore.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
2270
- tacticalModes: { ...effBefore.tacticalModes },
2271
- }
2272
- }
2273
- applyPatchTo(ws.config, true, true, true, isHumanLockCaller)
2274
- if (validatedPlugins !== null) {
2275
- if (safePatch.policyPluginsScope === 'global') {
2276
- state.config.policyPlugins = validatedPlugins
2277
- } else {
2278
- ws.config.policyPlugins = validatedPlugins
2279
- }
2280
- pushAuditToWs(ws, {
2281
- mode: resolveWorkspaceConfig(state, sid).permissionMode,
2282
- stage: 'policy_plugin',
2283
- rule: 'policy_plugin_updated',
2284
- decision: 'executed',
2285
- operation: '更新安全策略插件',
2286
- target: `${safePatch.policyPluginsScope === 'global' ? 'global' : sid} (${validatedPlugins.length} 个)`,
2287
- reason: `已加载 ${validatedPlugins.length} 个只紧不松安全策略插件`,
2288
- outcome: 'ok',
2289
- by: clamp(safePatch.by || 'operator', 40),
2290
- }, sid)
2291
- }
2292
- // Session permissionMode, intervention, lockedModelEfforts, and autoPilot NEVER leak globally across new sessions!
2293
- state.config.permissionMode = DEFAULT_CHIEF_PERMISSION_MODE
2294
- applyPatchTo(state.config, false, false, false, false)
2295
-
2296
- if (normalizedReqPerm) {
2297
- if (normalizedReqPerm === 'chief' && safePatch.confirmedChiefRisk === true) {
2298
- ws.chiefRiskAck = {
2299
- acknowledged: true,
2300
- at: Date.now(),
2301
- by: clamp(safePatch.by || 'operator', 40),
2302
- version: '1.2.1',
2303
- }
2304
- } else if (normalizedReqPerm !== 'chief') {
2305
- ws.chiefRiskAck = null
2306
- }
2307
- if (normalizedReqPerm !== effBefore.permissionMode) {
2308
- if (ws.pendingElevation && permissionRank(normalizedReqPerm) >= permissionRank(ws.pendingElevation.targetMode)) {
2309
- ws.pendingElevation = null
2310
- }
2311
- pushAuditToWs(ws, {
2312
- mode: normalizedReqPerm,
2313
- stage: 'permission_gate',
2314
- decision: 'mode_changed',
2315
- operation: '切换权限等级',
2316
- target: `${CHIEF_PERMISSION_META[effBefore.permissionMode].level} -> ${CHIEF_PERMISSION_META[normalizedReqPerm].level}`,
2317
- reason: normalizedReqPerm === 'chief' ? '用户勾选风险声明并确认启用 L3 参谋长模式' : `用户主动切换至 ${CHIEF_PERMISSION_META[normalizedReqPerm].title}`,
2318
- outcome: 'ok',
2319
- by: clamp(safePatch.by || 'operator', 40),
2320
- })
2321
- }
2322
- }
2323
-
2324
- const finalCfg = resolveWorkspaceConfig(state, sid)
2325
- if (!compactLowWarning && finalCfg.tacticalModes.compactThresholdMode === 'tokens' && finalCfg.tacticalModes.compactThresholdTokens < COMPACT_TOKEN_WARN_FLOOR) {
2326
- compactLowWarning = `当前阈值(${finalCfg.tacticalModes.compactThresholdInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
2327
- } else if (!compactLowWarning && finalCfg.tacticalModes.compactThresholdMode !== 'tokens' && finalCfg.tacticalModes.compactThresholdPct < COMPACT_PCT_WARN_FLOOR) {
2328
- compactLowWarning = `当前触发比例(${finalCfg.tacticalModes.compactThresholdPct}%)低于安全建议线 ${COMPACT_PCT_WARN_FLOOR}%,可能导致上下文频繁提前归档压缩`
2329
- }
2330
- return {
2331
- ok: true,
2332
- ...(compactLowWarning ? { compactLowWarning } : {}),
2333
- config: { ...finalCfg, tacticalModes: { ...finalCfg.tacticalModes } },
2334
- }
2335
- })
2336
- }
2337
-
2338
- export function mutateChiefFact(deps, { sessionId, op, id, text, category, pinned }) {
2339
- const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
2340
- return mutateChiefState((state) => {
2341
- const ws = ensureWorkspace(state, rootId)
2342
- if (op === 'add') {
2343
- const cat = category || 'discipline'
2344
- const activeCluster = getLinkedCluster(state, rootId)
2345
- const fact = normalizeFact({
2346
- text,
2347
- category: cat,
2348
- by: 'user',
2349
- pinned: Boolean(pinned),
2350
- originRootId: rootId === 'global' ? '' : rootId,
2351
- peerRootIds: cat === 'team' ? activeCluster.filter(pid => pid !== rootId) : [],
2352
- })
2353
- if (!fact) return { ok: false, error: '条目无效或包含敏感凭据' }
2354
- ws.facts.push(fact)
2355
- if (ws.facts.length > FACTS_CAP) ws.facts = ws.facts.slice(-FACTS_CAP)
2356
- return { ok: true, fact }
2357
- }
2358
- const target = ws.facts.find(f => f.id === id)
2359
- if (!target) return { ok: false, error: '未找到该记忆条目' }
2360
- if (op === 'remove') {
2361
- ws.facts = ws.facts.filter(f => f.id !== id)
2362
- return { ok: true }
2363
- }
2364
- if (op === 'pin') {
2365
- target.pinned = Boolean(pinned)
2366
- target.updatedAt = Date.now()
2367
- return { ok: true, fact: target }
2368
- }
2369
- if (op === 'edit') {
2370
- const clean = clamp(text, FACT_TEXT_MAX)
2371
- if (!clean || secretLike(clean)) return { ok: false, error: '内容无效或包含敏感凭据' }
2372
- target.text = clean
2373
- if (category) target.category = category
2374
- target.updatedAt = Date.now()
2375
- return { ok: true, fact: target }
2376
- }
2377
- return { ok: false, error: '未知操作: ' + op }
2378
- })
2379
- }
2380
-
2381
- export function shortAgentBriefName(name) {
2382
- const raw = String(name || '').trim()
2383
- if (!raw) return ''
2384
- return raw
2385
- .split('/')
2386
- .map(seg => seg.replace(/[-_]([0-9a-f]{8,40})$/i, (_, hex) => '·' + hex.slice(0, 4)))
2387
- .join('/')
2388
- }
2389
-
2390
- export function stripCheckpointNoise(text) {
2391
- return String(text || '')
2392
- .replace(/\[dsh-mnemon:[^\]]*\][\s\S]*/gi, '')
2393
- .replace(/Bounded completed checkpoint[\s\S]*/gi, '')
2394
- .replace(/\s+/g, ' ')
2395
- .trim()
2396
- }
2397
-
2398
- export function isInternalCheckpointNoise(text) {
2399
- const s = stripCheckpointNoise(text)
2400
- if (!s) return true
2401
- if (/^Mnemon idle checkpoint review\b/i.test(s)) return true
2402
- return false
2403
- }
2404
-
2405
- function repairJsonInvalidEscapes(jsonStr) {
2406
- let out = ''
2407
- let inString = false
2408
- for (let i = 0; i < jsonStr.length; i += 1) {
2409
- const ch = jsonStr[i]
2410
- if (!inString) {
2411
- if (ch === '"') inString = true
2412
- out += ch
2413
- continue
2414
- }
2415
- if (ch === '"') {
2416
- inString = false
2417
- out += ch
2418
- continue
2419
- }
2420
- if (ch === '\\') {
2421
- const next = jsonStr[i + 1]
2422
- if (next === undefined) {
2423
- out += '\\\\'
2424
- continue
2425
- }
2426
- if (next === 'u' && /^[0-9a-fA-F]{4}$/.test(jsonStr.slice(i + 2, i + 6))) {
2427
- out += jsonStr.slice(i, i + 6)
2428
- i += 5
2429
- continue
2430
- }
2431
- if ('"\\/bfnrt'.includes(next)) {
2432
- out += '\\' + next
2433
- i += 1
2434
- continue
2435
- }
2436
- // Escape invalid bare backslash (e.g. regex \s, \., Windows D:\path) inside JSON strings
2437
- out += '\\\\'
2438
- continue
2439
- }
2440
- out += ch
2441
- }
2442
- return out
2443
- }
2444
-
2445
- function tryParseJsonRobust(candidate) {
2446
- if (!candidate) return null
2447
- try {
2448
- const parsed = JSON.parse(candidate)
2449
- if (parsed && typeof parsed === 'object') return parsed
2450
- } catch {}
2451
- try {
2452
- const repaired = repairJsonInvalidEscapes(candidate)
2453
- const parsed = JSON.parse(repaired)
2454
- if (parsed && typeof parsed === 'object') return parsed
2455
- } catch {}
2456
- return null
2457
- }
2458
-
2459
- export function extractJsonObject(raw) {
2460
- const text = String(raw || '').trim()
2461
- if (!text) return null
2462
- const stripped = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim()
2463
- const direct = tryParseJsonRobust(stripped)
2464
- if (direct) return direct
2465
- const first = text.indexOf('{')
2466
- const last = text.lastIndexOf('}')
2467
- if (first !== -1 && last > first) {
2468
- const sliced = tryParseJsonRobust(text.slice(first, last + 1))
2469
- if (sliced) return sliced
2470
- }
2471
- return null
2472
- }
2473
-
2474
- const activeChiefWorkMap = new Map()
2475
- const ACTIVE_CHIEF_WORK_TTL_MS = 90_000
2476
-
2477
- export function beginChiefActiveWork(rootSessionId, spec = {}) {
2478
- const key = String(rootSessionId || 'global').trim() || 'global'
2479
- const id = 'cwork-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6)
2480
- activeChiefWorkMap.set(key, {
2481
- id,
2482
- tone: String(spec.tone || 'neon'),
2483
- tab: String(spec.tab || ''),
2484
- boundSubTab: String(spec.boundSubTab || ''),
2485
- label: String(spec.label || '参谋长正在自动维护中...'),
2486
- startedAt: Date.now(),
2487
- })
2488
- return id
2489
- }
2490
-
2491
- export function updateChiefActiveWork(rootSessionId, workId, patchSpec = {}) {
2492
- const key = String(rootSessionId || 'global').trim() || 'global'
2493
- const cur = activeChiefWorkMap.get(key)
2494
- if (!cur || (workId && cur.id !== workId)) return false
2495
- activeChiefWorkMap.set(key, {
2496
- ...cur,
2497
- ...(patchSpec.tone ? { tone: String(patchSpec.tone) } : {}),
2498
- ...(patchSpec.tab !== undefined ? { tab: String(patchSpec.tab || '') } : {}),
2499
- ...(patchSpec.boundSubTab !== undefined ? { boundSubTab: String(patchSpec.boundSubTab || '') } : {}),
2500
- ...(patchSpec.label ? { label: String(patchSpec.label) } : {}),
2501
- })
2502
- return true
2503
- }
2504
-
2505
- export function endChiefActiveWork(rootSessionId, workId = '') {
2506
- const key = String(rootSessionId || 'global').trim() || 'global'
2507
- const cur = activeChiefWorkMap.get(key)
2508
- if (!cur) return false
2509
- if (workId && cur.id !== workId) return false
2510
- activeChiefWorkMap.delete(key)
2511
- return true
2512
- }
2513
-
2514
- export function getChiefActiveWork(rootSessionId) {
2515
- const key = String(rootSessionId || 'global').trim() || 'global'
2516
- const cur = activeChiefWorkMap.get(key)
2517
- if (!cur) return null
2518
- if (Date.now() - Number(cur.startedAt || 0) > ACTIVE_CHIEF_WORK_TTL_MS) {
2519
- activeChiefWorkMap.delete(key)
2520
- return null
2521
- }
2522
- return { ...cur }
2523
- }
1
+ /**
2
+ * chief-state.js — 参谋全局持久化状态读写锁、集群协同与运行配置主控模块
3
+ *
4
+ * 【核心职责】
5
+ * 1. 管理单例 `cachedState`、跨进程排他锁(`acquireStateLock` + `try...finally { release() }`)、
6
+ * `mtimeMs` 缓存失效及 `renameSync` 原子落盘。
7
+ * 2. 管理工作区配置变更(`updateChiefConfig`)、审批/提权/账本入队、集群联通(`setPeerLink`)、
8
+ * 跨会话部署(`deployChiefWorkspaceState`)、托管预算熔断及水泡结构锁(`setBubbleManualLock`)。
9
+ * 3. Re-export `state-schema.js` 与 `state-media.js` 全部原对外契约,保持 `chief.js` 67 个导出零变化。
10
+ */
11
+
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import os from 'node:os'
15
+ import { threadId } from 'node:worker_threads'
16
+ import {
17
+ resolveProjectKey,
18
+ loadArchiveStore,
19
+ loadGlobalVaultRaw,
20
+ getChiefMountedGlobalForSession,
21
+ getTakenOutGlobalForSession,
22
+ collectSealedWatchSummary,
23
+ getFlippedOutPrecipitatedForSession,
24
+ } from './archives.js'
25
+ import {
26
+ DEFAULT_CHIEF_PERMISSION_MODE,
27
+ CHIEF_PERMISSION_META,
28
+ normalizePermissionMode,
29
+ permissionRank,
30
+ auditJsonlPath as safetyAuditJsonlPath,
31
+ appendAuditJsonlRecord,
32
+ validatePolicyPluginList,
33
+ } from './safety/index.js'
34
+ import {
35
+ APPROVALS_CAP,
36
+ AUDIT_LOG_CAP,
37
+ TASK_LEDGER_CAP,
38
+ DEFAULT_RESUME_TTL_MS,
39
+ FACTS_CAP,
40
+ FACT_TEXT_MAX,
41
+ CHAT_CAP,
42
+ MAIL_CAP,
43
+ CHIEF_RUN_MODES,
44
+ DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
45
+ LLM_LEDGER_RECENT_CAP,
46
+ DEFAULT_MANAGED_BUDGET_MAX_CALLS,
47
+ DEFAULT_MANAGED_BUDGET_MAX_TOKENS,
48
+ CHIEF_SCENARIO_PRESETS,
49
+ normalizeUiLang,
50
+ normalizeManagedBudgetCalls,
51
+ normalizeManagedBudgetTokens,
52
+ classifyChiefLlmCategory,
53
+ LLM_LEDGER_CALLS_MAX,
54
+ LLM_LEDGER_TOKENS_MAX,
55
+ emptyLlmLedger,
56
+ normalizeLlmLedger,
57
+ summarizeLlmLedger,
58
+ pushAlertEventToWs,
59
+ normalizeRunMode,
60
+ normalizeThinkingEffort,
61
+ normalizeTeamEffortMode,
62
+ nextId,
63
+ clamp,
64
+ cleanMultiline,
65
+ secretLike,
66
+ computeApprovalPayloadHash,
67
+ hasValidChiefRiskAck,
68
+ normalizePendingApproval,
69
+ normalizePendingElevation,
70
+ normalizeTaskLedgerEntry,
71
+ recoverTaskLedgerEntriesOnDiskLoad,
72
+ normalizeAuditEntry,
73
+ emptyWorkspace,
74
+ normalizeFact,
75
+ normalizeInquiryItem,
76
+ normalizeMail,
77
+ COMPACT_PCT_WARN_FLOOR,
78
+ COMPACT_TOKEN_HARD_MIN,
79
+ COMPACT_TOKEN_WARN_FLOOR,
80
+ formatCompactTokenShort,
81
+ parseCompactTokensInput,
82
+ resolveWorkspaceConfig,
83
+ isChiefSessionEnabled,
84
+ normalizeTacticalModes,
85
+ normalizeState,
86
+ normalizeBubbleHarness,
87
+ markTaskResumingActive,
88
+ unmarkTaskResumingActive,
89
+ SUGGESTIONS_CAP,
90
+ MODEL_TIMEOUT_MS,
91
+ CATALOG_TTL_MS,
92
+ REVIEW_DELAY_MS,
93
+ AUTO_SUMMARY_COOLDOWN_MS,
94
+ SMART_REVIEW_COOLDOWN_MS,
95
+ AUTO_REVIEW_COOLDOWN_MS,
96
+ SUMMARY_MAX_TOKENS,
97
+ SUMMARY_RETRY_MAX_TOKENS,
98
+ CHIEF_UPDATE_SOURCE,
99
+ CHIEF_RELAY_SOURCE,
100
+ CHIEF_INQUIRY_SOURCE,
101
+ CHIEF_EXEC_REQ_SOURCE,
102
+ CHAT_OPPORTUNISTIC_SUMMARY_COOLDOWN_MS,
103
+ CHIEF_THINKING_EFFORTS,
104
+ ALERT_EVENTS_CAP,
105
+ CHIEF_UI_LANGS,
106
+ normalizeAlertEvent,
107
+ normalizeLockedModelEfforts,
108
+ resolveAlignedModelEffort,
109
+ normalizeSuggestion,
110
+ COMPACT_THRESHOLD_MIN_PCT,
111
+ COMPACT_THRESHOLD_MAX_PCT,
112
+ shortAgentBriefName,
113
+ stripCheckpointNoise,
114
+ isInternalCheckpointNoise,
115
+ extractJsonObject,
116
+ beginChiefActiveWork,
117
+ updateChiefActiveWork,
118
+ endChiefActiveWork,
119
+ getChiefActiveWork,
120
+ OFFICIAL_HARNESS_CATALOG,
121
+ } from './state-schema.js'
122
+ import {
123
+ archiveTargetForRoot,
124
+ resolveSessionWorkspaceCwd,
125
+ persistChiefImagesToWorkspace,
126
+ admitChiefImages,
127
+ } from './state-media.js'
128
+
129
+ export {
130
+ markTaskResumingActive,
131
+ unmarkTaskResumingActive,
132
+ FACTS_CAP,
133
+ FACT_TEXT_MAX,
134
+ CHAT_CAP,
135
+ MAIL_CAP,
136
+ SUGGESTIONS_CAP,
137
+ MODEL_TIMEOUT_MS,
138
+ CATALOG_TTL_MS,
139
+ REVIEW_DELAY_MS,
140
+ AUTO_SUMMARY_COOLDOWN_MS,
141
+ SMART_REVIEW_COOLDOWN_MS,
142
+ AUTO_REVIEW_COOLDOWN_MS,
143
+ SUMMARY_MAX_TOKENS,
144
+ SUMMARY_RETRY_MAX_TOKENS,
145
+ CHIEF_UPDATE_SOURCE,
146
+ CHIEF_RELAY_SOURCE,
147
+ CHIEF_INQUIRY_SOURCE,
148
+ CHIEF_EXEC_REQ_SOURCE,
149
+ CHAT_OPPORTUNISTIC_SUMMARY_COOLDOWN_MS,
150
+ CHIEF_RUN_MODES,
151
+ DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
152
+ CHIEF_THINKING_EFFORTS,
153
+ ALERT_EVENTS_CAP,
154
+ LLM_LEDGER_RECENT_CAP,
155
+ DEFAULT_MANAGED_BUDGET_MAX_CALLS,
156
+ DEFAULT_MANAGED_BUDGET_MAX_TOKENS,
157
+ CHIEF_UI_LANGS,
158
+ CHIEF_SCENARIO_PRESETS,
159
+ normalizeUiLang,
160
+ normalizeManagedBudgetCalls,
161
+ normalizeManagedBudgetTokens,
162
+ classifyChiefLlmCategory,
163
+ emptyLlmLedger,
164
+ normalizeLlmLedger,
165
+ summarizeLlmLedger,
166
+ normalizeAlertEvent,
167
+ pushAlertEventToWs,
168
+ normalizeRunMode,
169
+ normalizeThinkingEffort,
170
+ normalizeLockedModelEfforts,
171
+ resolveAlignedModelEffort,
172
+ nextId,
173
+ clamp,
174
+ cleanMultiline,
175
+ secretLike,
176
+ computeApprovalPayloadHash,
177
+ hasValidChiefRiskAck,
178
+ recoverTaskLedgerEntriesOnDiskLoad,
179
+ normalizeFact,
180
+ normalizeSuggestion,
181
+ normalizeInquiryItem,
182
+ normalizeMail,
183
+ COMPACT_THRESHOLD_MIN_PCT,
184
+ COMPACT_THRESHOLD_MAX_PCT,
185
+ COMPACT_PCT_WARN_FLOOR,
186
+ COMPACT_TOKEN_HARD_MIN,
187
+ COMPACT_TOKEN_WARN_FLOOR,
188
+ formatCompactTokenShort,
189
+ parseCompactTokensInput,
190
+ resolveWorkspaceConfig,
191
+ isChiefSessionEnabled,
192
+ emptyWorkspace,
193
+ normalizeTacticalModes,
194
+ shortAgentBriefName,
195
+ stripCheckpointNoise,
196
+ isInternalCheckpointNoise,
197
+ extractJsonObject,
198
+ beginChiefActiveWork,
199
+ updateChiefActiveWork,
200
+ endChiefActiveWork,
201
+ getChiefActiveWork,
202
+ OFFICIAL_HARNESS_CATALOG,
203
+ normalizeBubbleHarness,
204
+ }
205
+ export {
206
+ resolveSessionWorkspaceCwd,
207
+ archiveTargetForRoot,
208
+ persistChiefImagesToWorkspace,
209
+ admitChiefImages,
210
+ }
211
+
212
+ export function touchWorkspaceActivity(sessionId) {
213
+ const sid = String(sessionId || '').trim()
214
+ if (!sid || sid === 'global') return false
215
+ try {
216
+ if (!isChiefSessionEnabled(loadChiefState(), sid)) return false
217
+ mutateChiefState((state) => {
218
+ const ws = ensureWorkspace(state, sid)
219
+ if (!ws.runtimeGuard || typeof ws.runtimeGuard !== 'object') ws.runtimeGuard = {}
220
+ ws.runtimeGuard.lastActivityAt = Date.now()
221
+ })
222
+ return true
223
+ } catch {
224
+ return false
225
+ }
226
+ }
227
+
228
+ export function activateChiefSession(sessionId, { force = false } = {}) {
229
+ const sid = String(sessionId || '').trim()
230
+ if (!sid || sid === 'global') return false
231
+ try {
232
+ const st0 = loadChiefState()
233
+ const explicit = st0 && st0.workspaces && st0.workspaces[sid] && st0.workspaces[sid].config
234
+ ? st0.workspaces[sid].config.sessionEnabled
235
+ : undefined
236
+ if (explicit === true) return true
237
+ if (!force && explicit === false) return false
238
+ mutateChiefState((state) => {
239
+ const effBefore = resolveWorkspaceConfig(state, sid)
240
+ const ws = ensureWorkspace(state, sid)
241
+ if (!ws.config || typeof ws.config !== 'object') {
242
+ ws.config = {
243
+ modelRef: effBefore.modelRef || '',
244
+ paceMode: effBefore.paceMode || 'manual',
245
+ runMode: effBefore.runMode || 'off',
246
+ thinkingEffort: effBefore.thinkingEffort || 'auto',
247
+ teamEffortMode: effBefore.teamEffortMode || 'auto',
248
+ managedIdleTimeoutMs: effBefore.managedIdleTimeoutMs || DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
249
+ notifyEnabled: effBefore.notifyEnabled !== false,
250
+ notifySound: Boolean(effBefore.notifySound),
251
+ uiLang: effBefore.uiLang || 'auto',
252
+ managedBudgetMaxCalls: effBefore.managedBudgetMaxCalls ?? DEFAULT_MANAGED_BUDGET_MAX_CALLS,
253
+ managedBudgetMaxTokens: effBefore.managedBudgetMaxTokens ?? DEFAULT_MANAGED_BUDGET_MAX_TOKENS,
254
+ lockedModelEfforts: { ...(effBefore.lockedModelEfforts || {}) },
255
+ permissionMode: effBefore.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
256
+ tacticalModes: { ...effBefore.tacticalModes },
257
+ sessionEnabled: true,
258
+ }
259
+ } else {
260
+ ws.config.sessionEnabled = true
261
+ }
262
+ })
263
+ return true
264
+ } catch {
265
+ return false
266
+ }
267
+ }
268
+
269
+
270
+ export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null) {
271
+ const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
272
+ const sessionTarget = sid ? archiveTargetForRoot(deps, sid, { vaultScope: 'session' }) : null
273
+ const globalTarget = archiveTargetForRoot(deps, sid || 'global', { vaultScope: 'global' })
274
+ const baseOpt = sessionTarget || globalTarget
275
+ const projectKey = resolveProjectKey(baseOpt.cwd)
276
+
277
+ let deskSessionItems = []
278
+ let deskGlobalItems = []
279
+ let deskFlippedItems = []
280
+ let mountedGlobalItems = []
281
+ let sessionItems = []
282
+ let recentlyUnpinnedWatch = []
283
+ let globalHookIndex = []
284
+ let sealedWatch = { sessionSealed: [], globalSealed: [], precipSealed: [] }
285
+
286
+ try {
287
+ if (sessionTarget) {
288
+ const stSess = loadArchiveStore(sessionTarget)
289
+ const allSess = Array.isArray(stSess.items) ? stSess.items : []
290
+ deskSessionItems = allSess.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).slice(0, 6)
291
+ sessionItems = allSess.slice(0, 16).map(it => ({
292
+ id: it.id,
293
+ title: it.title,
294
+ folder: it.folder,
295
+ summary: it.summary,
296
+ paperclip: it.paperclip,
297
+ hasHook: Boolean(it.hasHook),
298
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
299
+ hookCue: it.hookCue || '',
300
+ takenOut: Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid),
301
+ points: Array.isArray(it.points) ? it.points.slice(0, 3) : [],
302
+ }))
303
+ recentlyUnpinnedWatch = Array.isArray(stSess.recentlyUnpinnedWatch) ? stSess.recentlyUnpinnedWatch.slice() : []
304
+ }
305
+ } catch {}
306
+ try {
307
+ const gStore = loadGlobalVaultRaw(globalTarget)
308
+ const gAll = Array.isArray(gStore && gStore.items) ? gStore.items : []
309
+ if (sid) {
310
+ deskGlobalItems = getTakenOutGlobalForSession(sid, globalTarget).slice(0, 6)
311
+ mountedGlobalItems = getChiefMountedGlobalForSession(sid, globalTarget).slice(0, 6)
312
+ // Also include entries Chief pulled in this session
313
+ const pulledSet = new Set(mountedGlobalItems.map(x => x.id))
314
+ for (const g of gAll) {
315
+ if (g && Array.isArray(g.chiefPulledSessions) && g.chiefPulledSessions.includes(sid) && !pulledSet.has(g.id)) {
316
+ mountedGlobalItems.push(g)
317
+ pulledSet.add(g.id)
318
+ if (mountedGlobalItems.length >= 6) break
319
+ }
320
+ }
321
+ }
322
+ globalHookIndex = gAll
323
+ .filter(it =>
324
+ it
325
+ && it.hasHook === true
326
+ && (!sid || (!Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid)))
327
+ && (!sid || (!Array.isArray(it.chiefMountedSessions) || !it.chiefMountedSessions.includes(sid)))
328
+ && (!sid || (!Array.isArray(it.chiefPulledSessions) || !it.chiefPulledSessions.includes(sid)))
329
+ )
330
+ .slice(0, 12)
331
+ .map(it => ({
332
+ id: it.id,
333
+ title: it.title,
334
+ folder: it.folder,
335
+ paperclip: it.paperclip,
336
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
337
+ hookCue: it.hookCue || '',
338
+ }))
339
+ } catch {}
340
+ try {
341
+ if (sid) {
342
+ const st = stateSnapshot || loadChiefState()
343
+ const ws = st && st.workspaces && st.workspaces[sid]
344
+ const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
345
+ if (flippedIds.length > 0) {
346
+ deskFlippedItems = getFlippedOutPrecipitatedForSession(projectKey, sid, true, baseOpt).slice(0, 6)
347
+ }
348
+ }
349
+ } catch {}
350
+ try {
351
+ sealedWatch = collectSealedWatchSummary(sid, projectKey, baseOpt, { limitPerVault: 8 })
352
+ } catch {}
353
+
354
+ return {
355
+ deskSessionItems,
356
+ deskGlobalItems,
357
+ deskFlippedItems,
358
+ mountedGlobalItems,
359
+ sessionItems,
360
+ recentlyUnpinnedWatch,
361
+ globalHookIndex,
362
+ sealedWatch,
363
+ sessionTarget,
364
+ globalTarget,
365
+ }
366
+ }
367
+
368
+ /** Persist raw uploaded images onto local workspace `.dsh-chief/uploads/` so any agent can inspect raw files even when LLM vision is unavailable. */
369
+
370
+ function chiefDir() {
371
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
372
+ return path.join(home, 'chief')
373
+ }
374
+
375
+ function stateFilePath() {
376
+ return path.join(chiefDir(), 'chief-state.json')
377
+ }
378
+
379
+ export function auditJsonlPath() {
380
+ return safetyAuditJsonlPath()
381
+ }
382
+
383
+ export function pushAuditToWs(ws, entry = {}, sessionId = '') {
384
+ if (!ws || typeof ws !== 'object') return null
385
+ if (!Array.isArray(ws.auditLog)) ws.auditLog = []
386
+ const norm = normalizeAuditEntry(entry)
387
+ if (!norm) return null
388
+ ws.auditLog.push(norm)
389
+ if (ws.auditLog.length > AUDIT_LOG_CAP) ws.auditLog = ws.auditLog.slice(-AUDIT_LOG_CAP)
390
+ appendAuditJsonlRecord(norm, sessionId)
391
+ return norm
392
+ }
393
+
394
+ export function appendChiefAuditLog(sessionId = 'global', entry = {}) {
395
+ const rootId = String(sessionId || 'global').trim() || 'global'
396
+ return mutateChiefState((state) => {
397
+ const ws = ensureWorkspace(state, rootId)
398
+ return pushAuditToWs(ws, entry, rootId)
399
+ })
400
+ }
401
+
402
+ export function enqueueApprovalToWs(ws, item = {}) {
403
+ if (!ws || typeof ws !== 'object') return null
404
+ if (!Array.isArray(ws.pendingApprovals)) ws.pendingApprovals = []
405
+ const dKey = clamp(item.dedupeKey || '', 120)
406
+ if (dKey) {
407
+ const existing = ws.pendingApprovals.find(a => a && a.status === 'pending' && a.dedupeKey === dKey)
408
+ if (existing) return existing
409
+ }
410
+ const kind = item.kind || 'tool'
411
+ const payload = item.payload && typeof item.payload === 'object' ? item.payload : {}
412
+ const now = Date.now()
413
+ const norm = normalizePendingApproval({
414
+ ...item,
415
+ status: 'pending',
416
+ dedupeKey: dKey,
417
+ payloadHash: computeApprovalPayloadHash(kind, payload),
418
+ expiresAt: Number(item.expiresAt) || (now + DEFAULT_RESUME_TTL_MS),
419
+ })
420
+ if (!norm) return null
421
+ ws.pendingApprovals.push(norm)
422
+ if (ws.pendingApprovals.length > APPROVALS_CAP) {
423
+ ws.pendingApprovals = ws.pendingApprovals.slice(-APPROVALS_CAP)
424
+ }
425
+ pushAlertEventToWs(ws, {
426
+ kind: 'pending_approval',
427
+ level: 'warn',
428
+ title: '🔐 等待人类逐项审批',
429
+ body: clamp(`${norm.operationLabel}${norm.targetLabel ? ' · ' + norm.targetLabel : ''}`, 180),
430
+ dedupeKey: 'apr:' + norm.id,
431
+ at: now,
432
+ })
433
+ return norm
434
+ }
435
+
436
+ export function queueChiefApproval(sessionId = 'global', item = {}) {
437
+ const rootId = String(sessionId || 'global').trim() || 'global'
438
+ return mutateChiefState((state) => {
439
+ const ws = ensureWorkspace(state, rootId)
440
+ return enqueueApprovalToWs(ws, item)
441
+ })
442
+ }
443
+
444
+ export function enqueueElevationToWs(ws, req = {}) {
445
+ if (!ws || typeof ws !== 'object') return null
446
+ const currentMode = normalizePermissionMode(
447
+ ws.config && ws.config.permissionMode ? ws.config.permissionMode : DEFAULT_CHIEF_PERMISSION_MODE,
448
+ { requireAck: true, hasChiefRiskAck: hasValidChiefRiskAck(ws) },
449
+ )
450
+ const targetMode = normalizePermissionMode(req.targetMode || 'strategist')
451
+ if (permissionRank(targetMode) <= permissionRank(currentMode)) return null
452
+ const now = Date.now()
453
+ const norm = normalizePendingElevation({
454
+ fromMode: currentMode,
455
+ targetMode,
456
+ reason: req.reason || 'Agent 申请提升权限以继续当前任务',
457
+ requestedActionSummary: req.requestedActionSummary || '',
458
+ resumeTaskId: req.resumeTaskId || '',
459
+ expiresAt: Number(req.expiresAt) || (now + DEFAULT_RESUME_TTL_MS),
460
+ by: req.by || 'chief',
461
+ })
462
+ if (!norm) return null
463
+ ws.pendingElevation = norm
464
+ pushAuditToWs(ws, {
465
+ mode: currentMode,
466
+ stage: 'permission_gate',
467
+ decision: 'elevation_requested',
468
+ operation: '申请提权',
469
+ target: `${CHIEF_PERMISSION_META[currentMode].level} -> ${CHIEF_PERMISSION_META[targetMode].level}`,
470
+ reason: norm.reason,
471
+ outcome: 'pending',
472
+ by: norm.by,
473
+ }, req.sessionId || '')
474
+ pushAlertEventToWs(ws, {
475
+ kind: 'pending_elevation',
476
+ level: 'warn',
477
+ title: '⬆️ 参谋申请提权',
478
+ body: clamp(`${CHIEF_PERMISSION_META[currentMode].level} -> ${CHIEF_PERMISSION_META[targetMode].level}:${norm.reason}`, 180),
479
+ dedupeKey: 'elv:' + norm.id,
480
+ at: now,
481
+ })
482
+ return norm
483
+ }
484
+
485
+ export function requestChiefElevation(sessionId = 'global', req = {}) {
486
+ const rootId = String(sessionId || 'global').trim() || 'global'
487
+ return mutateChiefState((state) => {
488
+ const ws = ensureWorkspace(state, rootId)
489
+ return enqueueElevationToWs(ws, { ...(req && typeof req === 'object' ? req : {}), sessionId: rootId })
490
+ })
491
+ }
492
+
493
+ export function upsertTaskLedgerOnWs(ws, rawTask = {}) {
494
+ if (!ws || typeof ws !== 'object') return null
495
+ if (!Array.isArray(ws.taskLedger)) {
496
+ ws.taskLedger = Array.isArray(ws.resumeTasks) ? ws.resumeTasks : []
497
+ }
498
+ ws.resumeTasks = ws.taskLedger
499
+ const lookupId = rawTask.taskId || rawTask.id
500
+ const existingIdx = lookupId ? ws.taskLedger.findIndex(t => t && (t.taskId === lookupId || t.id === lookupId)) : -1
501
+ if (existingIdx >= 0) {
502
+ const prev = ws.taskLedger[existingIdx]
503
+ const merged = normalizeTaskLedgerEntry({
504
+ ...prev,
505
+ ...rawTask,
506
+ updatedAt: Date.now(),
507
+ completedActions: rawTask.appendCompletedAction
508
+ ? [...(prev.completedActions || []), rawTask.appendCompletedAction]
509
+ : (rawTask.completedActions || prev.completedActions),
510
+ pendingApprovalIds: rawTask.pendingApprovalIds || prev.pendingApprovalIds,
511
+ })
512
+ if (merged) ws.taskLedger[existingIdx] = merged
513
+ return merged
514
+ }
515
+ const created = normalizeTaskLedgerEntry(rawTask)
516
+ if (!created) return null
517
+ ws.taskLedger.push(created)
518
+ if (ws.taskLedger.length > TASK_LEDGER_CAP) {
519
+ ws.taskLedger = ws.taskLedger.slice(-TASK_LEDGER_CAP)
520
+ ws.resumeTasks = ws.taskLedger
521
+ }
522
+ return created
523
+ }
524
+
525
+ export function upsertResumeTaskOnWs(ws, rawTask = {}) {
526
+ return upsertTaskLedgerOnWs(ws, rawTask)
527
+ }
528
+
529
+ export function enqueueChiefInquiryOnWs(ws, raw = {}) {
530
+ if (!ws || typeof ws !== 'object') return null
531
+ if (!Array.isArray(ws.inquiries)) ws.inquiries = []
532
+ const norm = normalizeInquiryItem(raw)
533
+ if (!norm) return null
534
+ const dup = ws.inquiries.find(
535
+ q => q && (q.status === 'pending' || q.status === 'delivered') && q.question === norm.question && q.target === norm.target,
536
+ )
537
+ if (dup) return dup
538
+ ws.inquiries.push(norm)
539
+ if (ws.inquiries.length > 24) ws.inquiries = ws.inquiries.slice(-24)
540
+ return norm
541
+ }
542
+
543
+ export function answerChiefInquiry(sessionId = 'global', { inquiryId = '', answer = '', by = 'lead' } = {}) {
544
+ const rootId = String(sessionId || 'global').trim() || 'global'
545
+ const cleanAns = cleanMultiline(answer || '', 1200)
546
+ if (!cleanAns) return { ok: false, error: 'inquiry.reply 需要非空答复文本 (text)' }
547
+ return mutateChiefState((state) => {
548
+ const ws = ensureWorkspace(state, rootId)
549
+ if (!Array.isArray(ws.inquiries)) ws.inquiries = []
550
+ let idx = inquiryId
551
+ ? ws.inquiries.findIndex(q => q && (q.inquiryId === inquiryId || q.id === inquiryId))
552
+ : -1
553
+ if (idx < 0 && !inquiryId) {
554
+ for (let i = ws.inquiries.length - 1; i >= 0; i -= 1) {
555
+ if (ws.inquiries[i] && (ws.inquiries[i].status === 'pending' || ws.inquiries[i].status === 'delivered')) {
556
+ idx = i
557
+ break
558
+ }
559
+ }
560
+ }
561
+ if (idx < 0) return { ok: false, error: `未找到待回复问询:${inquiryId || '最近未答问询'}` }
562
+ const existing = ws.inquiries[idx]
563
+ if (!existing || existing.status === 'answered' || (existing.status !== 'pending' && existing.status !== 'delivered')) {
564
+ const prevId = (existing && existing.inquiryId) || inquiryId
565
+ const prevStatus = (existing && existing.status) || 'unknown'
566
+ pushAuditToWs(ws, {
567
+ mode: resolveWorkspaceConfig(state, rootId).permissionMode,
568
+ stage: 'inquiry_channel',
569
+ rule: 'inquiry_reply_replay_rejected',
570
+ decision: 'rejected',
571
+ operation: '拦截重复问询答复',
572
+ target: prevId,
573
+ reason: `问询 #${prevId} 已结案 (status=${prevStatus}),拒绝重放覆写`,
574
+ outcome: 'rejected',
575
+ by: clamp(by || 'lead', 40),
576
+ }, rootId)
577
+ return {
578
+ ok: false,
579
+ alreadyAnswered: true,
580
+ code: 'inquiry_already_answered',
581
+ error: `问询 #${prevId} 已回复结案,拒绝重复应答`,
582
+ inquiry: existing,
583
+ }
584
+ }
585
+ const now = Date.now()
586
+ const item = {
587
+ ...existing,
588
+ status: 'answered',
589
+ answer: cleanAns,
590
+ answeredBy: clamp(by || 'lead', 40),
591
+ answeredAt: now,
592
+ }
593
+ ws.inquiries[idx] = item
594
+ if (item.taskId) {
595
+ upsertTaskLedgerOnWs(ws, {
596
+ taskId: item.taskId,
597
+ kind: 'inquiry',
598
+ status: 'completed',
599
+ inquiryId: item.inquiryId,
600
+ lastReceipt: `已收到 ${item.answeredBy} 原路答复:${clamp(cleanAns, 120)}`,
601
+ resolvedAt: now,
602
+ })
603
+ }
604
+ ws.chat.push({
605
+ id: nextId('chat'),
606
+ role: 'chief',
607
+ kind: 'receipt',
608
+ text: `- 【⚡ 优先问询回执 #${item.inquiryId}】已收到 \`${item.answeredBy}\` 不中断原路回复:\n- 【问】${item.question}\n- 【答】${cleanAns}`,
609
+ actions: [`问询已回执 #${item.inquiryId}`],
610
+ at: now,
611
+ })
612
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
613
+ pushAuditToWs(ws, {
614
+ mode: resolveWorkspaceConfig(state, rootId).permissionMode,
615
+ stage: 'inquiry_channel',
616
+ rule: 'inquiry_reply',
617
+ decision: 'answered',
618
+ operation: '优先问询原路回复',
619
+ target: item.inquiryId,
620
+ reason: clamp(cleanAns, 140),
621
+ outcome: 'ok',
622
+ by: item.answeredBy,
623
+ }, rootId)
624
+ return { ok: true, inquiry: item }
625
+ })
626
+ }
627
+
628
+ const STATE_LOCK_WAIT_MS = 10000
629
+
630
+ const STATE_LOCK_STALE_MS = 15000
631
+
632
+ const STATE_LOCK_CONTENDED_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY'])
633
+
634
+ const heldStateLocks = new Set()
635
+
636
+ const stateLockSleeper = new Int32Array(new SharedArrayBuffer(4))
637
+
638
+ function sleepStateLockSync(ms) {
639
+ try {
640
+ Atomics.wait(stateLockSleeper, 0, 0, ms)
641
+ } catch {}
642
+ }
643
+
644
+ /** Cross-process O_EXCL lock around `chief-state.json` read-modify-write cycles (fixes red-team E1). */
645
+ function acquireStateLock(file = stateFilePath()) {
646
+ if (heldStateLocks.has(file)) return () => {}
647
+ const lock = file + '.lock'
648
+ try {
649
+ fs.mkdirSync(path.dirname(lock), { recursive: true })
650
+ } catch {}
651
+ const deadline = Date.now() + STATE_LOCK_WAIT_MS
652
+ for (;;) {
653
+ try {
654
+ const fd = fs.openSync(lock, 'wx')
655
+ try {
656
+ fs.writeSync(fd, `${process.pid}:${threadId}`)
657
+ } catch {}
658
+ fs.closeSync(fd)
659
+ heldStateLocks.add(file)
660
+ return () => {
661
+ heldStateLocks.delete(file)
662
+ try {
663
+ fs.unlinkSync(lock)
664
+ } catch {}
665
+ }
666
+ } catch (error) {
667
+ const code = error && error.code
668
+ if (code === 'ENOENT' && Date.now() < deadline) {
669
+ try {
670
+ fs.mkdirSync(path.dirname(lock), { recursive: true })
671
+ } catch {}
672
+ sleepStateLockSync(2)
673
+ continue
674
+ }
675
+ if (!error || !STATE_LOCK_CONTENDED_CODES.has(code)) {
676
+ heldStateLocks.add(file)
677
+ return () => heldStateLocks.delete(file)
678
+ }
679
+ if (Date.now() >= deadline) {
680
+ try {
681
+ fs.unlinkSync(lock)
682
+ } catch {}
683
+ heldStateLocks.add(file)
684
+ return () => heldStateLocks.delete(file)
685
+ }
686
+ if (code === 'EEXIST') {
687
+ try {
688
+ const stat = fs.statSync(lock)
689
+ if (Date.now() - stat.mtimeMs > STATE_LOCK_STALE_MS) {
690
+ fs.unlinkSync(lock)
691
+ continue
692
+ }
693
+ } catch {}
694
+ }
695
+ sleepStateLockSync(2 + Math.floor(Math.random() * 4))
696
+ }
697
+ }
698
+ }
699
+
700
+ export function withChiefStateLock(fn) {
701
+ const file = stateFilePath()
702
+ const release = acquireStateLock(file)
703
+ try {
704
+ return fn()
705
+ } finally {
706
+ release()
707
+ }
708
+ }
709
+
710
+ let cachedState = null
711
+
712
+ let cachedMtime = 0
713
+
714
+ function applyColdLoadLedgerRecovery(state) {
715
+ if (!state || !state.workspaces || typeof state.workspaces !== 'object') return false
716
+ let changed = false
717
+ const now = Date.now()
718
+ for (const ws of Object.values(state.workspaces)) {
719
+ if (!ws || !Array.isArray(ws.taskLedger) || ws.taskLedger.length === 0) continue
720
+ const beforeStatuses = ws.taskLedger.map(t => t && t.status)
721
+ const recovered = recoverTaskLedgerEntriesOnDiskLoad(ws.taskLedger, now)
722
+ ws.taskLedger = recovered
723
+ ws.resumeTasks = recovered
724
+ for (let i = 0; i < recovered.length; i += 1) {
725
+ if (recovered[i] && recovered[i].status !== beforeStatuses[i]) {
726
+ changed = true
727
+ }
728
+ }
729
+ }
730
+ return changed
731
+ }
732
+
733
+ export function loadChiefState({ forceDisk = false } = {}) {
734
+ const file = stateFilePath()
735
+ try {
736
+ const stat = fs.statSync(file)
737
+ if (!forceDisk && cachedState && stat.mtimeMs === cachedMtime) return cachedState
738
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
739
+ const nextState = normalizeState(parsed)
740
+ applyColdLoadLedgerRecovery(nextState)
741
+ cachedState = nextState
742
+ cachedMtime = stat.mtimeMs
743
+ return cachedState
744
+ } catch {
745
+ if (forceDisk) {
746
+ cachedState = normalizeState({})
747
+ cachedMtime = -1
748
+ return cachedState
749
+ }
750
+ if (!cachedState) cachedState = normalizeState({})
751
+ return cachedState
752
+ }
753
+ }
754
+
755
+ export function reconcileChiefStateOnBoot() {
756
+ return mutateChiefState((state) => applyColdLoadLedgerRecovery(state))
757
+ }
758
+
759
+ export function saveChiefState(state) {
760
+ const normalized = normalizeState(state)
761
+ const file = stateFilePath()
762
+ try {
763
+ fs.mkdirSync(path.dirname(file), { recursive: true })
764
+ const tmp = `${file}.${process.pid}.${threadId}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 6)}.tmp`
765
+ fs.writeFileSync(tmp, JSON.stringify(normalized, null, 2), 'utf8')
766
+ let renameErr = null
767
+ for (let attempt = 0; attempt < 8; attempt += 1) {
768
+ try {
769
+ fs.renameSync(tmp, file)
770
+ renameErr = null
771
+ break
772
+ } catch (err) {
773
+ renameErr = err
774
+ const code = err && err.code
775
+ if (code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') break
776
+ sleepStateLockSync(2 + attempt * 2)
777
+ }
778
+ }
779
+ if (renameErr) {
780
+ try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp) } catch {}
781
+ throw renameErr
782
+ }
783
+ try {
784
+ cachedMtime = fs.statSync(file).mtimeMs
785
+ } catch {
786
+ cachedMtime = -1
787
+ }
788
+ } catch {}
789
+ cachedState = normalized
790
+ return normalized
791
+ }
792
+
793
+ export function mutateChiefState(mutator) {
794
+ return withChiefStateLock(() => {
795
+ const state = loadChiefState({ forceDisk: true })
796
+ const result = mutator(state)
797
+ saveChiefState(state)
798
+ return result
799
+ })
800
+ }
801
+
802
+ /** Find connected component of linked root sessions (undirected graph). */
803
+ export function getLinkedCluster(state, rootSessionId) {
804
+ const seed = String(rootSessionId || '').trim()
805
+ if (!seed) return ['global']
806
+ const visited = new Set([seed])
807
+ const queue = [seed]
808
+ const links = (state && state.links) || {}
809
+ while (queue.length > 0) {
810
+ const cur = queue.shift()
811
+ const direct = Array.isArray(links[cur]) ? links[cur] : []
812
+ for (const peer of direct) {
813
+ if (peer && !visited.has(peer)) {
814
+ visited.add(peer)
815
+ queue.push(peer)
816
+ }
817
+ }
818
+ for (const [other, list] of Object.entries(links)) {
819
+ if (Array.isArray(list) && list.includes(cur) && !visited.has(other)) {
820
+ visited.add(other)
821
+ queue.push(other)
822
+ }
823
+ }
824
+ }
825
+ return [...visited].sort()
826
+ }
827
+
828
+ export function computeClusterSig(cluster = []) {
829
+ return [...new Set((Array.isArray(cluster) ? cluster : []).map(x => String(x || '').trim()).filter(Boolean))].sort().join('|')
830
+ }
831
+
832
+ export function setPeerLink(rootA, rootB, linked) {
833
+ const a = String(rootA || '').trim()
834
+ const b = String(rootB || '').trim()
835
+ if (!a || !b || a === b) return { ok: false, error: '需要两个不同的主会话才能建立协同连接' }
836
+ return mutateChiefState((state) => {
837
+ const affected = new Set([
838
+ ...getLinkedCluster(state, a),
839
+ ...getLinkedCluster(state, b),
840
+ ])
841
+ const setA = new Set(state.links[a] || [])
842
+ const setB = new Set(state.links[b] || [])
843
+ if (linked) {
844
+ setA.add(b)
845
+ setB.add(a)
846
+ } else {
847
+ setA.delete(b)
848
+ setB.delete(a)
849
+ }
850
+ if (setA.size) state.links[a] = [...setA]
851
+ else delete state.links[a]
852
+ if (setB.size) state.links[b] = [...setB]
853
+ else delete state.links[b]
854
+
855
+ // Topology isolation guard: purge stale narrative caches on EVERY affected session whose cluster changed
856
+ // so detaching from a peer cluster NEVER leaves residual peer context inside Chief's narrative digest!
857
+ const now = Date.now()
858
+ for (const sid of affected) {
859
+ const ws = ensureWorkspace(state, sid)
860
+ const nextCluster = getLinkedCluster(state, sid)
861
+ const nextSig = computeClusterSig(nextCluster)
862
+ if (!ws.narrative || ws.narrative.clusterSig !== nextSig) {
863
+ ws.narrative = { hash: '', text: '', at: 0, byModel: '', clusterSig: nextSig }
864
+ }
865
+ if (!linked) {
866
+ ws.seenFactsAt = { [sid]: now }
867
+ } else {
868
+ ws.seenFactsAt = {}
869
+ }
870
+ }
871
+ return { ok: true, cluster: getLinkedCluster(state, a) }
872
+ })
873
+ }
874
+
875
+ export function ensureWorkspace(state, rootId) {
876
+ const key = String(rootId || 'global').trim() || 'global'
877
+ if (!state.workspaces[key]) state.workspaces[key] = emptyWorkspace()
878
+ return state.workspaces[key]
879
+ }
880
+
881
+ function filterFactsForCluster(rawFacts, clusterSet, rootId) {
882
+ return (Array.isArray(rawFacts) ? rawFacts : []).filter((f) => {
883
+ if (!f || !f.text) return false
884
+ if (f.originRootId && !clusterSet.has(f.originRootId)) return false
885
+ if (f.category === 'team' && Array.isArray(f.peerRootIds) && f.peerRootIds.length > 0) {
886
+ // A team fact created during multi-session collaboration stays ONLY if another participant besides rootId remains linked
887
+ const participants = f.originRootId ? [f.originRootId, ...f.peerRootIds] : f.peerRootIds
888
+ const peerStillLinked = participants.some(pid => pid && pid !== rootId && clusterSet.has(pid))
889
+ if (!peerStillLinked) return false
890
+ }
891
+ return true
892
+ })
893
+ }
894
+
895
+ function annotateMailClusterState(mail, clusterSet) {
896
+ if (!mail || typeof mail !== 'object') return mail
897
+ const isHarnessRoot = id => typeof id === 'string' && id.startsWith('harness:')
898
+ const fromOut = Boolean(mail.fromRootId && !isHarnessRoot(mail.fromRootId) && !clusterSet.has(mail.fromRootId))
899
+ const toOut = Boolean(mail.toRootId && mail.toRootId !== 'all' && !isHarnessRoot(mail.toRootId) && !clusterSet.has(mail.toRootId))
900
+ const detachedFromCluster = fromOut || toOut
901
+ return detachedFromCluster ? { ...mail, detachedFromCluster: true } : mail
902
+ }
903
+
904
+ /** Merge facts & mailbox across all linked peer sessions in the federation cluster, isolating detached artifacts. */
905
+ export function clusterView(state, rootId) {
906
+ const cluster = getLinkedCluster(state, rootId)
907
+ const clusterSig = computeClusterSig(cluster)
908
+ const clusterSet = new Set(cluster)
909
+ const primary = ensureWorkspace(state, rootId)
910
+ if (cluster.length <= 1) {
911
+ return {
912
+ cluster,
913
+ clusterSig,
914
+ primary,
915
+ facts: filterFactsForCluster(primary.facts, clusterSet, rootId),
916
+ mailbox: (primary.mailbox || []).map(m => annotateMailClusterState(m, clusterSet)),
917
+ suggestions: primary.suggestions.filter(s => s.status === 'pending'),
918
+ chat: primary.chat,
919
+ narrative: primary.narrative,
920
+ }
921
+ }
922
+ const factMap = new Map()
923
+ const mailMap = new Map()
924
+ for (const sid of cluster) {
925
+ const ws = ensureWorkspace(state, sid)
926
+ for (const f of filterFactsForCluster(ws.facts, clusterSet, rootId)) factMap.set(f.id, f)
927
+ for (const m of ws.mailbox) {
928
+ if (m && m.broadcastId && m.channelType === 'broadcast') {
929
+ mailMap.set('bcast:' + m.broadcastId, annotateMailClusterState(m, clusterSet))
930
+ } else {
931
+ mailMap.set(m.id, annotateMailClusterState(m, clusterSet))
932
+ }
933
+ }
934
+ }
935
+ const facts = [...factMap.values()].sort((a, b) => (a.addedAt || 0) - (b.addedAt || 0)).slice(-FACTS_CAP)
936
+ const mailbox = [...mailMap.values()].sort((a, b) => (a.at || 0) - (b.at || 0)).slice(-MAIL_CAP)
937
+ return {
938
+ cluster,
939
+ clusterSig,
940
+ primary,
941
+ facts,
942
+ mailbox,
943
+ suggestions: primary.suggestions.filter(s => s.status === 'pending'),
944
+ chat: primary.chat,
945
+ narrative: primary.narrative,
946
+ }
947
+ }
948
+
949
+ /* -------------------------------------------------------------------------- */
950
+ /* Model Catalog & Auxiliary LLM Caller */
951
+ /* -------------------------------------------------------------------------- */
952
+
953
+ /** Manage which cold precipitated-vault entries are explicitly unsealed/flipped into a single root session. */
954
+ export function updateWorkspaceFlippedIds(sessionId, { flippedId = '', sealId = '', clearAll = false } = {}) {
955
+ const key = String(sessionId || 'global').trim() || 'global'
956
+ return mutateChiefState((state) => {
957
+ const ws = ensureWorkspace(state, key)
958
+ const set = new Set(ws.flippedPrecipitatedIds || [])
959
+ if (clearAll) {
960
+ set.clear()
961
+ } else {
962
+ if (flippedId) set.add(String(flippedId).trim())
963
+ if (sealId) set.delete(String(sealId).trim())
964
+ }
965
+ ws.flippedPrecipitatedIds = [...set].slice(-20)
966
+ return { ok: true, flippedPrecipitatedIds: ws.flippedPrecipitatedIds.slice() }
967
+ })
968
+ }
969
+
970
+ /** One-click system deployment of Chief state (`facts`, `narrative`, `chat`/`mailbox` bridge) to a target Chief workspace (strictly keeping `flippedPrecipitatedIds = []`). */
971
+ export function deployChiefWorkspaceState(deps, {
972
+ fromRootId = '',
973
+ toRootId = '',
974
+ fromTitle = '',
975
+ customText = '',
976
+ objective = '',
977
+ } = {}) {
978
+ const fromKey = String(fromRootId || 'global').trim() || 'global'
979
+ const toKey = String(toRootId || '').trim()
980
+ if (!toKey) return { ok: false, error: '目标会话 ID 不能为空' }
981
+
982
+ return mutateChiefState((state) => {
983
+ const fromWs = ensureWorkspace(state, fromKey)
984
+ const toWs = ensureWorkspace(state, toKey)
985
+
986
+ const existingTexts = new Set(toWs.facts.map(f => f.text.trim()))
987
+ let copiedFacts = 0
988
+ for (const f of fromWs.facts) {
989
+ if (!f || !f.text) continue
990
+ const norm = f.text.trim()
991
+ if (existingTexts.has(norm)) continue
992
+ existingTexts.add(norm)
993
+ toWs.facts.push({
994
+ ...f,
995
+ id: nextId('fact'),
996
+ originRootId: toKey === 'global' ? (f.originRootId || '') : toKey,
997
+ peerRootIds: [],
998
+ source: f.source || `移交自 ${fromTitle || fromKey}`,
999
+ updatedAt: Date.now(),
1000
+ })
1001
+ copiedFacts += 1
1002
+ }
1003
+ if (toWs.facts.length > FACTS_CAP) {
1004
+ const pinned = toWs.facts.filter(f => f.pinned)
1005
+ const rest = toWs.facts.filter(f => !f.pinned).slice(-(FACTS_CAP - pinned.length))
1006
+ toWs.facts = [...pinned, ...rest].slice(-FACTS_CAP)
1007
+ }
1008
+
1009
+ if (fromWs.narrative && fromWs.narrative.text && !toWs.narrative.text) {
1010
+ toWs.narrative = {
1011
+ ...fromWs.narrative,
1012
+ hash: fromWs.narrative.hash || '',
1013
+ clusterSig: toKey,
1014
+ at: Date.now(),
1015
+ }
1016
+ }
1017
+
1018
+ const briefLines = [
1019
+ `- 【跨会话接力部署】本会话参谋状态已自 **${fromTitle || fromKey}** 系统级一键移交部署完成(新对话默认以 **L0 · 顾问模式** 安全启动)。`,
1020
+ objective ? `- 【继承总目标】${clamp(objective, 180)}` : '',
1021
+ copiedFacts > 0 ? `- 【继承纪律与事实】共继承 **${copiedFacts} 条**核心记忆与纪律。` : '',
1022
+ customText ? `- 【附带交接叮嘱】${clamp(customText, 240)}` : '',
1023
+ ].filter(Boolean).join('\n')
1024
+
1025
+ const mailItem = normalizeMail({
1026
+ id: nextId('mail'),
1027
+ from: 'DSH 参谋长 (接力部署)',
1028
+ fromSession: fromKey,
1029
+ to: 'lead',
1030
+ toSession: toKey,
1031
+ subject: `跨会话参谋部署:自 ${fromTitle || fromKey}`,
1032
+ text: briefLines,
1033
+ mode: 'silent',
1034
+ deliveredPhysical: false,
1035
+ at: Date.now(),
1036
+ })
1037
+ if (mailItem) {
1038
+ toWs.mailbox.push(mailItem)
1039
+ if (toWs.mailbox.length > MAIL_CAP) toWs.mailbox = toWs.mailbox.slice(-MAIL_CAP)
1040
+ }
1041
+
1042
+ toWs.chat.push({
1043
+ id: nextId('chat'),
1044
+ role: 'chief',
1045
+ text: briefLines,
1046
+ actions: ['系统接力部署', '默认 L0 顾问', ...(copiedFacts > 0 ? [`继承记忆 ×${copiedFacts}`] : [])],
1047
+ at: Date.now(),
1048
+ })
1049
+ if (toWs.chat.length > CHAT_CAP) toWs.chat = toWs.chat.slice(-CHAT_CAP)
1050
+
1051
+ // Clone safe workspace chief config (model, effort, tactical preferences), ALWAYS forcing intervention=false, runMode='off' & L0 advisor!
1052
+ const fromCfg = resolveWorkspaceConfig(state, fromKey)
1053
+ toWs.config = {
1054
+ modelRef: fromCfg.modelRef || '',
1055
+ paceMode: 'manual',
1056
+ runMode: 'off',
1057
+ thinkingEffort: fromCfg.thinkingEffort || 'auto',
1058
+ teamEffortMode: fromCfg.teamEffortMode || 'auto',
1059
+ managedIdleTimeoutMs: fromCfg.managedIdleTimeoutMs || DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
1060
+ permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
1061
+ autoPilot: false,
1062
+ autoReview: false,
1063
+ tacticalModes: {
1064
+ ...normalizeTacticalModes(fromCfg.tacticalModes),
1065
+ intervention: false,
1066
+ },
1067
+ }
1068
+ toWs.chiefRiskAck = null
1069
+ toWs.pendingApprovals = []
1070
+ toWs.pendingElevation = null
1071
+ pushAuditToWs(toWs, {
1072
+ mode: DEFAULT_CHIEF_PERMISSION_MODE,
1073
+ stage: 'deploy',
1074
+ decision: 'reset_to_l0',
1075
+ operation: '跨会话接力部署',
1076
+ target: toKey,
1077
+ reason: '新对话强制从最低档 L0 顾问模式安全启动并清空高权限状态',
1078
+ outcome: 'ok',
1079
+ by: 'deploy',
1080
+ })
1081
+ toWs.runtimeGuard.interventionTurns = 0
1082
+ toWs.runtimeGuard.unchangedCount = 0
1083
+ toWs.runtimeGuard.circuitBroken = false
1084
+ toWs.runtimeGuard.circuitReason = ''
1085
+
1086
+ // Strictly keep precipitated cold vault isolated at 0-token default in destination session!
1087
+ toWs.flippedPrecipitatedIds = []
1088
+
1089
+ return {
1090
+ ok: true,
1091
+ copiedFacts,
1092
+ narrativeCopied: Boolean(fromWs.narrative && fromWs.narrative.text),
1093
+ flippedPrecipitatedIds: [],
1094
+ config: { ...toWs.config, tacticalModes: { ...toWs.config.tacticalModes } },
1095
+ }
1096
+ })
1097
+ }
1098
+
1099
+ /* -------------------------------------------------------------------------- */
1100
+ /* Chief Command Bar: All-Seeing Strategist + Relay + Bounds + Board Ops */
1101
+ /* -------------------------------------------------------------------------- */
1102
+
1103
+ export function updateChiefConfig(patch) {
1104
+ const rawInput = patch && typeof patch === 'object' ? patch : {}
1105
+ const rawPreset = typeof rawInput.preset === 'string' ? rawInput.preset.trim().toLowerCase() : ''
1106
+ const presetSpec = CHIEF_SCENARIO_PRESETS[rawPreset] || null
1107
+ const safePatch = presetSpec
1108
+ ? {
1109
+ ...presetSpec,
1110
+ ...rawInput,
1111
+ tacticalModes: {
1112
+ ...(presetSpec.tacticalModes || {}),
1113
+ ...(rawInput.tacticalModes && typeof rawInput.tacticalModes === 'object' ? rawInput.tacticalModes : {}),
1114
+ },
1115
+ }
1116
+ : rawInput
1117
+ const sid = String(safePatch.sessionId || safePatch.session || '').trim() || 'global'
1118
+ const GLOBAL_ONLY_CFG_KEYS = new Set(['defaultAutoEnableSessions', 'uiLang', 'notifyEnabled', 'notifySound'])
1119
+ const META_CFG_KEYS = new Set([
1120
+ 'sessionId',
1121
+ 'session',
1122
+ 'by',
1123
+ 'byUser',
1124
+ '_fromUiPanel',
1125
+ 'confirmedDisableSafetyGuard',
1126
+ 'safetyGuardScope',
1127
+ ])
1128
+ const payloadKeys = Object.keys(safePatch).filter(k => !META_CFG_KEYS.has(k) && safePatch[k] !== undefined)
1129
+ const callerBy = typeof safePatch.by === 'string' ? safePatch.by.trim() : ''
1130
+ const isHumanBy = !callerBy || /^(?:user|human|operator|ui_panel)$/i.test(callerBy)
1131
+ const isHumanLockCaller = safePatch._fromUiPanel === true
1132
+ || (safePatch.byUser === true && isHumanBy)
1133
+
1134
+ const incomingTacticalRaw = safePatch.tacticalModes && typeof safePatch.tacticalModes === 'object'
1135
+ ? safePatch.tacticalModes
1136
+ : null
1137
+ const wantsGlobalSafetyToggle = typeof safePatch.globalSafetyGuardEnabled === 'boolean'
1138
+ || Boolean(incomingTacticalRaw && typeof incomingTacticalRaw.safetyGuardEnabled === 'boolean' && (sid === 'global' || safePatch.safetyGuardScope === 'global'))
1139
+ const targetGlobalSafetyVal = typeof safePatch.globalSafetyGuardEnabled === 'boolean'
1140
+ ? safePatch.globalSafetyGuardEnabled
1141
+ : (wantsGlobalSafetyToggle ? Boolean(incomingTacticalRaw.safetyGuardEnabled) : undefined)
1142
+ const wantsSessionSafetyToggle = !wantsGlobalSafetyToggle
1143
+ && Boolean(incomingTacticalRaw && typeof incomingTacticalRaw.safetyGuardEnabled === 'boolean')
1144
+ const targetSessionSafetyVal = wantsSessionSafetyToggle
1145
+ ? Boolean(incomingTacticalRaw.safetyGuardEnabled)
1146
+ : undefined
1147
+ const wantsDisableSafety = targetGlobalSafetyVal === false || targetSessionSafetyVal === false
1148
+
1149
+ const isGlobalSafetyOnly = payloadKeys.length > 0 && payloadKeys.every(k =>
1150
+ k === 'globalSafetyGuardEnabled'
1151
+ || (k === 'tacticalModes' && wantsGlobalSafetyToggle && Object.keys(incomingTacticalRaw || {}).length === 1),
1152
+ )
1153
+ const isGlobalPrefOnly = payloadKeys.length > 0 && payloadKeys.every(k => GLOBAL_ONLY_CFG_KEYS.has(k))
1154
+ const isDefaultAutoOnly = payloadKeys.length === 1 && payloadKeys[0] === 'defaultAutoEnableSessions'
1155
+ return mutateChiefState((state) => {
1156
+ const existingWs = state.workspaces && state.workspaces[sid] ? state.workspaces[sid] : null
1157
+ const effBeforeCheck = resolveWorkspaceConfig(state, sid)
1158
+ if (wantsGlobalSafetyToggle || wantsSessionSafetyToggle) {
1159
+ if (!isHumanLockCaller) {
1160
+ const blockEntry = {
1161
+ mode: effBeforeCheck.permissionMode,
1162
+ stage: 'safety_guard_toggle',
1163
+ rule: 'safety_guard_human_only',
1164
+ decision: 'blocked',
1165
+ operation: wantsGlobalSafetyToggle ? '修改全局安全卫兵开关' : '修改会话安全卫兵开关',
1166
+ target: wantsGlobalSafetyToggle ? 'global' : sid,
1167
+ reason: `未授权来源 (${callerBy || 'unknown'}) 试图修改安全卫兵开关,仅允许人类通过设置面板显式操作`,
1168
+ outcome: 'rejected',
1169
+ by: clamp(callerBy || 'unknown', 40),
1170
+ }
1171
+ if (existingWs) pushAuditToWs(existingWs, blockEntry, sid)
1172
+ else {
1173
+ const normBlock = normalizeAuditEntry(blockEntry)
1174
+ if (normBlock) appendAuditJsonlRecord(normBlock, sid)
1175
+ }
1176
+ return {
1177
+ ok: false,
1178
+ blocked: true,
1179
+ code: 'safety_guard_human_only',
1180
+ error: '安全卫兵开关仅允许人类通过设置面板显式操作,已拦截非人类来源修改',
1181
+ }
1182
+ }
1183
+ if (wantsDisableSafety && safePatch.confirmedDisableSafetyGuard !== true) {
1184
+ return {
1185
+ ok: false,
1186
+ requireSafetyGuardConfirm: true,
1187
+ scope: targetGlobalSafetyVal === false ? 'global' : 'session',
1188
+ error: '关闭安全卫兵需先在风险确认弹窗中勾选确认(confirmedDisableSafetyGuard: true)',
1189
+ }
1190
+ }
1191
+ }
1192
+ if (isGlobalSafetyOnly) {
1193
+ const nextGlobalVal = Boolean(targetGlobalSafetyVal)
1194
+ state.config.tacticalModes = {
1195
+ ...normalizeTacticalModes(state.config.tacticalModes),
1196
+ safetyGuardEnabled: nextGlobalVal,
1197
+ }
1198
+ const toggleEntry = {
1199
+ mode: effBeforeCheck.permissionMode,
1200
+ stage: 'safety_guard_toggle',
1201
+ rule: 'safety_guard_toggled',
1202
+ decision: nextGlobalVal ? 'executed' : 'disabled',
1203
+ operation: '切换全局安全卫兵总开关',
1204
+ target: 'global',
1205
+ reason: nextGlobalVal ? '人类显式开启全局安全卫兵总开关' : '人类确认风险后关闭全局安全卫兵总开关',
1206
+ outcome: 'ok',
1207
+ by: clamp(callerBy || 'operator', 40),
1208
+ }
1209
+ if (existingWs) pushAuditToWs(existingWs, toggleEntry, sid)
1210
+ else {
1211
+ const normToggle = normalizeAuditEntry(toggleEntry)
1212
+ if (normToggle) appendAuditJsonlRecord(normToggle, sid)
1213
+ }
1214
+ const nextCfg = resolveWorkspaceConfig(state, sid)
1215
+ return {
1216
+ ok: true,
1217
+ config: { ...nextCfg, tacticalModes: { ...nextCfg.tacticalModes } },
1218
+ llmLedger: summarizeLlmLedger(existingWs && existingWs.llmLedger, nextCfg),
1219
+ }
1220
+ }
1221
+ if (isDefaultAutoOnly || (isGlobalPrefOnly && !(existingWs && existingWs.config))) {
1222
+ if (typeof safePatch.defaultAutoEnableSessions === 'boolean') {
1223
+ state.config.defaultAutoEnableSessions = safePatch.defaultAutoEnableSessions
1224
+ }
1225
+ if (typeof safePatch.uiLang === 'string') {
1226
+ state.config.uiLang = normalizeUiLang(safePatch.uiLang)
1227
+ }
1228
+ if (typeof safePatch.notifyEnabled === 'boolean') {
1229
+ state.config.notifyEnabled = safePatch.notifyEnabled
1230
+ }
1231
+ if (typeof safePatch.notifySound === 'boolean') {
1232
+ state.config.notifySound = safePatch.notifySound
1233
+ }
1234
+ const nextCfg = resolveWorkspaceConfig(state, sid)
1235
+ return {
1236
+ ok: true,
1237
+ config: { ...nextCfg, tacticalModes: { ...nextCfg.tacticalModes } },
1238
+ llmLedger: summarizeLlmLedger(existingWs && existingWs.llmLedger, nextCfg),
1239
+ }
1240
+ }
1241
+ const ws = ensureWorkspace(state, sid)
1242
+ const effBefore = resolveWorkspaceConfig(state, sid)
1243
+ const prevTactical = normalizeTacticalModes(effBefore.tacticalModes)
1244
+ if (typeof safePatch.ackHazardAlertId === 'string' && safePatch.ackHazardAlertId.trim()) {
1245
+ const ackId = safePatch.ackHazardAlertId.trim()
1246
+ if (ws && ws.runtimeGuard && ws.runtimeGuard.hazardAlert && (ackId === '*' || ws.runtimeGuard.hazardAlert.id === ackId)) {
1247
+ ws.runtimeGuard.hazardAlert = null
1248
+ }
1249
+ const hasOtherKeys = Object.keys(safePatch).some(
1250
+ k => k !== 'sessionId' && k !== 'session' && k !== 'ackHazardAlertId',
1251
+ )
1252
+ if (!hasOtherKeys) {
1253
+ const curCfg = resolveWorkspaceConfig(state, sid)
1254
+ return {
1255
+ ok: true,
1256
+ clearedHazardAlert: true,
1257
+ config: { ...curCfg, tacticalModes: { ...curCfg.tacticalModes } },
1258
+ runtimeGuard: ws ? { ...ws.runtimeGuard } : null,
1259
+ }
1260
+ }
1261
+ }
1262
+
1263
+ if (safePatch.emergencyStopIntervention === true) {
1264
+ if (ws) {
1265
+ if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effBefore }
1266
+ ws.config.tacticalModes = { ...normalizeTacticalModes(ws.config.tacticalModes), intervention: false }
1267
+ ws.runtimeGuard.interventionTurns = 0
1268
+ ws.runtimeGuard.unchangedCount = 0
1269
+ ws.runtimeGuard.circuitBroken = false
1270
+ ws.runtimeGuard.circuitReason = ''
1271
+ ws.runtimeGuard.hazardAlert = null
1272
+ }
1273
+ state.config.tacticalModes = { ...normalizeTacticalModes(state.config.tacticalModes), intervention: false }
1274
+ const stoppedCfg = resolveWorkspaceConfig(state, sid)
1275
+ return {
1276
+ ok: true,
1277
+ emergencyStopped: true,
1278
+ config: { ...stoppedCfg, tacticalModes: { ...stoppedCfg.tacticalModes } },
1279
+ runtimeGuard: ws ? { ...ws.runtimeGuard } : null,
1280
+ }
1281
+ }
1282
+
1283
+ // Hard gate on model thinking effort lock mutations (human UI / explicit byUser only)
1284
+ const wantsLockMutation = safePatch.lockedModelEfforts !== undefined
1285
+ || safePatch.toggleLockAgentEffort !== undefined
1286
+ || safePatch.teamEffortMode !== undefined
1287
+ if (wantsLockMutation && !isHumanLockCaller) {
1288
+ pushAuditToWs(ws, {
1289
+ mode: effBefore.permissionMode,
1290
+ stage: 'model_effort_lock',
1291
+ rule: 'effort_lock_human_only',
1292
+ decision: 'blocked',
1293
+ operation: '修改模型思考强度锁挡',
1294
+ target: sid,
1295
+ reason: `未授权来源 (${callerBy || 'unknown'}) 试图修改 lockedModelEfforts,仅允许人类面板显式操作`,
1296
+ outcome: 'rejected',
1297
+ by: clamp(callerBy || 'unknown', 40),
1298
+ }, sid)
1299
+ return {
1300
+ ok: false,
1301
+ blocked: true,
1302
+ lockedByUser: true,
1303
+ code: 'effort_lock_human_only',
1304
+ error: '思考强度锁挡 (lockedModelEfforts) 仅允许人类通过面板或显式 byUser 授权修改,已拦截越权变更',
1305
+ }
1306
+ }
1307
+ if (
1308
+ typeof safePatch.thinkingEffort === 'string'
1309
+ && effBefore.lockedModelEfforts
1310
+ && effBefore.lockedModelEfforts.chief === true
1311
+ && !isHumanLockCaller
1312
+ ) {
1313
+ pushAuditToWs(ws, {
1314
+ mode: effBefore.permissionMode,
1315
+ stage: 'model_effort_lock',
1316
+ rule: 'effort_lock_human_only',
1317
+ decision: 'blocked',
1318
+ operation: '修改参谋长思考强度',
1319
+ target: sid,
1320
+ reason: `参谋长思考强度已被用户锁定 (lockedModelEfforts.chief),拒绝非人类来源 (${callerBy || 'unknown'}) 修改`,
1321
+ outcome: 'rejected',
1322
+ by: clamp(callerBy || 'unknown', 40),
1323
+ }, sid)
1324
+ return {
1325
+ ok: false,
1326
+ blocked: true,
1327
+ lockedByUser: true,
1328
+ code: 'effort_lock_human_only',
1329
+ error: '参谋长思考强度已被用户锁定 (lockedModelEfforts.chief),仅允许人类显式修改',
1330
+ }
1331
+ }
1332
+
1333
+ // Check explicit Policy Plugin list (restrict-only) BEFORE applying any changes
1334
+ let validatedPlugins = null
1335
+ if (safePatch.policyPlugins !== undefined) {
1336
+ const plugCheck = validatePolicyPluginList(safePatch.policyPlugins)
1337
+ if (!plugCheck.ok) {
1338
+ pushAuditToWs(ws, {
1339
+ mode: effBefore.permissionMode,
1340
+ stage: 'policy_plugin',
1341
+ rule: plugCheck.code || 'policy_plugin_rejected',
1342
+ decision: 'rejected',
1343
+ operation: '配置只紧不松策略插件',
1344
+ target: sid,
1345
+ reason: plugCheck.error,
1346
+ outcome: 'rejected',
1347
+ by: clamp(safePatch.by || 'operator', 40),
1348
+ }, sid)
1349
+ return {
1350
+ ok: false,
1351
+ code: plugCheck.code || 'POLICY_PLUGIN_WEAKENING_FORBIDDEN',
1352
+ error: plugCheck.error,
1353
+ }
1354
+ }
1355
+ validatedPlugins = plugCheck.plugins
1356
+ }
1357
+
1358
+ // Check explicit permission mode transition BEFORE applying any changes
1359
+ let normalizedReqPerm = ''
1360
+ if (typeof safePatch.permissionMode === 'string' && safePatch.permissionMode.trim()) {
1361
+ normalizedReqPerm = normalizePermissionMode(safePatch.permissionMode)
1362
+ if (normalizedReqPerm === 'chief' && safePatch.confirmedChiefRisk !== true && !hasValidChiefRiskAck(ws)) {
1363
+ pushAuditToWs(ws, {
1364
+ mode: effBefore.permissionMode,
1365
+ stage: 'permission_gate',
1366
+ decision: 'deny_unacknowledged_l3',
1367
+ operation: '切换 L3 参谋长模式',
1368
+ target: sid,
1369
+ reason: '未阅读并勾选确认高权限风险告知(confirmedChiefRisk: true)',
1370
+ outcome: 'denied',
1371
+ by: 'operator',
1372
+ })
1373
+ return {
1374
+ ok: false,
1375
+ requireChiefRiskConfirm: true,
1376
+ error: '启用「L3 · 参谋长模式」前必须阅读高权限风险告知并主动勾选确认(confirmedChiefRisk: true)',
1377
+ }
1378
+ }
1379
+ }
1380
+
1381
+ let incomingTactical = incomingTacticalRaw ? { ...incomingTacticalRaw } : null
1382
+ if (incomingTactical && incomingTactical.intervention === true && !prevTactical.intervention) {
1383
+ if (safePatch.confirmedInterventionRisk !== true) {
1384
+ return {
1385
+ ok: false,
1386
+ error: '开启「接管督导模式」需先确认双项风险免责声明(confirmedInterventionRisk: true)',
1387
+ }
1388
+ }
1389
+ if (ws) {
1390
+ ws.runtimeGuard.interventionTurns = 0
1391
+ ws.runtimeGuard.unchangedCount = 0
1392
+ ws.runtimeGuard.circuitBroken = false
1393
+ ws.runtimeGuard.circuitReason = ''
1394
+ ws.runtimeGuard.hazardAlert = null
1395
+ ws.runtimeGuard.lastGoalAchievedSig = ''
1396
+ }
1397
+ }
1398
+
1399
+ const wantsUnlimitedTurns = Boolean(
1400
+ incomingTactical
1401
+ && (incomingTactical.maxInterventionTurns === 0 || incomingTactical.maxInterventionTurns === '0')
1402
+ )
1403
+ if (wantsUnlimitedTurns && prevTactical.maxInterventionTurns !== 0 && safePatch.confirmedUnlimitedTurns !== true) {
1404
+ return {
1405
+ ok: false,
1406
+ error: '切换至「♾️ 无限督导轮次」需先通过作者风险确认弹窗(confirmedUnlimitedTurns: true)',
1407
+ }
1408
+ }
1409
+
1410
+ const wantsAutoPilot = Boolean(
1411
+ safePatch.runMode === 'managed'
1412
+ || safePatch.paceMode === 'auto'
1413
+ || (typeof safePatch.paceMode !== 'string' && typeof safePatch.runMode !== 'string' && safePatch.stopped !== true && safePatch.autoPilot === true)
1414
+ )
1415
+ if (wantsAutoPilot && effBefore.runMode !== 'managed' && effBefore.paceMode !== 'auto' && safePatch.confirmedAutoPilot !== true) {
1416
+ return {
1417
+ ok: false,
1418
+ requireAutoPilotConfirm: true,
1419
+ error: '开启「🤖 托管模式」需先确认本会话自治范围与 5 条件自动休眠保护(confirmedAutoPilot: true)',
1420
+ }
1421
+ }
1422
+ if (ws && wantsAutoPilot && (effBefore.runMode !== 'managed' || effBefore.paceMode !== 'auto')) {
1423
+ const now = Date.now()
1424
+ ws.runtimeGuard.autoPilotStartedAt = now
1425
+ ws.runtimeGuard.managedStartedAt = now
1426
+ ws.runtimeGuard.lastActivityAt = now
1427
+ ws.runtimeGuard.autoPilotHadTurn = false
1428
+ ws.llmLedger = normalizeLlmLedger(ws.llmLedger)
1429
+ ws.llmLedger.managedRun = {
1430
+ startedAt: now,
1431
+ calls: 0,
1432
+ tokens: 0,
1433
+ tripped: false,
1434
+ trippedAt: 0,
1435
+ trippedReason: '',
1436
+ }
1437
+ }
1438
+ if (ws && !wantsAutoPilot && safePatch.runMode === 'patrol' && ws.llmLedger && ws.llmLedger.managedRun && ws.llmLedger.managedRun.tripped) {
1439
+ ws.llmLedger.managedRun.tripped = false
1440
+ ws.llmLedger.managedRun.trippedAt = 0
1441
+ ws.llmLedger.managedRun.trippedReason = ''
1442
+ }
1443
+ if (ws && safePatch.resetManagedBudget === true) {
1444
+ ws.llmLedger = normalizeLlmLedger(ws.llmLedger)
1445
+ ws.llmLedger.managedRun = {
1446
+ startedAt: Date.now(),
1447
+ calls: 0,
1448
+ tokens: 0,
1449
+ tripped: false,
1450
+ trippedAt: 0,
1451
+ trippedReason: '',
1452
+ }
1453
+ }
1454
+ if (ws && safePatch.resetLlmLedger === true) {
1455
+ ws.llmLedger = emptyLlmLedger()
1456
+ }
1457
+
1458
+ let compactLowWarning = ''
1459
+ if (incomingTactical && typeof incomingTactical.compactThresholdInput === 'string') {
1460
+ const parsedTok = parseCompactTokensInput(incomingTactical.compactThresholdInput)
1461
+ if (!parsedTok.ok) {
1462
+ return { ok: false, error: parsedTok.error }
1463
+ }
1464
+ incomingTactical.compactThresholdTokens = parsedTok.tokens
1465
+ incomingTactical.compactThresholdInput = parsedTok.displayInput
1466
+ compactLowWarning = parsedTok.lowWarning || ''
1467
+ } else if (incomingTactical && typeof incomingTactical.compactThresholdTokens === 'number') {
1468
+ const safeTok = Math.max(COMPACT_TOKEN_HARD_MIN, Math.round(incomingTactical.compactThresholdTokens))
1469
+ incomingTactical.compactThresholdTokens = safeTok
1470
+ incomingTactical.compactThresholdInput = formatCompactTokenShort(safeTok)
1471
+ if (safeTok < COMPACT_TOKEN_WARN_FLOOR) {
1472
+ compactLowWarning = `当前阈值(${incomingTactical.compactThresholdInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
1473
+ }
1474
+ }
1475
+
1476
+ const applyPatchTo = (targetCfg, allowIntervention, allowAutoPilot = allowIntervention, allowPermSync = false, allowLocks = false, allowSafetyGuardToggle = false) => {
1477
+ if (typeof safePatch.modelRef === 'string') targetCfg.modelRef = safePatch.modelRef.trim()
1478
+ if (typeof safePatch.thinkingEffort === 'string') {
1479
+ targetCfg.thinkingEffort = normalizeThinkingEffort(safePatch.thinkingEffort)
1480
+ }
1481
+ if (allowLocks && typeof safePatch.teamEffortMode === 'string') {
1482
+ targetCfg.teamEffortMode = normalizeTeamEffortMode(safePatch.teamEffortMode)
1483
+ }
1484
+ if (Number.isFinite(Number(safePatch.managedIdleTimeoutMs)) && Number(safePatch.managedIdleTimeoutMs) >= 50) {
1485
+ targetCfg.managedIdleTimeoutMs = Math.min(2 * 60 * 60 * 1000, Math.round(Number(safePatch.managedIdleTimeoutMs)))
1486
+ }
1487
+ if (typeof safePatch.notifyEnabled === 'boolean') targetCfg.notifyEnabled = safePatch.notifyEnabled
1488
+ if (typeof safePatch.notifySound === 'boolean') targetCfg.notifySound = safePatch.notifySound
1489
+ if (typeof safePatch.uiLang === 'string') targetCfg.uiLang = normalizeUiLang(safePatch.uiLang)
1490
+ if (safePatch.managedBudgetMaxCalls !== undefined) {
1491
+ targetCfg.managedBudgetMaxCalls = normalizeManagedBudgetCalls(safePatch.managedBudgetMaxCalls)
1492
+ }
1493
+ if (safePatch.managedBudgetMaxTokens !== undefined) {
1494
+ targetCfg.managedBudgetMaxTokens = normalizeManagedBudgetTokens(safePatch.managedBudgetMaxTokens)
1495
+ }
1496
+ if (allowLocks && (
1497
+ (safePatch.lockedModelEfforts && typeof safePatch.lockedModelEfforts === 'object')
1498
+ || (safePatch.toggleLockAgentEffort && typeof safePatch.toggleLockAgentEffort === 'object')
1499
+ )) {
1500
+ const curLocks = { ...(targetCfg.lockedModelEfforts || {}) }
1501
+ if (safePatch.lockedModelEfforts && typeof safePatch.lockedModelEfforts === 'object') {
1502
+ for (const [lk, lv] of Object.entries(safePatch.lockedModelEfforts)) {
1503
+ const ck = String(lk || '').trim().slice(0, 64)
1504
+ if (!ck) continue
1505
+ if (lv === true) curLocks[ck] = true
1506
+ else delete curLocks[ck]
1507
+ }
1508
+ }
1509
+ if (safePatch.toggleLockAgentEffort && typeof safePatch.toggleLockAgentEffort === 'object') {
1510
+ const lk = String(safePatch.toggleLockAgentEffort.target || 'lead').trim().slice(0, 64)
1511
+ if (lk) {
1512
+ if (safePatch.toggleLockAgentEffort.locked === true) curLocks[lk] = true
1513
+ else delete curLocks[lk]
1514
+ }
1515
+ }
1516
+ targetCfg.lockedModelEfforts = curLocks
1517
+ }
1518
+ if (allowPermSync && normalizedReqPerm) {
1519
+ targetCfg.permissionMode = normalizedReqPerm
1520
+ }
1521
+ if (typeof safePatch.runMode === 'string' && CHIEF_RUN_MODES.includes(safePatch.runMode)) {
1522
+ const nextRun = (!allowAutoPilot && safePatch.runMode === 'managed') ? 'off' : safePatch.runMode
1523
+ targetCfg.runMode = nextRun
1524
+ targetCfg.stopped = false
1525
+ targetCfg.paceMode = nextRun === 'managed' ? 'auto' : (nextRun === 'patrol' ? 'smart' : 'manual')
1526
+ targetCfg.autoPilot = nextRun === 'managed' && allowAutoPilot
1527
+ targetCfg.autoReview = nextRun === 'managed' && allowAutoPilot
1528
+ } else if (typeof safePatch.paceMode === 'string' && ['manual', 'smart', 'auto', 'stopped'].includes(safePatch.paceMode)) {
1529
+ const nextPace = (!allowAutoPilot && safePatch.paceMode === 'auto') ? 'manual' : safePatch.paceMode
1530
+ targetCfg.paceMode = nextPace
1531
+ const isStopped = nextPace === 'stopped'
1532
+ targetCfg.stopped = isStopped
1533
+ targetCfg.runMode = isStopped ? 'off' : (nextPace === 'auto' ? 'managed' : (nextPace === 'smart' ? 'patrol' : 'off'))
1534
+ targetCfg.autoPilot = !isStopped && nextPace === 'auto' && allowAutoPilot
1535
+ targetCfg.autoReview = !isStopped && nextPace === 'auto' && allowAutoPilot
1536
+ } else if (typeof safePatch.stopped === 'boolean') {
1537
+ targetCfg.stopped = safePatch.stopped
1538
+ if (safePatch.stopped) {
1539
+ targetCfg.paceMode = 'stopped'
1540
+ targetCfg.runMode = 'off'
1541
+ targetCfg.autoPilot = false
1542
+ targetCfg.autoReview = false
1543
+ } else {
1544
+ if (targetCfg.paceMode === 'stopped') targetCfg.paceMode = 'manual'
1545
+ if (!allowAutoPilot && targetCfg.paceMode === 'auto') targetCfg.paceMode = 'manual'
1546
+ targetCfg.runMode = normalizeRunMode(targetCfg.runMode, targetCfg)
1547
+ targetCfg.autoPilot = targetCfg.paceMode === 'auto' && allowAutoPilot
1548
+ targetCfg.autoReview = targetCfg.paceMode === 'auto' && allowAutoPilot
1549
+ }
1550
+ } else if (typeof safePatch.autoPilot === 'boolean') {
1551
+ const nextAuto = Boolean(safePatch.autoPilot && allowAutoPilot)
1552
+ targetCfg.stopped = false
1553
+ targetCfg.paceMode = nextAuto ? 'auto' : 'manual'
1554
+ targetCfg.runMode = nextAuto ? 'managed' : 'off'
1555
+ targetCfg.autoPilot = nextAuto
1556
+ targetCfg.autoReview = nextAuto
1557
+ }
1558
+ if (!allowAutoPilot && (targetCfg.paceMode === 'auto' || targetCfg.runMode === 'managed')) {
1559
+ targetCfg.paceMode = 'manual'
1560
+ targetCfg.runMode = 'off'
1561
+ targetCfg.autoPilot = false
1562
+ targetCfg.autoReview = false
1563
+ }
1564
+ if (typeof safePatch.autoReview === 'boolean' && typeof safePatch.paceMode !== 'string' && typeof safePatch.runMode !== 'string' && typeof safePatch.stopped !== 'boolean') {
1565
+ targetCfg.autoReview = safePatch.autoReview
1566
+ if (!safePatch.autoReview) {
1567
+ targetCfg.stopped = false
1568
+ targetCfg.paceMode = 'manual'
1569
+ targetCfg.runMode = 'off'
1570
+ }
1571
+ }
1572
+ if (incomingTactical) {
1573
+ const prevTargetTactical = normalizeTacticalModes(targetCfg.tacticalModes)
1574
+ const merged = normalizeTacticalModes({
1575
+ ...prevTargetTactical,
1576
+ ...incomingTactical,
1577
+ })
1578
+ if (!allowIntervention) merged.intervention = false
1579
+ if (!allowSafetyGuardToggle) {
1580
+ merged.safetyGuardEnabled = prevTargetTactical.safetyGuardEnabled !== false
1581
+ }
1582
+ targetCfg.tacticalModes = merged
1583
+ } else if (!allowIntervention && targetCfg.tacticalModes) {
1584
+ targetCfg.tacticalModes = { ...normalizeTacticalModes(targetCfg.tacticalModes), intervention: false }
1585
+ }
1586
+ }
1587
+
1588
+ if (!ws.config || typeof ws.config !== 'object') {
1589
+ ws.config = {
1590
+ modelRef: effBefore.modelRef || '',
1591
+ paceMode: effBefore.paceMode || 'manual',
1592
+ runMode: effBefore.runMode || 'off',
1593
+ thinkingEffort: effBefore.thinkingEffort || 'auto',
1594
+ teamEffortMode: effBefore.teamEffortMode || 'auto',
1595
+ managedIdleTimeoutMs: effBefore.managedIdleTimeoutMs || DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
1596
+ notifyEnabled: effBefore.notifyEnabled !== false,
1597
+ notifySound: Boolean(effBefore.notifySound),
1598
+ uiLang: effBefore.uiLang || 'auto',
1599
+ managedBudgetMaxCalls: effBefore.managedBudgetMaxCalls ?? DEFAULT_MANAGED_BUDGET_MAX_CALLS,
1600
+ managedBudgetMaxTokens: effBefore.managedBudgetMaxTokens ?? DEFAULT_MANAGED_BUDGET_MAX_TOKENS,
1601
+ lockedModelEfforts: { ...(effBefore.lockedModelEfforts || {}) },
1602
+ permissionMode: effBefore.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
1603
+ tacticalModes: { ...effBefore.tacticalModes },
1604
+ }
1605
+ }
1606
+ applyPatchTo(ws.config, true, true, true, isHumanLockCaller, wantsSessionSafetyToggle)
1607
+ if (wantsGlobalSafetyToggle) {
1608
+ state.config.tacticalModes = {
1609
+ ...normalizeTacticalModes(state.config.tacticalModes),
1610
+ safetyGuardEnabled: Boolean(targetGlobalSafetyVal),
1611
+ }
1612
+ pushAuditToWs(ws, {
1613
+ mode: resolveWorkspaceConfig(state, sid).permissionMode,
1614
+ stage: 'safety_guard_toggle',
1615
+ rule: 'safety_guard_toggled',
1616
+ decision: targetGlobalSafetyVal ? 'executed' : 'disabled',
1617
+ operation: '切换全局安全卫兵总开关',
1618
+ target: 'global',
1619
+ reason: targetGlobalSafetyVal ? '人类显式开启全局安全卫兵总开关' : '人类确认风险后关闭全局安全卫兵总开关',
1620
+ outcome: 'ok',
1621
+ by: clamp(callerBy || 'operator', 40),
1622
+ }, sid)
1623
+ }
1624
+ if (wantsSessionSafetyToggle) {
1625
+ pushAuditToWs(ws, {
1626
+ mode: resolveWorkspaceConfig(state, sid).permissionMode,
1627
+ stage: 'safety_guard_toggle',
1628
+ rule: 'safety_guard_toggled',
1629
+ decision: targetSessionSafetyVal ? 'executed' : 'disabled',
1630
+ operation: '切换会话安全卫兵开关',
1631
+ target: sid,
1632
+ reason: targetSessionSafetyVal ? '人类显式开启本会话安全卫兵' : '人类确认风险后关闭本会话安全卫兵',
1633
+ outcome: 'ok',
1634
+ by: clamp(callerBy || 'operator', 40),
1635
+ }, sid)
1636
+ }
1637
+ if (typeof safePatch.defaultAutoEnableSessions === 'boolean') {
1638
+ state.config.defaultAutoEnableSessions = safePatch.defaultAutoEnableSessions
1639
+ }
1640
+ if (typeof safePatch.sessionEnabled === 'boolean') {
1641
+ ws.config.sessionEnabled = safePatch.sessionEnabled
1642
+ if (!safePatch.sessionEnabled) {
1643
+ ws.config.runMode = 'off'
1644
+ ws.config.paceMode = 'manual'
1645
+ ws.config.stopped = false
1646
+ ws.config.autoPilot = false
1647
+ ws.config.autoReview = false
1648
+ ws.config.tacticalModes = { ...normalizeTacticalModes(ws.config.tacticalModes), intervention: false }
1649
+ }
1650
+ } else if (!isGlobalPrefOnly && sid !== 'global') {
1651
+ ws.config.sessionEnabled = true
1652
+ }
1653
+ if (validatedPlugins !== null) {
1654
+ if (safePatch.policyPluginsScope === 'global') {
1655
+ state.config.policyPlugins = validatedPlugins
1656
+ } else {
1657
+ ws.config.policyPlugins = validatedPlugins
1658
+ }
1659
+ pushAuditToWs(ws, {
1660
+ mode: resolveWorkspaceConfig(state, sid).permissionMode,
1661
+ stage: 'policy_plugin',
1662
+ rule: 'policy_plugin_updated',
1663
+ decision: 'executed',
1664
+ operation: '更新安全策略插件',
1665
+ target: `${safePatch.policyPluginsScope === 'global' ? 'global' : sid} (${validatedPlugins.length} 个)`,
1666
+ reason: `已加载 ${validatedPlugins.length} 个只紧不松安全策略插件`,
1667
+ outcome: 'ok',
1668
+ by: clamp(safePatch.by || 'operator', 40),
1669
+ }, sid)
1670
+ }
1671
+ // Session permissionMode, intervention, lockedModelEfforts, and autoPilot NEVER leak globally across new sessions!
1672
+ state.config.permissionMode = DEFAULT_CHIEF_PERMISSION_MODE
1673
+ applyPatchTo(state.config, false, false, false, false)
1674
+
1675
+ if (normalizedReqPerm) {
1676
+ if (normalizedReqPerm === 'chief' && safePatch.confirmedChiefRisk === true) {
1677
+ ws.chiefRiskAck = {
1678
+ acknowledged: true,
1679
+ at: Date.now(),
1680
+ by: clamp(safePatch.by || 'operator', 40),
1681
+ version: '1.2.1',
1682
+ }
1683
+ } else if (normalizedReqPerm !== 'chief') {
1684
+ ws.chiefRiskAck = null
1685
+ }
1686
+ if (normalizedReqPerm !== effBefore.permissionMode) {
1687
+ if (ws.pendingElevation && permissionRank(normalizedReqPerm) >= permissionRank(ws.pendingElevation.targetMode)) {
1688
+ ws.pendingElevation = null
1689
+ }
1690
+ pushAuditToWs(ws, {
1691
+ mode: normalizedReqPerm,
1692
+ stage: 'permission_gate',
1693
+ decision: 'mode_changed',
1694
+ operation: '切换权限等级',
1695
+ target: `${CHIEF_PERMISSION_META[effBefore.permissionMode].level} -> ${CHIEF_PERMISSION_META[normalizedReqPerm].level}`,
1696
+ reason: normalizedReqPerm === 'chief' ? '用户勾选风险声明并确认启用 L3 参谋长模式' : `用户主动切换至 ${CHIEF_PERMISSION_META[normalizedReqPerm].title}`,
1697
+ outcome: 'ok',
1698
+ by: clamp(safePatch.by || 'operator', 40),
1699
+ })
1700
+ }
1701
+ }
1702
+
1703
+ const finalCfg = resolveWorkspaceConfig(state, sid)
1704
+ if (!compactLowWarning && finalCfg.tacticalModes.compactThresholdMode === 'tokens' && finalCfg.tacticalModes.compactThresholdTokens < COMPACT_TOKEN_WARN_FLOOR) {
1705
+ compactLowWarning = `当前阈值(${finalCfg.tacticalModes.compactThresholdInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
1706
+ } else if (!compactLowWarning && finalCfg.tacticalModes.compactThresholdMode !== 'tokens' && finalCfg.tacticalModes.compactThresholdPct < COMPACT_PCT_WARN_FLOOR) {
1707
+ compactLowWarning = `当前触发比例(${finalCfg.tacticalModes.compactThresholdPct}%)低于安全建议线 ${COMPACT_PCT_WARN_FLOOR}%,可能导致上下文频繁提前归档压缩`
1708
+ }
1709
+ return {
1710
+ ok: true,
1711
+ ...(presetSpec ? { appliedPreset: presetSpec.id } : {}),
1712
+ ...(compactLowWarning ? { compactLowWarning } : {}),
1713
+ config: { ...finalCfg, tacticalModes: { ...finalCfg.tacticalModes } },
1714
+ llmLedger: summarizeLlmLedger(ws.llmLedger, finalCfg),
1715
+ }
1716
+ })
1717
+ }
1718
+
1719
+ export function mutateChiefFact(deps, { sessionId, op, id, text, category, pinned }) {
1720
+ const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
1721
+ return mutateChiefState((state) => {
1722
+ const ws = ensureWorkspace(state, rootId)
1723
+ if (op === 'add') {
1724
+ const cat = category || 'discipline'
1725
+ const activeCluster = getLinkedCluster(state, rootId)
1726
+ const fact = normalizeFact({
1727
+ text,
1728
+ category: cat,
1729
+ by: 'user',
1730
+ pinned: Boolean(pinned),
1731
+ originRootId: rootId === 'global' ? '' : rootId,
1732
+ peerRootIds: cat === 'team' ? activeCluster.filter(pid => pid !== rootId) : [],
1733
+ })
1734
+ if (!fact) return { ok: false, error: '条目无效或包含敏感凭据' }
1735
+ ws.facts.push(fact)
1736
+ if (ws.facts.length > FACTS_CAP) ws.facts = ws.facts.slice(-FACTS_CAP)
1737
+ return { ok: true, fact }
1738
+ }
1739
+ const target = ws.facts.find(f => f.id === id)
1740
+ if (!target) return { ok: false, error: '未找到该记忆条目' }
1741
+ if (op === 'remove') {
1742
+ ws.facts = ws.facts.filter(f => f.id !== id)
1743
+ return { ok: true }
1744
+ }
1745
+ if (op === 'pin') {
1746
+ target.pinned = Boolean(pinned)
1747
+ target.updatedAt = Date.now()
1748
+ return { ok: true, fact: target }
1749
+ }
1750
+ if (op === 'edit') {
1751
+ const clean = clamp(text, FACT_TEXT_MAX)
1752
+ if (!clean || secretLike(clean)) return { ok: false, error: '内容无效或包含敏感凭据' }
1753
+ target.text = clean
1754
+ if (category) target.category = category
1755
+ target.updatedAt = Date.now()
1756
+ return { ok: true, fact: target }
1757
+ }
1758
+ return { ok: false, error: '未知操作: ' + op }
1759
+ })
1760
+ }
1761
+
1762
+ export function recordWorkspaceAlertEvent(rootSessionId, spec = {}) {
1763
+ const key = String(rootSessionId || 'global').trim() || 'global'
1764
+ try {
1765
+ return mutateChiefState((state) => {
1766
+ const ws = ensureWorkspace(state, key)
1767
+ return pushAlertEventToWs(ws, spec)
1768
+ })
1769
+ } catch {
1770
+ return null
1771
+ }
1772
+ }
1773
+
1774
+ function tripManagedBudgetCircuit(state, ws, rootId, reason) {
1775
+ const now = Date.now()
1776
+ const effNow = resolveWorkspaceConfig(state, rootId)
1777
+ if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effNow }
1778
+ ws.config.runMode = 'off'
1779
+ ws.config.paceMode = 'manual'
1780
+ ws.config.autoPilot = false
1781
+ ws.config.autoReview = false
1782
+ ws.config.tacticalModes = { ...normalizeTacticalModes(ws.config.tacticalModes), intervention: false }
1783
+ if (state.config && (state.config.runMode === 'managed' || state.config.paceMode === 'auto')) {
1784
+ state.config.runMode = 'off'
1785
+ state.config.paceMode = 'manual'
1786
+ state.config.autoPilot = false
1787
+ state.config.autoReview = false
1788
+ }
1789
+ ws.llmLedger = normalizeLlmLedger(ws.llmLedger)
1790
+ ws.llmLedger.managedRun.tripped = true
1791
+ ws.llmLedger.managedRun.trippedAt = now
1792
+ ws.llmLedger.managedRun.trippedReason = clamp(reason || '已触及托管硬预算上限,自动熔断休眠', 200)
1793
+ ws.chat.push({
1794
+ id: nextId('chat'),
1795
+ role: 'chief',
1796
+ kind: 'receipt',
1797
+ text: `- 【🛑 托管硬预算熔断】${ws.llmLedger.managedRun.trippedReason}\n- 已自动将运行模式退回「⏸ 关停」(人工问答仍可随时使用),保护 Token 费用。`,
1798
+ actions: ['🛑 硬预算熔断'],
1799
+ at: now,
1800
+ })
1801
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
1802
+ pushAuditToWs(ws, {
1803
+ mode: effNow.permissionMode,
1804
+ stage: 'budget_guard',
1805
+ rule: 'managed_budget_exceeded',
1806
+ decision: 'tripped',
1807
+ operation: '托管硬预算上限熔断',
1808
+ target: rootId,
1809
+ reason: ws.llmLedger.managedRun.trippedReason,
1810
+ outcome: 'blocked',
1811
+ by: 'chief',
1812
+ }, rootId)
1813
+ pushAlertEventToWs(ws, {
1814
+ kind: 'budget_circuit_break',
1815
+ level: 'danger',
1816
+ title: '🛑 托管已达预算上限并熔断',
1817
+ body: ws.llmLedger.managedRun.trippedReason,
1818
+ dedupeKey: `budget:${rootId}:${ws.llmLedger.managedRun.startedAt || 0}`,
1819
+ at: now,
1820
+ })
1821
+ return ws.llmLedger.managedRun.trippedReason
1822
+ }
1823
+
1824
+ /** Check before background Managed LLM calls; never blocks human-initiated chat or consultation. */
1825
+ export function checkManagedBudgetBeforeCall(rootSessionId, reasonKind = '') {
1826
+ const rootId = String(rootSessionId || 'global').trim() || 'global'
1827
+ const category = classifyChiefLlmCategory(reasonKind)
1828
+ if (category !== 'review' && category !== 'dream') {
1829
+ return { allowed: true, category }
1830
+ }
1831
+ const st = loadChiefState()
1832
+ const effCfg = resolveWorkspaceConfig(st, rootId)
1833
+ const wsSnap = st.workspaces && st.workspaces[rootId] ? st.workspaces[rootId] : null
1834
+ const ledger = normalizeLlmLedger(wsSnap && wsSnap.llmLedger)
1835
+ const mr = ledger.managedRun
1836
+ if (mr.tripped && !effCfg.stopped && effCfg.runMode !== 'patrol') {
1837
+ return {
1838
+ allowed: false,
1839
+ tripped: true,
1840
+ category,
1841
+ reason: mr.trippedReason || '本轮托管硬预算已触发熔断,请重置计数后再继续',
1842
+ }
1843
+ }
1844
+ if (effCfg.stopped || effCfg.runMode !== 'managed') {
1845
+ return { allowed: true, category }
1846
+ }
1847
+ const maxCalls = normalizeManagedBudgetCalls(effCfg.managedBudgetMaxCalls)
1848
+ const maxTokens = normalizeManagedBudgetTokens(effCfg.managedBudgetMaxTokens)
1849
+ let exceedReason = ''
1850
+ if (mr.tripped) {
1851
+ exceedReason = mr.trippedReason || '本轮托管硬预算已触发熔断,请重置计数后再继续'
1852
+ } else if (maxCalls > 0 && mr.calls >= maxCalls) {
1853
+ exceedReason = `托管后台 LLM 调用已达上限 ${mr.calls}/${maxCalls} 次`
1854
+ } else if (maxTokens > 0 && mr.tokens >= maxTokens) {
1855
+ exceedReason = `托管后台 Token 消耗已达上限 ${formatCompactTokenShort(mr.tokens)}/${formatCompactTokenShort(maxTokens)}`
1856
+ }
1857
+ if (!exceedReason) {
1858
+ return { allowed: true, category }
1859
+ }
1860
+ const trippedReason = mutateChiefState((state) => {
1861
+ const ws = ensureWorkspace(state, rootId)
1862
+ return tripManagedBudgetCircuit(state, ws, rootId, exceedReason)
1863
+ })
1864
+ return { allowed: false, tripped: true, category, reason: trippedReason }
1865
+ }
1866
+
1867
+ /** Record every Chief LLM call usage and enforce Managed-mode hard budget cap immediately when reached. */
1868
+ export function recordChiefLlmUsage(rootSessionId, {
1869
+ reasonKind = '',
1870
+ modelRef = '',
1871
+ inputTokens = 0,
1872
+ outputTokens = 0,
1873
+ estimated = false,
1874
+ ok = true,
1875
+ } = {}) {
1876
+ const rootId = String(rootSessionId || 'global').trim() || 'global'
1877
+ const category = classifyChiefLlmCategory(reasonKind)
1878
+ const inTok = Math.min(LLM_LEDGER_TOKENS_MAX, Math.max(0, Math.round(Number(inputTokens) || 0)))
1879
+ const outTok = Math.min(LLM_LEDGER_TOKENS_MAX, Math.max(0, Math.round(Number(outputTokens) || 0)))
1880
+ const totTok = Math.min(LLM_LEDGER_TOKENS_MAX, inTok + outTok)
1881
+ const now = Date.now()
1882
+ return mutateChiefState((state) => {
1883
+ const ws = ensureWorkspace(state, rootId)
1884
+ const effCfg = resolveWorkspaceConfig(state, rootId)
1885
+ ws.llmLedger = normalizeLlmLedger(ws.llmLedger)
1886
+ const ledger = ws.llmLedger
1887
+ ledger.totalCalls = Math.min(LLM_LEDGER_CALLS_MAX, ledger.totalCalls + 1)
1888
+ ledger.totalInputTokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.totalInputTokens + inTok)
1889
+ ledger.totalOutputTokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.totalOutputTokens + outTok)
1890
+ ledger.totalTokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.totalTokens + totTok)
1891
+ if (!ledger.byCategory[category]) ledger.byCategory[category] = { calls: 0, tokens: 0 }
1892
+ ledger.byCategory[category].calls = Math.min(LLM_LEDGER_CALLS_MAX, ledger.byCategory[category].calls + 1)
1893
+ ledger.byCategory[category].tokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.byCategory[category].tokens + totTok)
1894
+ ledger.recent.push({
1895
+ id: nextId('llm'),
1896
+ at: now,
1897
+ category,
1898
+ reasonKind: clamp(reasonKind || '', 40),
1899
+ modelRef: clamp(modelRef || '', 80),
1900
+ inputTokens: inTok,
1901
+ outputTokens: outTok,
1902
+ totalTokens: totTok,
1903
+ estimated: Boolean(estimated),
1904
+ ok: ok !== false,
1905
+ })
1906
+ if (ledger.recent.length > LLM_LEDGER_RECENT_CAP) {
1907
+ ledger.recent = ledger.recent.slice(-LLM_LEDGER_RECENT_CAP)
1908
+ }
1909
+
1910
+ let trippedReason = ''
1911
+ if (!effCfg.stopped && effCfg.runMode === 'managed' && (category === 'review' || category === 'dream')) {
1912
+ if (!ledger.managedRun.startedAt) ledger.managedRun.startedAt = now
1913
+ ledger.managedRun.calls = Math.min(LLM_LEDGER_CALLS_MAX, ledger.managedRun.calls + 1)
1914
+ ledger.managedRun.tokens = Math.min(LLM_LEDGER_TOKENS_MAX, ledger.managedRun.tokens + totTok)
1915
+ const maxCalls = normalizeManagedBudgetCalls(effCfg.managedBudgetMaxCalls)
1916
+ const maxTokens = normalizeManagedBudgetTokens(effCfg.managedBudgetMaxTokens)
1917
+ if (maxCalls > 0 && ledger.managedRun.calls >= maxCalls) {
1918
+ trippedReason = tripManagedBudgetCircuit(
1919
+ state,
1920
+ ws,
1921
+ rootId,
1922
+ `托管后台 LLM 调用已达硬预算上限 (${ledger.managedRun.calls}/${maxCalls} 次)`,
1923
+ )
1924
+ } else if (maxTokens > 0 && ledger.managedRun.tokens >= maxTokens) {
1925
+ trippedReason = tripManagedBudgetCircuit(
1926
+ state,
1927
+ ws,
1928
+ rootId,
1929
+ `托管后台 Token 消耗已达硬预算上限 (${formatCompactTokenShort(ledger.managedRun.tokens)}/${formatCompactTokenShort(maxTokens)})`,
1930
+ )
1931
+ }
1932
+ }
1933
+ return {
1934
+ ok: true,
1935
+ category,
1936
+ tripped: Boolean(ws.llmLedger.managedRun.tripped && trippedReason),
1937
+ trippedReason,
1938
+ ledger: summarizeLlmLedger(ws.llmLedger, resolveWorkspaceConfig(state, rootId)),
1939
+ }
1940
+ })
1941
+ }
1942
+
1943
+ export function setBubbleHarnessMembership(rootId, { provider, label = '', role = '', joined = true } = {}) {
1944
+ const rid = String(rootId || '').trim()
1945
+ const pName = clamp(String(provider || '').trim(), 64)
1946
+ if (!rid) return { ok: false, error: '当前会话尚未绑定,无法调整协同水泡' }
1947
+ if (!pName || pName === 'spawn' || pName === 'fork') {
1948
+ return { ok: false, error: '无效的外部 Harness Provider 名称' }
1949
+ }
1950
+ return mutateChiefState((state) => {
1951
+ const ws = ensureWorkspace(state, rid)
1952
+ const cur = Array.isArray(ws.bubbleHarnesses) ? ws.bubbleHarnesses : []
1953
+ if (joined) {
1954
+ const entry = normalizeBubbleHarness({ provider: pName, label, role, joinedAt: Date.now() })
1955
+ const next = cur.filter(item => item && item.provider !== pName)
1956
+ next.push(entry)
1957
+ ws.bubbleHarnesses = next.slice(-12)
1958
+ pushAuditToWs(ws, {
1959
+ kind: 'bubble_harness_join',
1960
+ decision: 'allowed',
1961
+ tool: pName,
1962
+ reason: `将外部 Harness「${entry.label}」拖入协同作战水泡`,
1963
+ }, rid)
1964
+ } else {
1965
+ ws.bubbleHarnesses = cur.filter(item => item && item.provider !== pName)
1966
+ pushAuditToWs(ws, {
1967
+ kind: 'bubble_harness_leave',
1968
+ decision: 'allowed',
1969
+ tool: pName,
1970
+ reason: `将外部 Harness「${pName}」移出协同作战水泡`,
1971
+ }, rid)
1972
+ }
1973
+ return { ok: true, bubbleHarnesses: ws.bubbleHarnesses.slice() }
1974
+ })
1975
+ }
1976
+
1977
+ export function setBubbleManualLock(rootId, { locked = false, reason = '' } = {}) {
1978
+ const rid = String(rootId || '').trim()
1979
+ if (!rid) return { ok: false, error: '当前会话尚未绑定' }
1980
+ return mutateChiefState((state) => {
1981
+ const ws = ensureWorkspace(state, rid)
1982
+ ws.bubbleLock = {
1983
+ manualLocked: Boolean(locked),
1984
+ lockedAt: locked ? Date.now() : 0,
1985
+ reason: locked ? clamp(reason || '手动锁定编队结构,防止工作中拆散', 120) : '',
1986
+ }
1987
+ pushAuditToWs(ws, {
1988
+ kind: 'bubble_lock_set',
1989
+ decision: 'allowed',
1990
+ tool: 'bubble_lock',
1991
+ reason: locked ? `锁定协同水泡结构:${ws.bubbleLock.reason}` : '解除协同水泡手动结构锁',
1992
+ }, rid)
1993
+ return { ok: true, bubbleLock: { ...ws.bubbleLock } }
1994
+ })
1995
+ }
1996
+