dsh-chief 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/chief-state.js ADDED
@@ -0,0 +1,1777 @@
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
+ getChiefMountedGlobalForSession,
16
+ getTakenOutGlobalForSession,
17
+ collectSealedWatchSummary,
18
+ getFlippedOutPrecipitatedForSession,
19
+ } from './archives.js'
20
+ import {
21
+ DEFAULT_CHIEF_PERMISSION_MODE,
22
+ CHIEF_PERMISSION_META,
23
+ normalizePermissionMode,
24
+ permissionRank,
25
+ } from './chief-executor.js'
26
+
27
+ const APPROVALS_CAP = 30
28
+
29
+ const AUDIT_LOG_CAP = 80
30
+
31
+ const RESUME_TASKS_CAP = 20
32
+
33
+ const DEFAULT_RESUME_TTL_MS = 30 * 60 * 1000
34
+
35
+ const STATE_VERSION = 1
36
+
37
+ export const FACTS_CAP = 120
38
+
39
+ export const FACT_TEXT_MAX = 260
40
+
41
+ export const CHAT_CAP = 36
42
+
43
+ export const MAIL_CAP = 80
44
+
45
+ export const SUGGESTIONS_CAP = 6
46
+
47
+ export const MODEL_TIMEOUT_MS = 90_000
48
+
49
+ export const CATALOG_TTL_MS = 10_000
50
+
51
+ export const REVIEW_DELAY_MS = 2_800
52
+
53
+ export const AUTO_SUMMARY_COOLDOWN_MS = 5 * 60_000
54
+
55
+ export const SMART_REVIEW_COOLDOWN_MS = 3 * 60_000
56
+
57
+ export const AUTO_REVIEW_COOLDOWN_MS = 90_000
58
+
59
+ // Thinking models spend several thousand output tokens on internal reasoning before emitting text;
60
+ // small caps (e.g. 2k-4k) starve the visible answer to empty string.
61
+ export const SUMMARY_MAX_TOKENS = 16_384
62
+
63
+ export const SUMMARY_RETRY_MAX_TOKENS = 32_768
64
+
65
+ export const CHIEF_UPDATE_SOURCE = 'dsh-chief-update'
66
+
67
+ export const CHIEF_RELAY_SOURCE = 'dsh-chief-relay'
68
+
69
+ 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-----)/
70
+
71
+ let dshAttachmentModulePromise = null
72
+
73
+ async function loadDshAttachment() {
74
+ if (!dshAttachmentModulePromise) {
75
+ dshAttachmentModulePromise = import('@deepseek-ai/dsh-attachment').catch(() => null)
76
+ }
77
+ return dshAttachmentModulePromise
78
+ }
79
+
80
+ const CHIEF_MAX_IMAGES = 4
81
+
82
+ const CHIEF_IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
83
+
84
+ function normalizeUploadedImage(raw, idx = 0) {
85
+ if (!raw || typeof raw !== 'object') return null
86
+ let mediaType = String(raw.mediaType || raw.mimeType || raw.type || '').trim().toLowerCase()
87
+ let data = String(raw.data || raw.base64 || '').trim()
88
+ const dataUrlMatch = data.match(/^data:([^;]+);base64,(.+)$/is)
89
+ if (dataUrlMatch) {
90
+ if (!mediaType) mediaType = dataUrlMatch[1].trim().toLowerCase()
91
+ data = dataUrlMatch[2].trim()
92
+ }
93
+ if (mediaType === 'image/jpg') mediaType = 'image/jpeg'
94
+ data = data.replace(/\s+/g, '')
95
+ if (!CHIEF_IMAGE_MEDIA_TYPES.has(mediaType) || !data) return null
96
+ const ext = mediaType === 'image/jpeg' ? 'jpg' : (mediaType.split('/')[1] || 'png')
97
+ const name = typeof raw.name === 'string' && raw.name.trim()
98
+ ? clamp(raw.name.trim(), 80)
99
+ : `chief-image-${idx + 1}.${ext}`
100
+ return { name, mediaType, data }
101
+ }
102
+
103
+ export function resolveSessionWorkspaceCwd(deps, sessionId) {
104
+ const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || sessionId
105
+ try {
106
+ if (deps && typeof deps.getSessionCwd === 'function') {
107
+ const c = deps.getSessionCwd(rootId) || deps.getSessionCwd(sessionId)
108
+ if (c && fs.existsSync(c)) return c
109
+ }
110
+ if (deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function') {
111
+ const b = deps.boardForSession(deps.boardFileFor(rootId))
112
+ const sess = b && b.sessions && (b.sessions[rootId] || b.sessions[sessionId])
113
+ if (sess && sess.cwd && fs.existsSync(sess.cwd)) return sess.cwd
114
+ }
115
+ } catch {}
116
+ return process.cwd()
117
+ }
118
+
119
+ export function archiveTargetForRoot(deps, rootId, extra = '') {
120
+ const opts = extra && typeof extra === 'object' ? extra : { cabinetId: String(extra || '') }
121
+ const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
122
+ const sharedFile = deps && (typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile)
123
+ const cwd = resolveSessionWorkspaceCwd(deps, rootId)
124
+ let cab = opts.cabinetId ? String(opts.cabinetId).trim() : ''
125
+ if (vaultScope !== 'global' && !cab && deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function' && rootId && rootId !== 'global') {
126
+ try {
127
+ const b = deps.boardForSession(deps.boardFileFor(rootId))
128
+ if (b && typeof b.activeCabinetId === 'string') cab = b.activeCabinetId.trim()
129
+ } catch {}
130
+ }
131
+ return {
132
+ customSharedBoardFile: sharedFile || '',
133
+ cwd,
134
+ vaultScope,
135
+ ...(vaultScope !== 'global' && rootId && rootId !== 'global' ? { rootSessionId: String(rootId).trim() } : {}),
136
+ ...(cab ? { cabinetId: cab } : {}),
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Chief-of-Staff visibility matrix (0-Token Global Cold Vault):
142
+ * - Sees current session's Working Cabinet (`session`), if bound to a concrete rootSessionId
143
+ * - Sees ONLY System Global Cold Vault entries explicitly mounted for Chief in THIS session (`chiefMountedSessions`) — 0 Token by default!
144
+ * - Sees Precipitated Vault entries ONLY when explicitly `flippedOut` (`ws.flippedPrecipitatedIds`) for this session!
145
+ */
146
+ export function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null) {
147
+ const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
148
+ const sessionTarget = sid ? archiveTargetForRoot(deps, sid, { vaultScope: 'session' }) : null
149
+ const globalTarget = archiveTargetForRoot(deps, sid || 'global', { vaultScope: 'global' })
150
+ const baseOpt = sessionTarget || globalTarget
151
+ const projectKey = resolveProjectKey(baseOpt.cwd)
152
+
153
+ let deskSessionItems = []
154
+ let deskGlobalItems = []
155
+ let deskFlippedItems = []
156
+ let mountedGlobalItems = []
157
+ let sealedWatch = { sessionSealed: [], globalSealed: [], precipSealed: [] }
158
+
159
+ try {
160
+ if (sessionTarget) {
161
+ const stSess = loadArchiveStore(sessionTarget)
162
+ const allSess = Array.isArray(stSess.items) ? stSess.items : []
163
+ deskSessionItems = allSess.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).slice(0, 6)
164
+ }
165
+ } catch {}
166
+ try {
167
+ if (sid) {
168
+ deskGlobalItems = getTakenOutGlobalForSession(sid, globalTarget).slice(0, 6)
169
+ mountedGlobalItems = getChiefMountedGlobalForSession(sid, globalTarget).slice(0, 6)
170
+ }
171
+ } catch {}
172
+ try {
173
+ if (sid) {
174
+ const st = stateSnapshot || loadChiefState()
175
+ const ws = st && st.workspaces && st.workspaces[sid]
176
+ const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
177
+ if (flippedIds.length > 0) {
178
+ deskFlippedItems = getFlippedOutPrecipitatedForSession(projectKey, sid, true, baseOpt).slice(0, 6)
179
+ }
180
+ }
181
+ } catch {}
182
+ try {
183
+ sealedWatch = collectSealedWatchSummary(sid, projectKey, baseOpt, { limitPerVault: 8 })
184
+ } catch {}
185
+
186
+ return {
187
+ deskSessionItems,
188
+ deskGlobalItems,
189
+ deskFlippedItems,
190
+ mountedGlobalItems,
191
+ sealedWatch,
192
+ sessionTarget,
193
+ globalTarget,
194
+ }
195
+ }
196
+
197
+ /** Persist raw uploaded images onto local workspace `.dsh-chief/uploads/` so any agent can inspect raw files even when LLM vision is unavailable. */
198
+ export function persistChiefImagesToWorkspace(deps, sessionId, rawImages) {
199
+ const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
200
+ if (!list.length) return []
201
+ const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
202
+ if (!normalized.length) return []
203
+
204
+ const cwd = resolveSessionWorkspaceCwd(deps, sessionId)
205
+ const uploadDir = path.join(cwd, '.dsh-chief', 'uploads')
206
+ fs.mkdirSync(uploadDir, { recursive: true })
207
+
208
+ const d = new Date()
209
+ const stamp = [
210
+ d.getFullYear(),
211
+ String(d.getMonth() + 1).padStart(2, '0'),
212
+ String(d.getDate()).padStart(2, '0'),
213
+ ].join('') + '-' + [
214
+ String(d.getHours()).padStart(2, '0'),
215
+ String(d.getMinutes()).padStart(2, '0'),
216
+ String(d.getSeconds()).padStart(2, '0'),
217
+ ].join('')
218
+
219
+ const saved = []
220
+ for (let idx = 0; idx < normalized.length; idx += 1) {
221
+ const img = normalized[idx]
222
+ const ext = img.mediaType === 'image/jpeg' ? 'jpg' : (img.mediaType.split('/')[1] || 'png')
223
+ const baseRaw = path.basename(String(img.name || `image-${idx + 1}`), path.extname(String(img.name || '')))
224
+ const safeName = baseRaw.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || `image-${idx + 1}`
225
+ const fileName = `${stamp}-${idx + 1}-${safeName}.${ext}`
226
+ const absPath = path.join(uploadDir, fileName)
227
+ const buf = Buffer.from(img.data, 'base64')
228
+ fs.writeFileSync(absPath, buf)
229
+ saved.push({
230
+ index: idx + 1,
231
+ path: absPath,
232
+ name: img.name || fileName,
233
+ mediaType: img.mediaType,
234
+ bytes: buf.length,
235
+ })
236
+ }
237
+ return saved
238
+ }
239
+
240
+ export async function admitChiefImages(deps, rawImages) {
241
+ const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
242
+ if (!list.length) return []
243
+ const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
244
+ if (!normalized.length) {
245
+ throw new Error('上传的图片格式不受支持(仅支持 PNG / JPEG / WebP / GIF Base64)')
246
+ }
247
+
248
+ if (deps && typeof deps.admitImagesOverride === 'function') {
249
+ const refs = await deps.admitImagesOverride(normalized)
250
+ return (Array.isArray(refs) ? refs : []).filter(Boolean).map(attachment => ({ type: 'image', attachment }))
251
+ }
252
+
253
+ const attachmentsSvc = deps && typeof deps.getAttachments === 'function'
254
+ ? deps.getAttachments()
255
+ : (deps && deps.runtime && typeof deps.runtime.get === 'function' ? deps.runtime.get('attachments') : null)
256
+ if (!attachmentsSvc) {
257
+ throw new Error('当前 DSH 运行环境未挂载 attachments 图片服务,无法处理图片上传')
258
+ }
259
+
260
+ const attMod = await loadDshAttachment()
261
+ if (attMod && typeof attMod.admitEncodedImages === 'function') {
262
+ const refs = await attMod.admitEncodedImages(attachmentsSvc, normalized)
263
+ return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
264
+ }
265
+
266
+ if (typeof attachmentsSvc.saveImages === 'function') {
267
+ const payload = normalized.map(img => ({
268
+ data: Uint8Array.from(Buffer.from(img.data, 'base64')),
269
+ mediaType: img.mediaType,
270
+ name: img.name,
271
+ }))
272
+ const refs = await attachmentsSvc.saveImages(payload)
273
+ return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
274
+ }
275
+
276
+ throw new Error('attachments 服务缺少 saveImages / admitEncodedImages 接口')
277
+ }
278
+
279
+ let idSeq = 0
280
+
281
+ export function nextId(prefix) {
282
+ idSeq = (idSeq + 1) % 1000000
283
+ return prefix + '-' + Date.now().toString(36) + '-' + idSeq.toString(36)
284
+ }
285
+
286
+ export function clamp(value, max) {
287
+ const text = String(value == null ? '' : value).replace(/\s+/g, ' ').trim()
288
+ if (text.length <= max) return text
289
+ return text.slice(0, Math.max(0, max - 1)) + '…'
290
+ }
291
+
292
+ export function cleanMultiline(value, max) {
293
+ const text = String(value == null ? '' : value).replace(/\r/g, '').trim()
294
+ if (text.length <= max) return text
295
+ return text.slice(0, Math.max(0, max - 1)) + '…'
296
+ }
297
+
298
+ export function secretLike(text) {
299
+ return SECRET_PATTERN.test(String(text || ''))
300
+ }
301
+
302
+ function chiefDir() {
303
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
304
+ return path.join(home, 'chief')
305
+ }
306
+
307
+ function stateFilePath() {
308
+ return path.join(chiefDir(), 'chief-state.json')
309
+ }
310
+
311
+ export function auditJsonlPath() {
312
+ return path.join(chiefDir(), 'chief-audit.jsonl')
313
+ }
314
+
315
+ function appendAuditJsonlLine(record) {
316
+ try {
317
+ const file = auditJsonlPath()
318
+ fs.mkdirSync(path.dirname(file), { recursive: true })
319
+ fs.appendFileSync(file, JSON.stringify(record) + '\n', 'utf8')
320
+ } catch {}
321
+ }
322
+
323
+ function canonicalSortJsonValue(val) {
324
+ if (val === null || val === undefined) return null
325
+ if (Array.isArray(val)) return val.map(v => canonicalSortJsonValue(v))
326
+ if (typeof val === 'object') {
327
+ const out = {}
328
+ for (const k of Object.keys(val).sort()) {
329
+ const v = val[k]
330
+ if (v !== undefined) out[k] = canonicalSortJsonValue(v)
331
+ }
332
+ return out
333
+ }
334
+ return val
335
+ }
336
+
337
+ export function computeApprovalPayloadHash(kind = 'tool', payload = {}) {
338
+ const canonical = JSON.stringify(canonicalSortJsonValue({
339
+ kind: String(kind || 'tool'),
340
+ payload: payload && typeof payload === 'object' ? payload : {},
341
+ }))
342
+ return crypto.createHash('sha256').update(canonical).digest('hex')
343
+ }
344
+
345
+ function normalizeChiefRiskAck(raw) {
346
+ if (!raw || typeof raw !== 'object' || raw.acknowledged !== true) return null
347
+ const at = Number(raw.at) || 0
348
+ if (at <= 0) return null
349
+ return {
350
+ acknowledged: true,
351
+ at,
352
+ by: clamp(raw.by || 'operator', 40),
353
+ version: clamp(raw.version || '1.2.1', 20),
354
+ }
355
+ }
356
+
357
+ export function hasValidChiefRiskAck(ws) {
358
+ return Boolean(ws && ws.chiefRiskAck && ws.chiefRiskAck.acknowledged === true && Number(ws.chiefRiskAck.at) > 0)
359
+ }
360
+
361
+ function normalizePendingApproval(raw) {
362
+ if (!raw || typeof raw !== 'object') return null
363
+ const opLabel = clamp(raw.operationLabel || raw.operation || '', 80)
364
+ if (!opLabel) return null
365
+ const validStatuses = ['pending', 'approved', 'rejected', 'executed', 'failed']
366
+ const status = validStatuses.includes(raw.status) ? raw.status : 'pending'
367
+ const validKinds = ['tool', 'relay', 'compact', 'auto_continue']
368
+ const kind = validKinds.includes(raw.kind) ? raw.kind : 'tool'
369
+ const validCategories = ['workspace_file', 'system_command', 'main_workflow', 'subagent_workflow']
370
+ const category = validCategories.includes(raw.category) ? raw.category : 'workspace_file'
371
+ const payload = raw.payload && typeof raw.payload === 'object' ? raw.payload : {}
372
+ const payloadHash = typeof raw.payloadHash === 'string' && raw.payloadHash.trim()
373
+ ? raw.payloadHash.trim()
374
+ : computeApprovalPayloadHash(kind, payload)
375
+ return {
376
+ id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('apr'),
377
+ status,
378
+ category,
379
+ operationLabel: opLabel,
380
+ targetLabel: clamp(raw.targetLabel || raw.target || '', 120),
381
+ reason: clamp(raw.reason || '', 240),
382
+ impact: clamp(raw.impact || '', 220),
383
+ preview: cleanMultiline(raw.preview || '', 420),
384
+ kind,
385
+ payload,
386
+ payloadHash,
387
+ resumeTaskId: clamp(raw.resumeTaskId || '', 80),
388
+ expiresAt: Math.max(0, Number(raw.expiresAt) || 0),
389
+ dedupeKey: clamp(raw.dedupeKey || '', 120),
390
+ by: clamp(raw.by || 'chief', 40),
391
+ createdAt: Number(raw.createdAt) || Date.now(),
392
+ resolvedAt: Number(raw.resolvedAt) || 0,
393
+ resolvedBy: clamp(raw.resolvedBy || '', 40),
394
+ resultMessage: clamp(raw.resultMessage || '', 260),
395
+ }
396
+ }
397
+
398
+ function normalizePendingElevation(raw) {
399
+ if (!raw || typeof raw !== 'object') return null
400
+ if (raw.status && raw.status !== 'pending') return null
401
+ const targetMode = normalizePermissionMode(raw.targetMode)
402
+ if (targetMode === 'advisor') return null
403
+ const createdAt = Number(raw.createdAt) || Date.now()
404
+ return {
405
+ id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('elv'),
406
+ status: 'pending',
407
+ fromMode: normalizePermissionMode(raw.fromMode || 'advisor'),
408
+ targetMode,
409
+ reason: clamp(raw.reason || '当前任务需要更高参谋权限才能继续执行', 260),
410
+ requestedActionSummary: clamp(raw.requestedActionSummary || '', 220),
411
+ resumeTaskId: clamp(raw.resumeTaskId || '', 80),
412
+ expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
413
+ by: clamp(raw.by || 'chief', 40),
414
+ createdAt,
415
+ }
416
+ }
417
+
418
+ function normalizeResumeTask(raw) {
419
+ if (!raw || typeof raw !== 'object') return null
420
+ const originalText = cleanMultiline(raw.originalText || '', 2000)
421
+ if (!originalText) return null
422
+ const validStatuses = ['awaiting_elevation', 'awaiting_approval', 'resuming', 'completed', 'cancelled', 'expired', 'failed']
423
+ const status = validStatuses.includes(raw.status) ? raw.status : 'awaiting_approval'
424
+ const createdAt = Number(raw.createdAt) || Date.now()
425
+ return {
426
+ id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('rtask'),
427
+ status,
428
+ originalText,
429
+ forcedTarget: clamp(raw.forcedTarget || '', 64),
430
+ forcedMode: ['steer', 'followup', 'silent'].includes(raw.forcedMode) ? raw.forcedMode : 'steer',
431
+ savedImagePaths: Array.isArray(raw.savedImagePaths)
432
+ ? raw.savedImagePaths.slice(0, 4).filter(p => p && typeof p.path === 'string').map(p => ({
433
+ index: Number(p.index) || 1,
434
+ path: String(p.path),
435
+ name: clamp(p.name || '', 80),
436
+ mediaType: clamp(p.mediaType || '', 40),
437
+ bytes: Math.max(0, Number(p.bytes) || 0),
438
+ }))
439
+ : [],
440
+ completedActions: Array.isArray(raw.completedActions)
441
+ ? raw.completedActions.map(x => clamp(x, 220)).filter(Boolean).slice(-12)
442
+ : [],
443
+ pendingApprovalIds: Array.isArray(raw.pendingApprovalIds)
444
+ ? [...new Set(raw.pendingApprovalIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 12)
445
+ : [],
446
+ elevationId: clamp(raw.elevationId || '', 80),
447
+ resumeDepth: Math.max(0, Math.min(4, Math.round(Number(raw.resumeDepth) || 0))),
448
+ createdAt,
449
+ expiresAt: Math.max(0, Number(raw.expiresAt) || (createdAt + DEFAULT_RESUME_TTL_MS)),
450
+ resolvedAt: Math.max(0, Number(raw.resolvedAt) || 0),
451
+ }
452
+ }
453
+
454
+ function normalizeAuditEntry(raw) {
455
+ if (!raw || typeof raw !== 'object') return null
456
+ const op = clamp(raw.operation || raw.tool || '', 80)
457
+ if (!op) return null
458
+ return {
459
+ id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('aud'),
460
+ at: Number(raw.at) || Date.now(),
461
+ mode: normalizePermissionMode(raw.mode || DEFAULT_CHIEF_PERMISSION_MODE),
462
+ stage: clamp(raw.stage || 'executor', 40),
463
+ decision: clamp(raw.decision || 'executed', 40),
464
+ operation: op,
465
+ target: clamp(raw.target || '', 140),
466
+ reason: clamp(raw.reason || '', 220),
467
+ outcome: clamp(raw.outcome || 'ok', 40),
468
+ by: clamp(raw.by || 'chief', 40),
469
+ }
470
+ }
471
+
472
+ export function pushAuditToWs(ws, entry = {}, sessionId = '') {
473
+ if (!ws || typeof ws !== 'object') return null
474
+ if (!Array.isArray(ws.auditLog)) ws.auditLog = []
475
+ const norm = normalizeAuditEntry(entry)
476
+ if (!norm) return null
477
+ ws.auditLog.push(norm)
478
+ if (ws.auditLog.length > AUDIT_LOG_CAP) ws.auditLog = ws.auditLog.slice(-AUDIT_LOG_CAP)
479
+ appendAuditJsonlLine({
480
+ ...(sessionId ? { sessionId: String(sessionId) } : {}),
481
+ ...norm,
482
+ })
483
+ return norm
484
+ }
485
+
486
+ function emptyWorkspace() {
487
+ return {
488
+ config: null,
489
+ chiefRiskAck: null,
490
+ pendingApprovals: [],
491
+ pendingElevation: null,
492
+ resumeTasks: [],
493
+ auditLog: [],
494
+ facts: [],
495
+ narrative: { hash: '', text: '', at: 0, byModel: '', clusterSig: '' },
496
+ suggestions: [],
497
+ chat: [],
498
+ mailbox: [],
499
+ seenMailAt: {},
500
+ seenFactsAt: {},
501
+ reviewCursors: {},
502
+ runtimeGuard: {
503
+ lastCompactedSeq: 0,
504
+ lastCompactedAt: 0,
505
+ interventionTurns: 0,
506
+ lastDigestHash: '',
507
+ unchangedCount: 0,
508
+ cooldownUntil: 0,
509
+ circuitBroken: false,
510
+ circuitReason: '',
511
+ hazardAlert: null,
512
+ lastGoalAchievedSig: '',
513
+ autoPilotStartedAt: 0,
514
+ autoPilotHadTurn: false,
515
+ lastAutoArchiveOrgAt: 0,
516
+ },
517
+ flippedPrecipitatedIds: [],
518
+ }
519
+ }
520
+
521
+ export function normalizeFact(raw) {
522
+ if (!raw || typeof raw !== 'object') return null
523
+ const text = clamp(raw.text, FACT_TEXT_MAX)
524
+ if (!text || secretLike(text)) return null
525
+ const validCategories = ['discipline', 'architecture', 'progress', 'preference', 'team']
526
+ const category = validCategories.includes(raw.category) ? raw.category : 'discipline'
527
+ const peerRootIds = Array.isArray(raw.peerRootIds)
528
+ ? [...new Set(raw.peerRootIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 16)
529
+ : []
530
+ return {
531
+ id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('fact'),
532
+ text,
533
+ category,
534
+ by: clamp(raw.by || 'chief', 36),
535
+ source: clamp(raw.source || '', 60),
536
+ originRootId: typeof raw.originRootId === 'string' ? raw.originRootId.trim() : '',
537
+ ...(peerRootIds.length ? { peerRootIds } : {}),
538
+ pinned: Boolean(raw.pinned),
539
+ addedAt: Number(raw.addedAt) || Date.now(),
540
+ updatedAt: Number(raw.updatedAt) || Number(raw.addedAt) || Date.now(),
541
+ }
542
+ }
543
+
544
+ export function normalizeSuggestion(raw) {
545
+ if (!raw || typeof raw !== 'object') return null
546
+ const title = clamp(raw.title, 90)
547
+ if (!title) return null
548
+ const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice'].includes(raw.kind) ? raw.kind : 'relay'
549
+ const boundField = ['forbidden', 'allowed', 'notes'].includes(raw.boundField) ? raw.boundField : 'forbidden'
550
+ const replaces = Array.isArray(raw.replaces)
551
+ ? raw.replaces.map(x => String(x || '').trim()).filter(Boolean).slice(0, 20)
552
+ : []
553
+ return {
554
+ id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('sug'),
555
+ kind,
556
+ boundField,
557
+ replaces,
558
+ pinGlobal: Boolean(raw.pinGlobal),
559
+ fromAgent: clamp(raw.fromAgent || '', 48),
560
+ title,
561
+ reason: clamp(raw.reason || '', 220),
562
+ target: clamp(raw.target || (kind === 'bound' ? 'bounds' : kind === 'goal_approval' ? 'board' : 'lead'), 64),
563
+ targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : kind === 'goal_approval' ? '目标结项批示' : kind === 'advice' ? '参谋进言' : '主对话'), 40),
564
+ mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : (kind === 'advice' ? 'followup' : 'steer'),
565
+ draftText: cleanMultiline(raw.draftText || '', 600),
566
+ evidence: cleanMultiline(raw.evidence || '', 600),
567
+ missing: clamp(raw.missing || '', 300),
568
+ boardOp: raw.boardOp && typeof raw.boardOp === 'object' ? raw.boardOp : null,
569
+ popup: Boolean(raw.popup || kind === 'advice'),
570
+ urgency: ['normal', 'high'].includes(raw.urgency) ? raw.urgency : 'normal',
571
+ status: ['pending', 'applied', 'dismissed'].includes(raw.status) ? raw.status : 'pending',
572
+ createdAt: Number(raw.createdAt) || Date.now(),
573
+ }
574
+ }
575
+
576
+ export function normalizeMail(raw) {
577
+ if (!raw || typeof raw !== 'object') return null
578
+ const imageCount = Math.max(0, Math.round(Number(raw.imageCount) || 0))
579
+ const text = cleanMultiline(raw.text, 1500) || (imageCount > 0 ? `[附图 ×${imageCount}]` : '')
580
+ if (!text) return null
581
+ const participantRoots = Array.isArray(raw.participantRoots)
582
+ ? [...new Set(raw.participantRoots.map(x => String(x || '').trim()).filter(Boolean))].sort().slice(0, 24)
583
+ : []
584
+ const validChannels = ['internal', 'pair', 'multi', 'broadcast']
585
+ const channelType = validChannels.includes(raw.channelType) ? raw.channelType : ''
586
+ return {
587
+ id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('mail'),
588
+ from: clamp(raw.from || 'agent', 48),
589
+ fromSession: String(raw.fromSession || ''),
590
+ fromRootId: String(raw.fromRootId || ''),
591
+ to: clamp(raw.to || 'lead', 64),
592
+ toSession: String(raw.toSession || ''),
593
+ toRootId: String(raw.toRootId || ''),
594
+ ...(participantRoots.length ? { participantRoots } : {}),
595
+ ...(channelType ? { channelType } : {}),
596
+ ...(raw.broadcastId ? { broadcastId: String(raw.broadcastId) } : {}),
597
+ subject: clamp(raw.subject || '', 80),
598
+ text,
599
+ ...(imageCount > 0 ? { imageCount } : {}),
600
+ mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : 'steer',
601
+ deliveredPhysical: Boolean(raw.deliveredPhysical),
602
+ readBy: Array.isArray(raw.readBy) ? raw.readBy.map(String).slice(0, 32) : [],
603
+ at: Number(raw.at) || Date.now(),
604
+ }
605
+ }
606
+
607
+ function normalizeWorkspace(raw) {
608
+ const src = raw && typeof raw === 'object' ? raw : {}
609
+ const base = emptyWorkspace()
610
+ base.facts = (Array.isArray(src.facts) ? src.facts : []).map(normalizeFact).filter(Boolean).slice(-FACTS_CAP)
611
+ if (src.narrative && typeof src.narrative === 'object') {
612
+ base.narrative = {
613
+ hash: String(src.narrative.hash || ''),
614
+ text: String(src.narrative.text || ''),
615
+ at: Number(src.narrative.at) || 0,
616
+ byModel: String(src.narrative.byModel || ''),
617
+ clusterSig: String(src.narrative.clusterSig || ''),
618
+ }
619
+ }
620
+ base.suggestions = (Array.isArray(src.suggestions) ? src.suggestions : [])
621
+ .map(normalizeSuggestion)
622
+ .filter(Boolean)
623
+ .slice(-SUGGESTIONS_CAP * 2)
624
+ base.chat = (Array.isArray(src.chat) ? src.chat : [])
625
+ .filter(item => item && typeof item === 'object' && typeof item.text === 'string')
626
+ .slice(-CHAT_CAP)
627
+ .map(item => {
628
+ const imageCount = Math.max(0, Math.round(Number(item.imageCount) || 0))
629
+ const kind = item.kind === 'receipt' ? 'receipt' : (item.kind === 'qa' ? 'qa' : '')
630
+ const resumeTaskId = item.resumeTaskId ? String(item.resumeTaskId) : ''
631
+ return {
632
+ id: String(item.id || nextId('chat')),
633
+ role: item.role === 'user' ? 'user' : 'chief',
634
+ text: cleanMultiline(item.text, 2000),
635
+ target: item.target ? String(item.target) : '',
636
+ ...(kind ? { kind } : {}),
637
+ ...(resumeTaskId ? { resumeTaskId } : {}),
638
+ ...(imageCount > 0 ? { imageCount } : {}),
639
+ actions: Array.isArray(item.actions) ? item.actions.slice(0, 8) : [],
640
+ at: Number(item.at) || Date.now(),
641
+ }
642
+ })
643
+ base.mailbox = (Array.isArray(src.mailbox) ? src.mailbox : []).map(normalizeMail).filter(Boolean).slice(-MAIL_CAP)
644
+ base.seenMailAt = src.seenMailAt && typeof src.seenMailAt === 'object' ? { ...src.seenMailAt } : {}
645
+ base.seenFactsAt = src.seenFactsAt && typeof src.seenFactsAt === 'object' ? { ...src.seenFactsAt } : {}
646
+ base.reviewCursors = src.reviewCursors && typeof src.reviewCursors === 'object' ? { ...src.reviewCursors } : {}
647
+ const rg = src.runtimeGuard && typeof src.runtimeGuard === 'object' ? src.runtimeGuard : {}
648
+ base.runtimeGuard = {
649
+ lastCompactedSeq: Math.max(0, Math.round(Number(rg.lastCompactedSeq) || 0)),
650
+ lastCompactedAt: Math.max(0, Number(rg.lastCompactedAt) || 0),
651
+ autoCompactCount: Math.max(0, Math.round(Number(rg.autoCompactCount) || 0)),
652
+ pendingSmartCompact: rg.pendingSmartCompact && typeof rg.pendingSmartCompact === 'object'
653
+ ? {
654
+ at: Number(rg.pendingSmartCompact.at) || Date.now(),
655
+ reason: clamp(rg.pendingSmartCompact.reason || '', 240),
656
+ by: clamp(rg.pendingSmartCompact.by || 'lead', 40),
657
+ }
658
+ : null,
659
+ interventionTurns: Math.max(0, Math.round(Number(rg.interventionTurns) || 0)),
660
+ lastDigestHash: String(rg.lastDigestHash || ''),
661
+ unchangedCount: Math.max(0, Math.round(Number(rg.unchangedCount) || 0)),
662
+ cooldownUntil: Math.max(0, Number(rg.cooldownUntil) || 0),
663
+ circuitBroken: Boolean(rg.circuitBroken),
664
+ circuitReason: String(rg.circuitReason || ''),
665
+ hazardAlert: rg.hazardAlert && typeof rg.hazardAlert === 'object' && (rg.hazardAlert.reason || rg.hazardAlert.title)
666
+ ? {
667
+ id: String(rg.hazardAlert.id || ''),
668
+ category: clamp(rg.hazardAlert.category || 'irreversible_risk', 40),
669
+ title: clamp(rg.hazardAlert.title || '强介入安全煞停', 120),
670
+ reason: cleanMultiline(rg.hazardAlert.reason || '', 600),
671
+ objective: clamp(rg.hazardAlert.objective || '', 300),
672
+ at: Math.max(0, Number(rg.hazardAlert.at) || 0),
673
+ }
674
+ : null,
675
+ lastGoalAchievedSig: String(rg.lastGoalAchievedSig || ''),
676
+ autoPilotStartedAt: Math.max(0, Number(rg.autoPilotStartedAt) || 0),
677
+ autoPilotHadTurn: Boolean(rg.autoPilotHadTurn),
678
+ lastAutoArchiveOrgAt: Math.max(0, Number(rg.lastAutoArchiveOrgAt) || 0),
679
+ }
680
+ base.chiefRiskAck = normalizeChiefRiskAck(src.chiefRiskAck)
681
+ base.pendingApprovals = (Array.isArray(src.pendingApprovals) ? src.pendingApprovals : [])
682
+ .map(normalizePendingApproval)
683
+ .filter(Boolean)
684
+ .slice(-APPROVALS_CAP)
685
+ base.pendingElevation = normalizePendingElevation(src.pendingElevation)
686
+ base.resumeTasks = (Array.isArray(src.resumeTasks) ? src.resumeTasks : [])
687
+ .map(normalizeResumeTask)
688
+ .filter(Boolean)
689
+ .slice(-RESUME_TASKS_CAP)
690
+ base.auditLog = (Array.isArray(src.auditLog) ? src.auditLog : [])
691
+ .map(normalizeAuditEntry)
692
+ .filter(Boolean)
693
+ .slice(-AUDIT_LOG_CAP)
694
+ const ackOk = hasValidChiefRiskAck(base)
695
+ if (src.config && typeof src.config === 'object') {
696
+ const validPaces = ['manual', 'smart', 'auto', 'stopped']
697
+ const pm = validPaces.includes(src.config.paceMode) ? src.config.paceMode : undefined
698
+ const rawStopped = typeof src.config.stopped === 'boolean' ? src.config.stopped : (pm === 'stopped')
699
+ const rawPerm = typeof src.config.permissionMode === 'string'
700
+ ? normalizePermissionMode(src.config.permissionMode, { requireAck: true, hasChiefRiskAck: ackOk })
701
+ : DEFAULT_CHIEF_PERMISSION_MODE
702
+ base.config = {
703
+ ...(typeof src.config.modelRef === 'string' ? { modelRef: src.config.modelRef.trim() } : {}),
704
+ permissionMode: rawPerm,
705
+ ...(typeof src.config.stopped === 'boolean' || pm === 'stopped' ? { stopped: rawStopped } : {}),
706
+ ...(pm ? { paceMode: pm, autoPilot: !rawStopped && pm === 'auto', autoReview: !rawStopped && pm !== 'manual' } : {}),
707
+ ...(src.config.tacticalModes && typeof src.config.tacticalModes === 'object'
708
+ ? { tacticalModes: normalizeTacticalModes(src.config.tacticalModes) }
709
+ : {}),
710
+ }
711
+ }
712
+ base.flippedPrecipitatedIds = Array.isArray(src.flippedPrecipitatedIds)
713
+ ? [...new Set(src.flippedPrecipitatedIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 20)
714
+ : []
715
+ return base
716
+ }
717
+
718
+ export const COMPACT_THRESHOLD_MIN_PCT = 10
719
+
720
+ export const COMPACT_THRESHOLD_MAX_PCT = 95
721
+
722
+ export const COMPACT_PCT_WARN_FLOOR = 25
723
+
724
+ export const COMPACT_TOKEN_HARD_MIN = 8_000
725
+
726
+ export const COMPACT_TOKEN_WARN_FLOOR = 32_000
727
+
728
+ /** Format a token threshold cleanly into compact K/M display notation (e.g. `64K`, `1M`). */
729
+ export function formatCompactTokenShort(tokens) {
730
+ const n = Math.max(0, Math.round(Number(tokens) || 0))
731
+ if (n >= 1_000_000 && n % 100_000 === 0) {
732
+ const m = n / 1_000_000
733
+ return (Number.isInteger(m) ? String(m) : m.toFixed(1).replace(/\.0$/, '')) + 'M'
734
+ }
735
+ if (n >= 1_000) {
736
+ const k = n / 1_000
737
+ return (k >= 100 ? String(Math.round(k)) : k.toFixed(1).replace(/\.0$/, '')) + 'K'
738
+ }
739
+ return String(n)
740
+ }
741
+
742
+ /**
743
+ * Parse custom context size threshold input (`'1M'` -> 1,000,000; `'64K'` -> 64,000; bare `'64'` -> `64K`).
744
+ * Bare numbers without a unit default to K, and values below `32K` attach a low-threshold warning.
745
+ */
746
+ export function parseCompactTokensInput(rawInput) {
747
+ const s = String(rawInput ?? '').trim()
748
+ if (!s) return { ok: false, error: '请输入上下文阈值,例如 64K、1M 或纯数字(无单位默认为 K)' }
749
+ const m = s.match(/^(\d+(?:\.\d+)?)\s*(k|m|t|tokens?)?$/i)
750
+ if (!m) return { ok: false, error: '格式无效:支持如 64K、1M 或纯数字(无单位默认为 K)' }
751
+ const num = Number(m[1])
752
+ if (!Number.isFinite(num) || num <= 0) return { ok: false, error: '上下文阈值必须大于 0' }
753
+ const unit = (m[2] || 'k').toLowerCase()
754
+ let rawTokens = 0
755
+ if (unit === 'm') rawTokens = Math.round(num * 1_000_000)
756
+ else if (unit === 'k') rawTokens = Math.round(num * 1_000)
757
+ else rawTokens = Math.round(num)
758
+ const tokens = Math.max(COMPACT_TOKEN_HARD_MIN, rawTokens)
759
+ const displayInput = formatCompactTokenShort(tokens)
760
+ const lowWarning = tokens < COMPACT_TOKEN_WARN_FLOOR
761
+ ? `当前阈值(${displayInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
762
+ : ''
763
+ return {
764
+ ok: true,
765
+ tokens,
766
+ rawTokens,
767
+ clampedToMin: rawTokens < COMPACT_TOKEN_HARD_MIN,
768
+ displayInput,
769
+ lowWarning,
770
+ }
771
+ }
772
+
773
+ /** Resolve effective Chief config for a specific root session (isolates `intervention` and `permissionMode` per session). */
774
+ export function resolveWorkspaceConfig(state, sessionId = '') {
775
+ const safeState = state && typeof state === 'object' ? state : {}
776
+ const base = safeState.config && typeof safeState.config === 'object' ? safeState.config : {}
777
+ const baseTactical = normalizeTacticalModes(base.tacticalModes)
778
+ const sid = String(sessionId || '').trim()
779
+ const ws = sid && safeState.workspaces && safeState.workspaces[sid] ? safeState.workspaces[sid] : null
780
+ const wsCfg = ws && ws.config && typeof ws.config === 'object' ? ws.config : null
781
+ const validPaces = ['manual', 'smart', 'auto', 'stopped']
782
+ const basePaceSafe = validPaces.includes(base.paceMode) && !(sid && base.paceMode === 'auto')
783
+ ? base.paceMode
784
+ : 'manual'
785
+ const rawPaceMode = wsCfg && validPaces.includes(wsCfg.paceMode)
786
+ ? wsCfg.paceMode
787
+ : basePaceSafe
788
+ const explicitStopped = wsCfg && typeof wsCfg.stopped === 'boolean'
789
+ ? wsCfg.stopped
790
+ : (typeof base.stopped === 'boolean' ? base.stopped : false)
791
+ const stopped = rawPaceMode === 'stopped' || explicitStopped
792
+ const paceMode = stopped ? 'stopped' : rawPaceMode
793
+ const modelRef = wsCfg && typeof wsCfg.modelRef === 'string'
794
+ ? wsCfg.modelRef.trim()
795
+ : (typeof base.modelRef === 'string' ? base.modelRef.trim() : '')
796
+ const mergedTactical = wsCfg && wsCfg.tacticalModes
797
+ ? normalizeTacticalModes({ ...baseTactical, ...wsCfg.tacticalModes })
798
+ : { ...baseTactical, ...(sid ? { intervention: false } : {}) }
799
+ const ackOk = hasValidChiefRiskAck(ws)
800
+ const rawPerm = (wsCfg && typeof wsCfg.permissionMode === 'string')
801
+ ? wsCfg.permissionMode
802
+ : DEFAULT_CHIEF_PERMISSION_MODE
803
+ const permissionMode = normalizePermissionMode(rawPerm, {
804
+ requireAck: true,
805
+ hasChiefRiskAck: ackOk,
806
+ })
807
+ const chiefRiskVerified = permissionMode === 'chief' ? ackOk : false
808
+ return {
809
+ modelRef,
810
+ paceMode,
811
+ stopped,
812
+ permissionMode,
813
+ chiefRiskVerified,
814
+ autoPilot: !stopped && paceMode === 'auto',
815
+ autoReview: !stopped && paceMode !== 'manual',
816
+ tacticalModes: mergedTactical,
817
+ }
818
+ }
819
+
820
+ const DEFAULT_TACTICAL_MODES = {
821
+ intervention: false,
822
+ autoCompact: false,
823
+ smartCompact: false,
824
+ compactThresholdMode: 'pct',
825
+ compactThresholdPct: 80,
826
+ compactThresholdTokens: 64_000,
827
+ compactThresholdInput: '64K',
828
+ strictVerify: false,
829
+ redlineSentinel: false,
830
+ conciseBrief: false,
831
+ maxInterventionTurns: 10,
832
+ }
833
+
834
+ export function normalizeTacticalModes(raw) {
835
+ const src = raw && typeof raw === 'object' ? raw : {}
836
+ const pct = Math.round(Number(src.compactThresholdPct) || DEFAULT_TACTICAL_MODES.compactThresholdPct)
837
+ const mode = src.compactThresholdMode === 'tokens' ? 'tokens' : 'pct'
838
+ const rawTokens = Math.round(Number(src.compactThresholdTokens) || DEFAULT_TACTICAL_MODES.compactThresholdTokens)
839
+ const compactThresholdTokens = Math.max(COMPACT_TOKEN_HARD_MIN, rawTokens)
840
+ const compactThresholdInput = typeof src.compactThresholdInput === 'string' && src.compactThresholdInput.trim()
841
+ ? src.compactThresholdInput.trim()
842
+ : formatCompactTokenShort(compactThresholdTokens)
843
+ const rawTurns = src.maxInterventionTurns
844
+ const isZeroTurns = rawTurns === 0 || rawTurns === '0'
845
+ const parsedTurns = isZeroTurns
846
+ ? 0
847
+ : Math.min(30, Math.max(1, Math.round(Number(rawTurns) || DEFAULT_TACTICAL_MODES.maxInterventionTurns)))
848
+ return {
849
+ intervention: Boolean(src.intervention),
850
+ autoCompact: Boolean(src.autoCompact),
851
+ smartCompact: Boolean(src.smartCompact),
852
+ compactThresholdMode: mode,
853
+ compactThresholdPct: Math.min(COMPACT_THRESHOLD_MAX_PCT, Math.max(COMPACT_THRESHOLD_MIN_PCT, pct)),
854
+ compactThresholdTokens,
855
+ compactThresholdInput,
856
+ strictVerify: Boolean(src.strictVerify),
857
+ redlineSentinel: Boolean(src.redlineSentinel),
858
+ conciseBrief: Boolean(src.conciseBrief),
859
+ maxInterventionTurns: parsedTurns,
860
+ }
861
+ }
862
+
863
+ function normalizeState(raw) {
864
+ const src = raw && typeof raw === 'object' ? raw : {}
865
+ const cfg = src.config && typeof src.config === 'object' ? src.config : {}
866
+ const links = {}
867
+ if (src.links && typeof src.links === 'object') {
868
+ for (const [k, list] of Object.entries(src.links)) {
869
+ if (!k || !Array.isArray(list)) continue
870
+ const clean = [...new Set(list.map(v => String(v || '').trim()).filter(v => v && v !== k))]
871
+ if (clean.length) links[k] = clean
872
+ }
873
+ }
874
+ const workspaces = {}
875
+ if (src.workspaces && typeof src.workspaces === 'object') {
876
+ for (const [k, ws] of Object.entries(src.workspaces)) {
877
+ if (!k) continue
878
+ workspaces[k] = normalizeWorkspace(ws)
879
+ }
880
+ }
881
+ const validPaces = ['manual', 'smart', 'auto', 'stopped']
882
+ // Default to 'manual' (human-paced, zero background token burn) unless explicitly set to smart/auto
883
+ const rawPace = validPaces.includes(cfg.paceMode) ? cfg.paceMode : 'manual'
884
+ const stopped = rawPace === 'stopped' || Boolean(cfg.stopped)
885
+ const paceMode = stopped ? 'stopped' : rawPace
886
+ return {
887
+ version: STATE_VERSION,
888
+ config: {
889
+ modelRef: typeof cfg.modelRef === 'string' ? cfg.modelRef.trim() : '',
890
+ paceMode,
891
+ stopped,
892
+ permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
893
+ autoPilot: !stopped && paceMode === 'auto',
894
+ autoReview: !stopped && paceMode !== 'manual',
895
+ tacticalModes: normalizeTacticalModes(cfg.tacticalModes),
896
+ },
897
+ links,
898
+ workspaces,
899
+ }
900
+ }
901
+
902
+ export function appendChiefAuditLog(sessionId = 'global', entry = {}) {
903
+ const rootId = String(sessionId || 'global').trim() || 'global'
904
+ return mutateChiefState((state) => {
905
+ const ws = ensureWorkspace(state, rootId)
906
+ return pushAuditToWs(ws, entry, rootId)
907
+ })
908
+ }
909
+
910
+ export function enqueueApprovalToWs(ws, item = {}) {
911
+ if (!ws || typeof ws !== 'object') return null
912
+ if (!Array.isArray(ws.pendingApprovals)) ws.pendingApprovals = []
913
+ const dKey = clamp(item.dedupeKey || '', 120)
914
+ if (dKey) {
915
+ const existing = ws.pendingApprovals.find(a => a && a.status === 'pending' && a.dedupeKey === dKey)
916
+ if (existing) return existing
917
+ }
918
+ const kind = item.kind || 'tool'
919
+ const payload = item.payload && typeof item.payload === 'object' ? item.payload : {}
920
+ const now = Date.now()
921
+ const norm = normalizePendingApproval({
922
+ ...item,
923
+ status: 'pending',
924
+ dedupeKey: dKey,
925
+ payloadHash: computeApprovalPayloadHash(kind, payload),
926
+ expiresAt: Number(item.expiresAt) || (now + DEFAULT_RESUME_TTL_MS),
927
+ })
928
+ if (!norm) return null
929
+ ws.pendingApprovals.push(norm)
930
+ if (ws.pendingApprovals.length > APPROVALS_CAP) {
931
+ ws.pendingApprovals = ws.pendingApprovals.slice(-APPROVALS_CAP)
932
+ }
933
+ return norm
934
+ }
935
+
936
+ export function queueChiefApproval(sessionId = 'global', item = {}) {
937
+ const rootId = String(sessionId || 'global').trim() || 'global'
938
+ return mutateChiefState((state) => {
939
+ const ws = ensureWorkspace(state, rootId)
940
+ return enqueueApprovalToWs(ws, item)
941
+ })
942
+ }
943
+
944
+ export function enqueueElevationToWs(ws, req = {}) {
945
+ if (!ws || typeof ws !== 'object') return null
946
+ const currentMode = normalizePermissionMode(
947
+ ws.config && ws.config.permissionMode ? ws.config.permissionMode : DEFAULT_CHIEF_PERMISSION_MODE,
948
+ { requireAck: true, hasChiefRiskAck: hasValidChiefRiskAck(ws) },
949
+ )
950
+ const targetMode = normalizePermissionMode(req.targetMode || 'strategist')
951
+ if (permissionRank(targetMode) <= permissionRank(currentMode)) return null
952
+ const now = Date.now()
953
+ const norm = normalizePendingElevation({
954
+ fromMode: currentMode,
955
+ targetMode,
956
+ reason: req.reason || 'Agent 申请提升权限以继续当前任务',
957
+ requestedActionSummary: req.requestedActionSummary || '',
958
+ resumeTaskId: req.resumeTaskId || '',
959
+ expiresAt: Number(req.expiresAt) || (now + DEFAULT_RESUME_TTL_MS),
960
+ by: req.by || 'chief',
961
+ })
962
+ if (!norm) return null
963
+ ws.pendingElevation = norm
964
+ pushAuditToWs(ws, {
965
+ mode: currentMode,
966
+ stage: 'permission_gate',
967
+ decision: 'elevation_requested',
968
+ operation: '申请提权',
969
+ target: `${CHIEF_PERMISSION_META[currentMode].level} -> ${CHIEF_PERMISSION_META[targetMode].level}`,
970
+ reason: norm.reason,
971
+ outcome: 'pending',
972
+ by: norm.by,
973
+ }, req.sessionId || '')
974
+ return norm
975
+ }
976
+
977
+ export function requestChiefElevation(sessionId = 'global', req = {}) {
978
+ const rootId = String(sessionId || 'global').trim() || 'global'
979
+ return mutateChiefState((state) => {
980
+ const ws = ensureWorkspace(state, rootId)
981
+ return enqueueElevationToWs(ws, { ...(req && typeof req === 'object' ? req : {}), sessionId: rootId })
982
+ })
983
+ }
984
+
985
+ export function upsertResumeTaskOnWs(ws, rawTask = {}) {
986
+ if (!ws || typeof ws !== 'object') return null
987
+ if (!Array.isArray(ws.resumeTasks)) ws.resumeTasks = []
988
+ const existingIdx = rawTask.id ? ws.resumeTasks.findIndex(t => t && t.id === rawTask.id) : -1
989
+ if (existingIdx >= 0) {
990
+ const prev = ws.resumeTasks[existingIdx]
991
+ const merged = normalizeResumeTask({
992
+ ...prev,
993
+ ...rawTask,
994
+ completedActions: rawTask.appendCompletedAction
995
+ ? [...(prev.completedActions || []), rawTask.appendCompletedAction]
996
+ : (rawTask.completedActions || prev.completedActions),
997
+ pendingApprovalIds: rawTask.pendingApprovalIds || prev.pendingApprovalIds,
998
+ })
999
+ if (merged) ws.resumeTasks[existingIdx] = merged
1000
+ return merged
1001
+ }
1002
+ const created = normalizeResumeTask(rawTask)
1003
+ if (!created) return null
1004
+ ws.resumeTasks.push(created)
1005
+ if (ws.resumeTasks.length > RESUME_TASKS_CAP) {
1006
+ ws.resumeTasks = ws.resumeTasks.slice(-RESUME_TASKS_CAP)
1007
+ }
1008
+ return created
1009
+ }
1010
+
1011
+ const STATE_LOCK_WAIT_MS = 10000
1012
+
1013
+ const STATE_LOCK_STALE_MS = 15000
1014
+
1015
+ const STATE_LOCK_CONTENDED_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY'])
1016
+
1017
+ const heldStateLocks = new Set()
1018
+
1019
+ const stateLockSleeper = new Int32Array(new SharedArrayBuffer(4))
1020
+
1021
+ function sleepStateLockSync(ms) {
1022
+ try {
1023
+ Atomics.wait(stateLockSleeper, 0, 0, ms)
1024
+ } catch {}
1025
+ }
1026
+
1027
+ /** Cross-process O_EXCL lock around `chief-state.json` read-modify-write cycles (fixes red-team E1). */
1028
+ function acquireStateLock(file = stateFilePath()) {
1029
+ if (heldStateLocks.has(file)) return () => {}
1030
+ const lock = file + '.lock'
1031
+ try {
1032
+ fs.mkdirSync(path.dirname(lock), { recursive: true })
1033
+ } catch {}
1034
+ const deadline = Date.now() + STATE_LOCK_WAIT_MS
1035
+ for (;;) {
1036
+ try {
1037
+ const fd = fs.openSync(lock, 'wx')
1038
+ try {
1039
+ fs.writeSync(fd, `${process.pid}:${threadId}`)
1040
+ } catch {}
1041
+ fs.closeSync(fd)
1042
+ heldStateLocks.add(file)
1043
+ return () => {
1044
+ heldStateLocks.delete(file)
1045
+ try {
1046
+ fs.unlinkSync(lock)
1047
+ } catch {}
1048
+ }
1049
+ } catch (error) {
1050
+ const code = error && error.code
1051
+ if (code === 'ENOENT' && Date.now() < deadline) {
1052
+ try {
1053
+ fs.mkdirSync(path.dirname(lock), { recursive: true })
1054
+ } catch {}
1055
+ sleepStateLockSync(2)
1056
+ continue
1057
+ }
1058
+ if (!error || !STATE_LOCK_CONTENDED_CODES.has(code)) {
1059
+ heldStateLocks.add(file)
1060
+ return () => heldStateLocks.delete(file)
1061
+ }
1062
+ if (Date.now() >= deadline) {
1063
+ try {
1064
+ fs.unlinkSync(lock)
1065
+ } catch {}
1066
+ heldStateLocks.add(file)
1067
+ return () => heldStateLocks.delete(file)
1068
+ }
1069
+ if (code === 'EEXIST') {
1070
+ try {
1071
+ const stat = fs.statSync(lock)
1072
+ if (Date.now() - stat.mtimeMs > STATE_LOCK_STALE_MS) {
1073
+ fs.unlinkSync(lock)
1074
+ continue
1075
+ }
1076
+ } catch {}
1077
+ }
1078
+ sleepStateLockSync(2 + Math.floor(Math.random() * 4))
1079
+ }
1080
+ }
1081
+ }
1082
+
1083
+ export function withChiefStateLock(fn) {
1084
+ const file = stateFilePath()
1085
+ const release = acquireStateLock(file)
1086
+ try {
1087
+ return fn()
1088
+ } finally {
1089
+ release()
1090
+ }
1091
+ }
1092
+
1093
+ let cachedState = null
1094
+
1095
+ let cachedMtime = 0
1096
+
1097
+ export function loadChiefState({ forceDisk = false } = {}) {
1098
+ const file = stateFilePath()
1099
+ try {
1100
+ const stat = fs.statSync(file)
1101
+ if (!forceDisk && cachedState && stat.mtimeMs === cachedMtime) return cachedState
1102
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
1103
+ cachedState = normalizeState(parsed)
1104
+ cachedMtime = stat.mtimeMs
1105
+ return cachedState
1106
+ } catch {
1107
+ if (forceDisk) {
1108
+ cachedState = normalizeState({})
1109
+ cachedMtime = -1
1110
+ return cachedState
1111
+ }
1112
+ if (!cachedState) cachedState = normalizeState({})
1113
+ return cachedState
1114
+ }
1115
+ }
1116
+
1117
+ export function saveChiefState(state) {
1118
+ const normalized = normalizeState(state)
1119
+ const file = stateFilePath()
1120
+ try {
1121
+ fs.mkdirSync(path.dirname(file), { recursive: true })
1122
+ const tmp = `${file}.${process.pid}.${threadId}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 6)}.tmp`
1123
+ fs.writeFileSync(tmp, JSON.stringify(normalized, null, 2), 'utf8')
1124
+ let renameErr = null
1125
+ for (let attempt = 0; attempt < 8; attempt += 1) {
1126
+ try {
1127
+ fs.renameSync(tmp, file)
1128
+ renameErr = null
1129
+ break
1130
+ } catch (err) {
1131
+ renameErr = err
1132
+ const code = err && err.code
1133
+ if (code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') break
1134
+ sleepStateLockSync(2 + attempt * 2)
1135
+ }
1136
+ }
1137
+ if (renameErr) {
1138
+ try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp) } catch {}
1139
+ throw renameErr
1140
+ }
1141
+ try {
1142
+ cachedMtime = fs.statSync(file).mtimeMs
1143
+ } catch {
1144
+ cachedMtime = -1
1145
+ }
1146
+ } catch {}
1147
+ cachedState = normalized
1148
+ return normalized
1149
+ }
1150
+
1151
+ export function mutateChiefState(mutator) {
1152
+ return withChiefStateLock(() => {
1153
+ const state = loadChiefState({ forceDisk: true })
1154
+ const result = mutator(state)
1155
+ saveChiefState(state)
1156
+ return result
1157
+ })
1158
+ }
1159
+
1160
+ /** Find connected component of linked root sessions (undirected graph). */
1161
+ export function getLinkedCluster(state, rootSessionId) {
1162
+ const seed = String(rootSessionId || '').trim()
1163
+ if (!seed) return ['global']
1164
+ const visited = new Set([seed])
1165
+ const queue = [seed]
1166
+ const links = (state && state.links) || {}
1167
+ while (queue.length > 0) {
1168
+ const cur = queue.shift()
1169
+ const direct = Array.isArray(links[cur]) ? links[cur] : []
1170
+ for (const peer of direct) {
1171
+ if (peer && !visited.has(peer)) {
1172
+ visited.add(peer)
1173
+ queue.push(peer)
1174
+ }
1175
+ }
1176
+ for (const [other, list] of Object.entries(links)) {
1177
+ if (Array.isArray(list) && list.includes(cur) && !visited.has(other)) {
1178
+ visited.add(other)
1179
+ queue.push(other)
1180
+ }
1181
+ }
1182
+ }
1183
+ return [...visited].sort()
1184
+ }
1185
+
1186
+ export function computeClusterSig(cluster = []) {
1187
+ return [...new Set((Array.isArray(cluster) ? cluster : []).map(x => String(x || '').trim()).filter(Boolean))].sort().join('|')
1188
+ }
1189
+
1190
+ export function setPeerLink(rootA, rootB, linked) {
1191
+ const a = String(rootA || '').trim()
1192
+ const b = String(rootB || '').trim()
1193
+ if (!a || !b || a === b) return { ok: false, error: '需要两个不同的主会话才能建立协同连接' }
1194
+ return mutateChiefState((state) => {
1195
+ const affected = new Set([
1196
+ ...getLinkedCluster(state, a),
1197
+ ...getLinkedCluster(state, b),
1198
+ ])
1199
+ const setA = new Set(state.links[a] || [])
1200
+ const setB = new Set(state.links[b] || [])
1201
+ if (linked) {
1202
+ setA.add(b)
1203
+ setB.add(a)
1204
+ } else {
1205
+ setA.delete(b)
1206
+ setB.delete(a)
1207
+ }
1208
+ if (setA.size) state.links[a] = [...setA]
1209
+ else delete state.links[a]
1210
+ if (setB.size) state.links[b] = [...setB]
1211
+ else delete state.links[b]
1212
+
1213
+ // Topology isolation guard: purge stale narrative caches on EVERY affected session whose cluster changed
1214
+ // so detaching from a peer cluster NEVER leaves residual peer context inside Chief's narrative digest!
1215
+ const now = Date.now()
1216
+ for (const sid of affected) {
1217
+ const ws = ensureWorkspace(state, sid)
1218
+ const nextCluster = getLinkedCluster(state, sid)
1219
+ const nextSig = computeClusterSig(nextCluster)
1220
+ if (!ws.narrative || ws.narrative.clusterSig !== nextSig) {
1221
+ ws.narrative = { hash: '', text: '', at: 0, byModel: '', clusterSig: nextSig }
1222
+ }
1223
+ if (!linked) {
1224
+ ws.seenFactsAt = { [sid]: now }
1225
+ } else {
1226
+ ws.seenFactsAt = {}
1227
+ }
1228
+ }
1229
+ return { ok: true, cluster: getLinkedCluster(state, a) }
1230
+ })
1231
+ }
1232
+
1233
+ export function ensureWorkspace(state, rootId) {
1234
+ const key = String(rootId || 'global').trim() || 'global'
1235
+ if (!state.workspaces[key]) state.workspaces[key] = emptyWorkspace()
1236
+ return state.workspaces[key]
1237
+ }
1238
+
1239
+ function filterFactsForCluster(rawFacts, clusterSet, rootId) {
1240
+ return (Array.isArray(rawFacts) ? rawFacts : []).filter((f) => {
1241
+ if (!f || !f.text) return false
1242
+ if (f.originRootId && !clusterSet.has(f.originRootId)) return false
1243
+ if (f.category === 'team' && Array.isArray(f.peerRootIds) && f.peerRootIds.length > 0) {
1244
+ // A team fact created during multi-session collaboration stays ONLY if another participant besides rootId remains linked
1245
+ const participants = f.originRootId ? [f.originRootId, ...f.peerRootIds] : f.peerRootIds
1246
+ const peerStillLinked = participants.some(pid => pid && pid !== rootId && clusterSet.has(pid))
1247
+ if (!peerStillLinked) return false
1248
+ }
1249
+ return true
1250
+ })
1251
+ }
1252
+
1253
+ function annotateMailClusterState(mail, clusterSet) {
1254
+ if (!mail || typeof mail !== 'object') return mail
1255
+ const fromOut = Boolean(mail.fromRootId && !clusterSet.has(mail.fromRootId))
1256
+ const toOut = Boolean(mail.toRootId && mail.toRootId !== 'all' && !clusterSet.has(mail.toRootId))
1257
+ const detachedFromCluster = fromOut || toOut
1258
+ return detachedFromCluster ? { ...mail, detachedFromCluster: true } : mail
1259
+ }
1260
+
1261
+ /** Merge facts & mailbox across all linked peer sessions in the federation cluster, isolating detached artifacts. */
1262
+ export function clusterView(state, rootId) {
1263
+ const cluster = getLinkedCluster(state, rootId)
1264
+ const clusterSig = computeClusterSig(cluster)
1265
+ const clusterSet = new Set(cluster)
1266
+ const primary = ensureWorkspace(state, rootId)
1267
+ if (cluster.length <= 1) {
1268
+ return {
1269
+ cluster,
1270
+ clusterSig,
1271
+ primary,
1272
+ facts: filterFactsForCluster(primary.facts, clusterSet, rootId),
1273
+ mailbox: (primary.mailbox || []).map(m => annotateMailClusterState(m, clusterSet)),
1274
+ suggestions: primary.suggestions.filter(s => s.status === 'pending'),
1275
+ chat: primary.chat,
1276
+ narrative: primary.narrative,
1277
+ }
1278
+ }
1279
+ const factMap = new Map()
1280
+ const mailMap = new Map()
1281
+ for (const sid of cluster) {
1282
+ const ws = ensureWorkspace(state, sid)
1283
+ for (const f of filterFactsForCluster(ws.facts, clusterSet, rootId)) factMap.set(f.id, f)
1284
+ for (const m of ws.mailbox) {
1285
+ if (m && m.broadcastId && m.channelType === 'broadcast') {
1286
+ mailMap.set('bcast:' + m.broadcastId, annotateMailClusterState(m, clusterSet))
1287
+ } else {
1288
+ mailMap.set(m.id, annotateMailClusterState(m, clusterSet))
1289
+ }
1290
+ }
1291
+ }
1292
+ const facts = [...factMap.values()].sort((a, b) => (a.addedAt || 0) - (b.addedAt || 0)).slice(-FACTS_CAP)
1293
+ const mailbox = [...mailMap.values()].sort((a, b) => (a.at || 0) - (b.at || 0)).slice(-MAIL_CAP)
1294
+ return {
1295
+ cluster,
1296
+ clusterSig,
1297
+ primary,
1298
+ facts,
1299
+ mailbox,
1300
+ suggestions: primary.suggestions.filter(s => s.status === 'pending'),
1301
+ chat: primary.chat,
1302
+ narrative: primary.narrative,
1303
+ }
1304
+ }
1305
+
1306
+ /* -------------------------------------------------------------------------- */
1307
+ /* Model Catalog & Auxiliary LLM Caller */
1308
+ /* -------------------------------------------------------------------------- */
1309
+
1310
+ /** Manage which cold precipitated-vault entries are explicitly unsealed/flipped into a single root session. */
1311
+ export function updateWorkspaceFlippedIds(sessionId, { flippedId = '', sealId = '', clearAll = false } = {}) {
1312
+ const key = String(sessionId || 'global').trim() || 'global'
1313
+ return mutateChiefState((state) => {
1314
+ const ws = ensureWorkspace(state, key)
1315
+ const set = new Set(ws.flippedPrecipitatedIds || [])
1316
+ if (clearAll) {
1317
+ set.clear()
1318
+ } else {
1319
+ if (flippedId) set.add(String(flippedId).trim())
1320
+ if (sealId) set.delete(String(sealId).trim())
1321
+ }
1322
+ ws.flippedPrecipitatedIds = [...set].slice(-20)
1323
+ return { ok: true, flippedPrecipitatedIds: ws.flippedPrecipitatedIds.slice() }
1324
+ })
1325
+ }
1326
+
1327
+ /** One-click system deployment of Chief state (`facts`, `narrative`, `chat`/`mailbox` bridge) to a target Chief workspace (strictly keeping `flippedPrecipitatedIds = []`). */
1328
+ export function deployChiefWorkspaceState(deps, {
1329
+ fromRootId = '',
1330
+ toRootId = '',
1331
+ fromTitle = '',
1332
+ customText = '',
1333
+ objective = '',
1334
+ } = {}) {
1335
+ const fromKey = String(fromRootId || 'global').trim() || 'global'
1336
+ const toKey = String(toRootId || '').trim()
1337
+ if (!toKey) return { ok: false, error: '目标会话 ID 不能为空' }
1338
+
1339
+ return mutateChiefState((state) => {
1340
+ const fromWs = ensureWorkspace(state, fromKey)
1341
+ const toWs = ensureWorkspace(state, toKey)
1342
+
1343
+ const existingTexts = new Set(toWs.facts.map(f => f.text.trim()))
1344
+ let copiedFacts = 0
1345
+ for (const f of fromWs.facts) {
1346
+ if (!f || !f.text) continue
1347
+ const norm = f.text.trim()
1348
+ if (existingTexts.has(norm)) continue
1349
+ existingTexts.add(norm)
1350
+ toWs.facts.push({
1351
+ ...f,
1352
+ id: nextId('fact'),
1353
+ originRootId: toKey === 'global' ? (f.originRootId || '') : toKey,
1354
+ peerRootIds: [],
1355
+ source: f.source || `移交自 ${fromTitle || fromKey}`,
1356
+ updatedAt: Date.now(),
1357
+ })
1358
+ copiedFacts += 1
1359
+ }
1360
+ if (toWs.facts.length > FACTS_CAP) {
1361
+ const pinned = toWs.facts.filter(f => f.pinned)
1362
+ const rest = toWs.facts.filter(f => !f.pinned).slice(-(FACTS_CAP - pinned.length))
1363
+ toWs.facts = [...pinned, ...rest].slice(-FACTS_CAP)
1364
+ }
1365
+
1366
+ if (fromWs.narrative && fromWs.narrative.text && !toWs.narrative.text) {
1367
+ toWs.narrative = {
1368
+ ...fromWs.narrative,
1369
+ hash: fromWs.narrative.hash || '',
1370
+ clusterSig: toKey,
1371
+ at: Date.now(),
1372
+ }
1373
+ }
1374
+
1375
+ const briefLines = [
1376
+ `- 【跨会话接力部署】本会话参谋状态已自 **${fromTitle || fromKey}** 系统级一键移交部署完成(新对话默认以 **L0 · 顾问模式** 安全启动)。`,
1377
+ objective ? `- 【继承总目标】${clamp(objective, 180)}` : '',
1378
+ copiedFacts > 0 ? `- 【继承纪律与事实】共继承 **${copiedFacts} 条**核心记忆与纪律。` : '',
1379
+ customText ? `- 【附带交接叮嘱】${clamp(customText, 240)}` : '',
1380
+ ].filter(Boolean).join('\n')
1381
+
1382
+ const mailItem = normalizeMail({
1383
+ id: nextId('mail'),
1384
+ from: 'DSH 参谋长 (接力部署)',
1385
+ fromSession: fromKey,
1386
+ to: 'lead',
1387
+ toSession: toKey,
1388
+ subject: `跨会话参谋部署:自 ${fromTitle || fromKey}`,
1389
+ text: briefLines,
1390
+ mode: 'silent',
1391
+ deliveredPhysical: false,
1392
+ at: Date.now(),
1393
+ })
1394
+ if (mailItem) {
1395
+ toWs.mailbox.push(mailItem)
1396
+ if (toWs.mailbox.length > MAIL_CAP) toWs.mailbox = toWs.mailbox.slice(-MAIL_CAP)
1397
+ }
1398
+
1399
+ toWs.chat.push({
1400
+ id: nextId('chat'),
1401
+ role: 'chief',
1402
+ text: briefLines,
1403
+ actions: ['系统接力部署', '默认 L0 顾问', ...(copiedFacts > 0 ? [`继承记忆 ×${copiedFacts}`] : [])],
1404
+ at: Date.now(),
1405
+ })
1406
+ if (toWs.chat.length > CHAT_CAP) toWs.chat = toWs.chat.slice(-CHAT_CAP)
1407
+
1408
+ // Clone safe workspace chief config (model, pace, tactical preferences), ALWAYS forcing intervention=false & L0 advisor!
1409
+ const fromCfg = resolveWorkspaceConfig(state, fromKey)
1410
+ toWs.config = {
1411
+ modelRef: fromCfg.modelRef || '',
1412
+ paceMode: fromCfg.paceMode || 'manual',
1413
+ permissionMode: DEFAULT_CHIEF_PERMISSION_MODE,
1414
+ autoPilot: Boolean(fromCfg.autoPilot),
1415
+ autoReview: Boolean(fromCfg.autoReview),
1416
+ tacticalModes: {
1417
+ ...normalizeTacticalModes(fromCfg.tacticalModes),
1418
+ intervention: false,
1419
+ },
1420
+ }
1421
+ toWs.chiefRiskAck = null
1422
+ toWs.pendingApprovals = []
1423
+ toWs.pendingElevation = null
1424
+ pushAuditToWs(toWs, {
1425
+ mode: DEFAULT_CHIEF_PERMISSION_MODE,
1426
+ stage: 'deploy',
1427
+ decision: 'reset_to_l0',
1428
+ operation: '跨会话接力部署',
1429
+ target: toKey,
1430
+ reason: '新对话强制从最低档 L0 顾问模式安全启动并清空高权限状态',
1431
+ outcome: 'ok',
1432
+ by: 'deploy',
1433
+ })
1434
+ toWs.runtimeGuard.interventionTurns = 0
1435
+ toWs.runtimeGuard.unchangedCount = 0
1436
+ toWs.runtimeGuard.circuitBroken = false
1437
+ toWs.runtimeGuard.circuitReason = ''
1438
+
1439
+ // Strictly keep precipitated cold vault isolated at 0-token default in destination session!
1440
+ toWs.flippedPrecipitatedIds = []
1441
+
1442
+ return {
1443
+ ok: true,
1444
+ copiedFacts,
1445
+ narrativeCopied: Boolean(fromWs.narrative && fromWs.narrative.text),
1446
+ flippedPrecipitatedIds: [],
1447
+ config: { ...toWs.config, tacticalModes: { ...toWs.config.tacticalModes } },
1448
+ }
1449
+ })
1450
+ }
1451
+
1452
+ /* -------------------------------------------------------------------------- */
1453
+ /* Chief Command Bar: All-Seeing Strategist + Relay + Bounds + Board Ops */
1454
+ /* -------------------------------------------------------------------------- */
1455
+
1456
+ export function updateChiefConfig(patch) {
1457
+ const safePatch = patch && typeof patch === 'object' ? patch : {}
1458
+ const sid = String(safePatch.sessionId || safePatch.session || '').trim() || 'global'
1459
+ return mutateChiefState((state) => {
1460
+ const ws = ensureWorkspace(state, sid)
1461
+ const effBefore = resolveWorkspaceConfig(state, sid)
1462
+ const prevTactical = normalizeTacticalModes(effBefore.tacticalModes)
1463
+ if (typeof safePatch.ackHazardAlertId === 'string' && safePatch.ackHazardAlertId.trim()) {
1464
+ const ackId = safePatch.ackHazardAlertId.trim()
1465
+ if (ws && ws.runtimeGuard && ws.runtimeGuard.hazardAlert && (ackId === '*' || ws.runtimeGuard.hazardAlert.id === ackId)) {
1466
+ ws.runtimeGuard.hazardAlert = null
1467
+ }
1468
+ const hasOtherKeys = Object.keys(safePatch).some(
1469
+ k => k !== 'sessionId' && k !== 'session' && k !== 'ackHazardAlertId',
1470
+ )
1471
+ if (!hasOtherKeys) {
1472
+ const curCfg = resolveWorkspaceConfig(state, sid)
1473
+ return {
1474
+ ok: true,
1475
+ clearedHazardAlert: true,
1476
+ config: { ...curCfg, tacticalModes: { ...curCfg.tacticalModes } },
1477
+ runtimeGuard: ws ? { ...ws.runtimeGuard } : null,
1478
+ }
1479
+ }
1480
+ }
1481
+
1482
+ if (safePatch.emergencyStopIntervention === true) {
1483
+ if (ws) {
1484
+ if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effBefore }
1485
+ ws.config.tacticalModes = { ...normalizeTacticalModes(ws.config.tacticalModes), intervention: false }
1486
+ ws.runtimeGuard.interventionTurns = 0
1487
+ ws.runtimeGuard.unchangedCount = 0
1488
+ ws.runtimeGuard.circuitBroken = false
1489
+ ws.runtimeGuard.circuitReason = ''
1490
+ ws.runtimeGuard.hazardAlert = null
1491
+ }
1492
+ state.config.tacticalModes = { ...normalizeTacticalModes(state.config.tacticalModes), intervention: false }
1493
+ const stoppedCfg = resolveWorkspaceConfig(state, sid)
1494
+ return {
1495
+ ok: true,
1496
+ emergencyStopped: true,
1497
+ config: { ...stoppedCfg, tacticalModes: { ...stoppedCfg.tacticalModes } },
1498
+ runtimeGuard: ws ? { ...ws.runtimeGuard } : null,
1499
+ }
1500
+ }
1501
+
1502
+ // Check explicit permission mode transition BEFORE applying any changes
1503
+ let normalizedReqPerm = ''
1504
+ if (typeof safePatch.permissionMode === 'string' && safePatch.permissionMode.trim()) {
1505
+ normalizedReqPerm = normalizePermissionMode(safePatch.permissionMode)
1506
+ if (normalizedReqPerm === 'chief' && safePatch.confirmedChiefRisk !== true && !hasValidChiefRiskAck(ws)) {
1507
+ pushAuditToWs(ws, {
1508
+ mode: effBefore.permissionMode,
1509
+ stage: 'permission_gate',
1510
+ decision: 'deny_unacknowledged_l3',
1511
+ operation: '切换 L3 参谋长模式',
1512
+ target: sid,
1513
+ reason: '未阅读并勾选确认高权限风险告知(confirmedChiefRisk: true)',
1514
+ outcome: 'denied',
1515
+ by: 'operator',
1516
+ })
1517
+ return {
1518
+ ok: false,
1519
+ requireChiefRiskConfirm: true,
1520
+ error: '启用「L3 · 参谋长模式」前必须阅读高权限风险告知并主动勾选确认(confirmedChiefRisk: true)',
1521
+ }
1522
+ }
1523
+ }
1524
+
1525
+ const incomingTacticalRaw = safePatch.tacticalModes && typeof safePatch.tacticalModes === 'object'
1526
+ ? safePatch.tacticalModes
1527
+ : null
1528
+ let incomingTactical = incomingTacticalRaw ? { ...incomingTacticalRaw } : null
1529
+ if (incomingTactical && incomingTactical.intervention === true && !prevTactical.intervention) {
1530
+ if (safePatch.confirmedInterventionRisk !== true) {
1531
+ return {
1532
+ ok: false,
1533
+ error: '开启「接管督导模式」需先确认双项风险免责声明(confirmedInterventionRisk: true)',
1534
+ }
1535
+ }
1536
+ if (ws) {
1537
+ ws.runtimeGuard.interventionTurns = 0
1538
+ ws.runtimeGuard.unchangedCount = 0
1539
+ ws.runtimeGuard.circuitBroken = false
1540
+ ws.runtimeGuard.circuitReason = ''
1541
+ ws.runtimeGuard.hazardAlert = null
1542
+ ws.runtimeGuard.lastGoalAchievedSig = ''
1543
+ }
1544
+ }
1545
+
1546
+ const wantsUnlimitedTurns = Boolean(
1547
+ incomingTactical
1548
+ && (incomingTactical.maxInterventionTurns === 0 || incomingTactical.maxInterventionTurns === '0')
1549
+ )
1550
+ if (wantsUnlimitedTurns && prevTactical.maxInterventionTurns !== 0 && safePatch.confirmedUnlimitedTurns !== true) {
1551
+ return {
1552
+ ok: false,
1553
+ error: '切换至「♾️ 无限督导轮次」需先通过作者风险确认弹窗(confirmedUnlimitedTurns: true)',
1554
+ }
1555
+ }
1556
+
1557
+ const wantsAutoPilot = Boolean(
1558
+ safePatch.paceMode === 'auto'
1559
+ || (typeof safePatch.paceMode !== 'string' && safePatch.stopped !== true && safePatch.autoPilot === true)
1560
+ )
1561
+ if (wantsAutoPilot && effBefore.paceMode !== 'auto' && safePatch.confirmedAutoPilot !== true) {
1562
+ return {
1563
+ ok: false,
1564
+ requireAutoPilotConfirm: true,
1565
+ error: '开启「⚡ 全自动托管」需先确认本会话自治范围与防空转退出弹窗(confirmedAutoPilot: true)',
1566
+ }
1567
+ }
1568
+ if (ws && wantsAutoPilot && effBefore.paceMode !== 'auto') {
1569
+ ws.runtimeGuard.autoPilotStartedAt = Date.now()
1570
+ ws.runtimeGuard.autoPilotHadTurn = false
1571
+ }
1572
+
1573
+ let compactLowWarning = ''
1574
+ if (incomingTactical && typeof incomingTactical.compactThresholdInput === 'string') {
1575
+ const parsedTok = parseCompactTokensInput(incomingTactical.compactThresholdInput)
1576
+ if (!parsedTok.ok) {
1577
+ return { ok: false, error: parsedTok.error }
1578
+ }
1579
+ incomingTactical.compactThresholdTokens = parsedTok.tokens
1580
+ incomingTactical.compactThresholdInput = parsedTok.displayInput
1581
+ compactLowWarning = parsedTok.lowWarning || ''
1582
+ } else if (incomingTactical && typeof incomingTactical.compactThresholdTokens === 'number') {
1583
+ const safeTok = Math.max(COMPACT_TOKEN_HARD_MIN, Math.round(incomingTactical.compactThresholdTokens))
1584
+ incomingTactical.compactThresholdTokens = safeTok
1585
+ incomingTactical.compactThresholdInput = formatCompactTokenShort(safeTok)
1586
+ if (safeTok < COMPACT_TOKEN_WARN_FLOOR) {
1587
+ compactLowWarning = `当前阈值(${incomingTactical.compactThresholdInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
1588
+ }
1589
+ }
1590
+
1591
+ const applyPatchTo = (targetCfg, allowIntervention, allowAutoPilot = allowIntervention, allowPermSync = false) => {
1592
+ if (typeof safePatch.modelRef === 'string') targetCfg.modelRef = safePatch.modelRef.trim()
1593
+ if (allowPermSync && normalizedReqPerm) {
1594
+ targetCfg.permissionMode = normalizedReqPerm
1595
+ }
1596
+ if (typeof safePatch.paceMode === 'string' && ['manual', 'smart', 'auto', 'stopped'].includes(safePatch.paceMode)) {
1597
+ const nextPace = (!allowAutoPilot && safePatch.paceMode === 'auto') ? 'manual' : safePatch.paceMode
1598
+ targetCfg.paceMode = nextPace
1599
+ const isStopped = nextPace === 'stopped'
1600
+ targetCfg.stopped = isStopped
1601
+ targetCfg.autoPilot = !isStopped && nextPace === 'auto' && allowAutoPilot
1602
+ targetCfg.autoReview = !isStopped && nextPace !== 'manual'
1603
+ } else if (typeof safePatch.stopped === 'boolean') {
1604
+ targetCfg.stopped = safePatch.stopped
1605
+ if (safePatch.stopped) {
1606
+ targetCfg.paceMode = 'stopped'
1607
+ targetCfg.autoPilot = false
1608
+ targetCfg.autoReview = false
1609
+ } else {
1610
+ if (targetCfg.paceMode === 'stopped') targetCfg.paceMode = 'manual'
1611
+ if (!allowAutoPilot && targetCfg.paceMode === 'auto') targetCfg.paceMode = 'manual'
1612
+ targetCfg.autoPilot = targetCfg.paceMode === 'auto' && allowAutoPilot
1613
+ targetCfg.autoReview = targetCfg.paceMode !== 'manual'
1614
+ }
1615
+ } else if (typeof safePatch.autoPilot === 'boolean') {
1616
+ const nextAuto = Boolean(safePatch.autoPilot && allowAutoPilot)
1617
+ targetCfg.stopped = false
1618
+ targetCfg.paceMode = nextAuto ? 'auto' : 'manual'
1619
+ targetCfg.autoPilot = nextAuto
1620
+ targetCfg.autoReview = nextAuto
1621
+ }
1622
+ if (!allowAutoPilot && targetCfg.paceMode === 'auto') {
1623
+ targetCfg.paceMode = 'manual'
1624
+ targetCfg.autoPilot = false
1625
+ }
1626
+ if (typeof safePatch.autoReview === 'boolean' && typeof safePatch.paceMode !== 'string' && typeof safePatch.stopped !== 'boolean') {
1627
+ targetCfg.autoReview = safePatch.autoReview
1628
+ if (!safePatch.autoReview) {
1629
+ targetCfg.stopped = false
1630
+ targetCfg.paceMode = 'manual'
1631
+ }
1632
+ }
1633
+ if (incomingTactical) {
1634
+ const merged = normalizeTacticalModes({
1635
+ ...normalizeTacticalModes(targetCfg.tacticalModes),
1636
+ ...incomingTactical,
1637
+ })
1638
+ if (!allowIntervention) merged.intervention = false
1639
+ targetCfg.tacticalModes = merged
1640
+ } else if (!allowIntervention && targetCfg.tacticalModes) {
1641
+ targetCfg.tacticalModes = { ...normalizeTacticalModes(targetCfg.tacticalModes), intervention: false }
1642
+ }
1643
+ }
1644
+
1645
+ if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effBefore }
1646
+ applyPatchTo(ws.config, true, true, true)
1647
+ // Session permissionMode, intervention, and autoPilot NEVER leak globally across new sessions!
1648
+ state.config.permissionMode = DEFAULT_CHIEF_PERMISSION_MODE
1649
+ applyPatchTo(state.config, false, false, false)
1650
+
1651
+ if (normalizedReqPerm) {
1652
+ if (normalizedReqPerm === 'chief' && safePatch.confirmedChiefRisk === true) {
1653
+ ws.chiefRiskAck = {
1654
+ acknowledged: true,
1655
+ at: Date.now(),
1656
+ by: clamp(safePatch.by || 'operator', 40),
1657
+ version: '1.2.1',
1658
+ }
1659
+ } else if (normalizedReqPerm !== 'chief') {
1660
+ ws.chiefRiskAck = null
1661
+ }
1662
+ if (normalizedReqPerm !== effBefore.permissionMode) {
1663
+ if (ws.pendingElevation && permissionRank(normalizedReqPerm) >= permissionRank(ws.pendingElevation.targetMode)) {
1664
+ ws.pendingElevation = null
1665
+ }
1666
+ pushAuditToWs(ws, {
1667
+ mode: normalizedReqPerm,
1668
+ stage: 'permission_gate',
1669
+ decision: 'mode_changed',
1670
+ operation: '切换权限等级',
1671
+ target: `${CHIEF_PERMISSION_META[effBefore.permissionMode].level} -> ${CHIEF_PERMISSION_META[normalizedReqPerm].level}`,
1672
+ reason: normalizedReqPerm === 'chief' ? '用户勾选风险声明并确认启用 L3 参谋长模式' : `用户主动切换至 ${CHIEF_PERMISSION_META[normalizedReqPerm].title}`,
1673
+ outcome: 'ok',
1674
+ by: clamp(safePatch.by || 'operator', 40),
1675
+ })
1676
+ }
1677
+ }
1678
+
1679
+ const finalCfg = resolveWorkspaceConfig(state, sid)
1680
+ if (!compactLowWarning && finalCfg.tacticalModes.compactThresholdMode === 'tokens' && finalCfg.tacticalModes.compactThresholdTokens < COMPACT_TOKEN_WARN_FLOOR) {
1681
+ compactLowWarning = `当前阈值(${finalCfg.tacticalModes.compactThresholdInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
1682
+ } else if (!compactLowWarning && finalCfg.tacticalModes.compactThresholdMode !== 'tokens' && finalCfg.tacticalModes.compactThresholdPct < COMPACT_PCT_WARN_FLOOR) {
1683
+ compactLowWarning = `当前触发比例(${finalCfg.tacticalModes.compactThresholdPct}%)低于安全建议线 ${COMPACT_PCT_WARN_FLOOR}%,可能导致上下文频繁提前归档压缩`
1684
+ }
1685
+ return {
1686
+ ok: true,
1687
+ ...(compactLowWarning ? { compactLowWarning } : {}),
1688
+ config: { ...finalCfg, tacticalModes: { ...finalCfg.tacticalModes } },
1689
+ }
1690
+ })
1691
+ }
1692
+
1693
+ export function mutateChiefFact(deps, { sessionId, op, id, text, category, pinned }) {
1694
+ const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
1695
+ return mutateChiefState((state) => {
1696
+ const ws = ensureWorkspace(state, rootId)
1697
+ if (op === 'add') {
1698
+ const cat = category || 'discipline'
1699
+ const activeCluster = getLinkedCluster(state, rootId)
1700
+ const fact = normalizeFact({
1701
+ text,
1702
+ category: cat,
1703
+ by: 'user',
1704
+ pinned: Boolean(pinned),
1705
+ originRootId: rootId === 'global' ? '' : rootId,
1706
+ peerRootIds: cat === 'team' ? activeCluster.filter(pid => pid !== rootId) : [],
1707
+ })
1708
+ if (!fact) return { ok: false, error: '条目无效或包含敏感凭据' }
1709
+ ws.facts.push(fact)
1710
+ if (ws.facts.length > FACTS_CAP) ws.facts = ws.facts.slice(-FACTS_CAP)
1711
+ return { ok: true, fact }
1712
+ }
1713
+ const target = ws.facts.find(f => f.id === id)
1714
+ if (!target) return { ok: false, error: '未找到该记忆条目' }
1715
+ if (op === 'remove') {
1716
+ ws.facts = ws.facts.filter(f => f.id !== id)
1717
+ return { ok: true }
1718
+ }
1719
+ if (op === 'pin') {
1720
+ target.pinned = Boolean(pinned)
1721
+ target.updatedAt = Date.now()
1722
+ return { ok: true, fact: target }
1723
+ }
1724
+ if (op === 'edit') {
1725
+ const clean = clamp(text, FACT_TEXT_MAX)
1726
+ if (!clean || secretLike(clean)) return { ok: false, error: '内容无效或包含敏感凭据' }
1727
+ target.text = clean
1728
+ if (category) target.category = category
1729
+ target.updatedAt = Date.now()
1730
+ return { ok: true, fact: target }
1731
+ }
1732
+ return { ok: false, error: '未知操作: ' + op }
1733
+ })
1734
+ }
1735
+
1736
+ export function shortAgentBriefName(name) {
1737
+ const raw = String(name || '').trim()
1738
+ if (!raw) return ''
1739
+ return raw
1740
+ .split('/')
1741
+ .map(seg => seg.replace(/[-_]([0-9a-f]{8,40})$/i, (_, hex) => '·' + hex.slice(0, 4)))
1742
+ .join('/')
1743
+ }
1744
+
1745
+ export function stripCheckpointNoise(text) {
1746
+ return String(text || '')
1747
+ .replace(/\[dsh-mnemon:[^\]]*\][\s\S]*/gi, '')
1748
+ .replace(/Bounded completed checkpoint[\s\S]*/gi, '')
1749
+ .replace(/\s+/g, ' ')
1750
+ .trim()
1751
+ }
1752
+
1753
+ export function isInternalCheckpointNoise(text) {
1754
+ const s = stripCheckpointNoise(text)
1755
+ if (!s) return true
1756
+ if (/^Mnemon idle checkpoint review\b/i.test(s)) return true
1757
+ return false
1758
+ }
1759
+
1760
+ export function extractJsonObject(raw) {
1761
+ const text = String(raw || '').trim()
1762
+ if (!text) return null
1763
+ const stripped = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim()
1764
+ try {
1765
+ const direct = JSON.parse(stripped)
1766
+ if (direct && typeof direct === 'object') return direct
1767
+ } catch {}
1768
+ const first = text.indexOf('{')
1769
+ const last = text.lastIndexOf('}')
1770
+ if (first !== -1 && last > first) {
1771
+ try {
1772
+ const sliced = JSON.parse(text.slice(first, last + 1))
1773
+ if (sliced && typeof sliced === 'object') return sliced
1774
+ } catch {}
1775
+ }
1776
+ return null
1777
+ }