dsh-chief 1.2.1 → 1.4.0

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