dsh-chief 1.3.0 → 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.
@@ -0,0 +1,391 @@
1
+ /**
2
+ * safety/policy-plugin.js
3
+ *
4
+ * Restrict-only Policy Plugin validation and runtime evaluation for DSH Chief.
5
+ * Plugins may tighten or narrow permissions and rules, NEVER weaken Hard Guards.
6
+ */
7
+
8
+ import path from 'node:path'
9
+ import { analyzeCommand } from './command-analyzer.js'
10
+ import { safeRealpath } from './path-guard.js'
11
+
12
+ const ROLE_ORDER = {
13
+ advisor: 0,
14
+ assistant: 1,
15
+ strategist: 2,
16
+ chief: 3,
17
+ }
18
+
19
+ export const FORBIDDEN_WEAKENING_KEYS = Object.freeze([
20
+ 'disableHardGuard',
21
+ 'bypassHardGuard',
22
+ 'allowOutsideWorkspace',
23
+ 'allowSensitiveCredentials',
24
+ 'allowDestructiveCommands',
25
+ 'bypassApproval',
26
+ 'relaxForbiddenBounds',
27
+ 'overrideExecutor',
28
+ 'autoApproveAll',
29
+ 'allowFifthRole',
30
+ 'skipHardGuard',
31
+ 'disableAudit',
32
+ 'allowNtfsAds',
33
+ 'allowBoundsWriteFromTool',
34
+ 'unrestrictedWrite',
35
+ ])
36
+
37
+ const ALLOWED_TOP_KEYS = new Set(['id', 'name', 'version', 'source', 'enabled', 'description', 'rules'])
38
+ const ALLOWED_RULE_KEYS = new Set([
39
+ 'maxRoleCeiling',
40
+ 'maxSubagentRoleCeiling',
41
+ 'denyTools',
42
+ 'requireApprovalTools',
43
+ 'forbidPathPrefixes',
44
+ 'restrictFsWritePrefixes',
45
+ 'forbidCommandPatterns',
46
+ 'requireApprovalCommandPatterns',
47
+ ])
48
+ const SUBAGENT_SAFE_ROLES = new Set(['advisor', 'assistant'])
49
+
50
+ function containsFunctionValue(obj, depth = 0) {
51
+ if (depth > 8 || obj == null) return false
52
+ if (typeof obj === 'function') return true
53
+ if (typeof obj !== 'object') return false
54
+ if (Array.isArray(obj)) return obj.some(v => containsFunctionValue(v, depth + 1))
55
+ for (const val of Object.values(obj)) {
56
+ if (containsFunctionValue(val, depth + 1)) return true
57
+ }
58
+ return false
59
+ }
60
+
61
+ function normalizeStringArray(raw, { fieldName, maxItems = 40, maxLen = 160 } = {}) {
62
+ if (raw === undefined) return { ok: true, list: [] }
63
+ if (!Array.isArray(raw)) {
64
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: `规则字段 ${fieldName} 必须为字符串数组` }
65
+ }
66
+ if (raw.length > maxItems) {
67
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: `规则字段 ${fieldName} 条目数超出上限 (${maxItems})` }
68
+ }
69
+ const out = []
70
+ for (const entry of raw) {
71
+ if (typeof entry !== 'string') {
72
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: `规则字段 ${fieldName} 仅允许字符串条目` }
73
+ }
74
+ const clean = entry.trim()
75
+ if (!clean) continue
76
+ if (clean.length > maxLen) {
77
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: `规则字段 ${fieldName} 单条长度超出上限 (${maxLen})` }
78
+ }
79
+ out.push(clean)
80
+ }
81
+ return { ok: true, list: [...new Set(out)] }
82
+ }
83
+
84
+ function validateSafeRegexPatterns(list, fieldName) {
85
+ for (const pat of list) {
86
+ // Reject obvious catastrophic backtracking constructs such as `(a+)+` or `(.*)*`
87
+ if (/\([^)]*[+*][^)]*\)[+*{]/.test(pat)) {
88
+ return { ok: false, code: 'POLICY_PLUGIN_UNSAFE_PATTERN', error: `拒绝含嵌套量词的正则规则 (${fieldName}): ${pat}` }
89
+ }
90
+ try {
91
+ // eslint-disable-next-line no-new
92
+ new RegExp(pat, 'i')
93
+ } catch {
94
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: `策略插件正则语法无效 (${fieldName}): ${pat}` }
95
+ }
96
+ }
97
+ return { ok: true }
98
+ }
99
+
100
+ export function validatePolicyPlugin(rawPlugin) {
101
+ if (!rawPlugin || typeof rawPlugin !== 'object' || Array.isArray(rawPlugin)) {
102
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: '策略插件必须是 JSON 对象' }
103
+ }
104
+ if (containsFunctionValue(rawPlugin)) {
105
+ return { ok: false, code: 'POLICY_PLUGIN_WEAKENING_FORBIDDEN', error: '策略插件禁止携带可执行函数回调(仅允许声明式 JSON 规则)' }
106
+ }
107
+
108
+ for (const k of Object.keys(rawPlugin)) {
109
+ if (FORBIDDEN_WEAKENING_KEYS.includes(k)) {
110
+ return {
111
+ ok: false,
112
+ code: 'POLICY_PLUGIN_WEAKENING_FORBIDDEN',
113
+ error: `策略插件禁止包含削弱/关闭安全卫兵的字段 "${k}"(只允许收紧规则)`,
114
+ }
115
+ }
116
+ if (!ALLOWED_TOP_KEYS.has(k)) {
117
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: `策略插件包含未定义顶层字段 "${k}"` }
118
+ }
119
+ }
120
+
121
+ const id = String(rawPlugin.id || '').trim()
122
+ const name = String(rawPlugin.name || id).trim()
123
+ const version = String(rawPlugin.version || '1.0.0').trim()
124
+ const source = String(rawPlugin.source || 'workspace').trim()
125
+ if (!id || !/^[a-zA-Z0-9._-]{2,64}$/.test(id)) {
126
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: '策略插件缺少合法 id(仅允许字母/数字/._-,2~64字符)' }
127
+ }
128
+ if (!name || name.length > 80) {
129
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: '策略插件 name 必须为 1~80 字符' }
130
+ }
131
+ if (rawPlugin.enabled !== undefined && typeof rawPlugin.enabled !== 'boolean') {
132
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: '策略插件 enabled 必须为布尔值' }
133
+ }
134
+
135
+ const rawRules = rawPlugin.rules && typeof rawPlugin.rules === 'object' && !Array.isArray(rawPlugin.rules)
136
+ ? rawPlugin.rules
137
+ : (rawPlugin.rules === undefined ? {} : null)
138
+ if (!rawRules) {
139
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: '策略插件 rules 必须为对象' }
140
+ }
141
+
142
+ for (const rk of Object.keys(rawRules)) {
143
+ if (FORBIDDEN_WEAKENING_KEYS.includes(rk)) {
144
+ return {
145
+ ok: false,
146
+ code: 'POLICY_PLUGIN_WEAKENING_FORBIDDEN',
147
+ error: `策略插件 rules 禁止包含削弱安全规则的字段 "${rk}"`,
148
+ }
149
+ }
150
+ if (!ALLOWED_RULE_KEYS.has(rk)) {
151
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: `策略插件 rules 包含未授权字段 "${rk}"` }
152
+ }
153
+ }
154
+
155
+ let maxRoleCeiling = ''
156
+ if (rawRules.maxRoleCeiling !== undefined) {
157
+ const r = String(rawRules.maxRoleCeiling || '').trim().toLowerCase()
158
+ if (!Object.prototype.hasOwnProperty.call(ROLE_ORDER, r)) {
159
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: `无效的 maxRoleCeiling 值:${r}` }
160
+ }
161
+ maxRoleCeiling = r
162
+ }
163
+
164
+ let maxSubagentRoleCeiling = ''
165
+ if (rawRules.maxSubagentRoleCeiling !== undefined) {
166
+ const sr = String(rawRules.maxSubagentRoleCeiling || '').trim().toLowerCase()
167
+ if (!SUBAGENT_SAFE_ROLES.has(sr)) {
168
+ return {
169
+ ok: false,
170
+ code: 'POLICY_PLUGIN_WEAKENING_FORBIDDEN',
171
+ error: `子代理角色上限只允许收紧至 advisor 或 assistant(收到 "${sr}")`,
172
+ }
173
+ }
174
+ maxSubagentRoleCeiling = sr
175
+ }
176
+
177
+ const denyToolsRes = normalizeStringArray(rawRules.denyTools, { fieldName: 'denyTools' })
178
+ if (!denyToolsRes.ok) return denyToolsRes
179
+
180
+ const reqAprToolsRes = normalizeStringArray(rawRules.requireApprovalTools, { fieldName: 'requireApprovalTools' })
181
+ if (!reqAprToolsRes.ok) return reqAprToolsRes
182
+
183
+ const forbidPathsRes = normalizeStringArray(rawRules.forbidPathPrefixes, { fieldName: 'forbidPathPrefixes' })
184
+ if (!forbidPathsRes.ok) return forbidPathsRes
185
+
186
+ const restrictWriteRes = normalizeStringArray(rawRules.restrictFsWritePrefixes, { fieldName: 'restrictFsWritePrefixes' })
187
+ if (!restrictWriteRes.ok) return restrictWriteRes
188
+ if (restrictWriteRes.list.some(p => p === '*' || p === '**' || p === '/' || p === '.')) {
189
+ return {
190
+ ok: false,
191
+ code: 'POLICY_PLUGIN_WEAKENING_FORBIDDEN',
192
+ error: 'restrictFsWritePrefixes 仅用于限定子目录白名单,禁止填写通配放宽符 (* / .)',
193
+ }
194
+ }
195
+
196
+ const forbidCmdsRes = normalizeStringArray(rawRules.forbidCommandPatterns, { fieldName: 'forbidCommandPatterns' })
197
+ if (!forbidCmdsRes.ok) return forbidCmdsRes
198
+ const patCheck1 = validateSafeRegexPatterns(forbidCmdsRes.list, 'forbidCommandPatterns')
199
+ if (!patCheck1.ok) return patCheck1
200
+
201
+ const reqAprCmdsRes = normalizeStringArray(rawRules.requireApprovalCommandPatterns, { fieldName: 'requireApprovalCommandPatterns' })
202
+ if (!reqAprCmdsRes.ok) return reqAprCmdsRes
203
+ const patCheck2 = validateSafeRegexPatterns(reqAprCmdsRes.list, 'requireApprovalCommandPatterns')
204
+ if (!patCheck2.ok) return patCheck2
205
+
206
+ return {
207
+ ok: true,
208
+ plugin: {
209
+ id,
210
+ name,
211
+ version: version.slice(0, 32),
212
+ source: source.slice(0, 48),
213
+ enabled: rawPlugin.enabled !== false,
214
+ description: String(rawPlugin.description || '').trim().slice(0, 200),
215
+ rules: {
216
+ ...(maxRoleCeiling ? { maxRoleCeiling } : {}),
217
+ ...(maxSubagentRoleCeiling ? { maxSubagentRoleCeiling } : {}),
218
+ denyTools: denyToolsRes.list,
219
+ requireApprovalTools: reqAprToolsRes.list,
220
+ forbidPathPrefixes: forbidPathsRes.list,
221
+ restrictFsWritePrefixes: restrictWriteRes.list,
222
+ forbidCommandPatterns: forbidCmdsRes.list,
223
+ requireApprovalCommandPatterns: reqAprCmdsRes.list,
224
+ },
225
+ },
226
+ }
227
+ }
228
+
229
+ export function validatePolicyPluginList(list) {
230
+ if (list === undefined || list === null) return { ok: true, plugins: [] }
231
+ if (!Array.isArray(list)) {
232
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: 'policyPlugins 必须为数组' }
233
+ }
234
+ if (list.length > 20) {
235
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: 'policyPlugins 数量超出上限 (20)' }
236
+ }
237
+ const out = []
238
+ const seenIds = new Set()
239
+ for (const raw of list) {
240
+ const res = validatePolicyPlugin(raw)
241
+ if (!res.ok) return res
242
+ if (seenIds.has(res.plugin.id)) {
243
+ return { ok: false, code: 'POLICY_PLUGIN_SCHEMA_INVALID', error: `存在重复的策略插件 id: ${res.plugin.id}` }
244
+ }
245
+ seenIds.add(res.plugin.id)
246
+ out.push(res.plugin)
247
+ }
248
+ return { ok: true, plugins: out }
249
+ }
250
+
251
+ function normalizeRelPrefix(cwd, targetPath) {
252
+ if (!targetPath) return ''
253
+ const rootAbs = cwd ? safeRealpath(cwd) : ''
254
+ const abs = rootAbs ? path.resolve(rootAbs, String(targetPath)) : path.resolve(String(targetPath))
255
+ const rel = rootAbs ? path.relative(rootAbs, abs) : abs
256
+ return rel.replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase()
257
+ }
258
+
259
+ function intersectPrefixes(existing, incoming) {
260
+ if (!incoming || !incoming.length) return existing
261
+ const cleanIncoming = incoming.map(p => p.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '').toLowerCase()).filter(Boolean)
262
+ if (!cleanIncoming.length) return existing
263
+ if (existing === null) return cleanIncoming
264
+ const merged = []
265
+ for (const a of existing) {
266
+ for (const b of cleanIncoming) {
267
+ if (a === b || a.startsWith(b + '/')) merged.push(a)
268
+ else if (b.startsWith(a + '/')) merged.push(b)
269
+ }
270
+ }
271
+ return [...new Set(merged)]
272
+ }
273
+
274
+ export function evaluatePolicyPlugins(plugins = [], {
275
+ tool = '',
276
+ opClass = '',
277
+ targetPath = '',
278
+ command = '',
279
+ cwd = '',
280
+ role = 'advisor',
281
+ } = {}) {
282
+ const list = Array.isArray(plugins) ? plugins : []
283
+ let effectiveMaxRole = role
284
+ let restrictedWritePrefixes = null
285
+ let forceApproval = false
286
+ let forceApprovalPluginId = ''
287
+ let forceApprovalReason = ''
288
+
289
+ const toolName = String(tool || '').trim()
290
+ const relTarget = normalizeRelPrefix(cwd, targetPath)
291
+ const cmdProbes = command
292
+ ? (() => {
293
+ const a = analyzeCommand(command)
294
+ return [a.raw, a.normalized, ...a.segments, ...a.inlinePayloads].filter(Boolean)
295
+ })()
296
+ : []
297
+
298
+ for (const rawPlugin of list) {
299
+ const v = validatePolicyPlugin(rawPlugin)
300
+ if (!v.ok) {
301
+ return {
302
+ decision: 'block',
303
+ stage: 'policy_plugin',
304
+ rule: 'policy_plugin_invalid',
305
+ pluginId: (rawPlugin && rawPlugin.id) || 'invalid',
306
+ reason: v.error,
307
+ badge: '🛡️ 非法策略插件拦截',
308
+ }
309
+ }
310
+ const plugin = v.plugin
311
+ if (!plugin.enabled) continue
312
+ const rules = plugin.rules || {}
313
+
314
+ if (rules.maxRoleCeiling && ROLE_ORDER[rules.maxRoleCeiling] < ROLE_ORDER[effectiveMaxRole]) {
315
+ effectiveMaxRole = rules.maxRoleCeiling
316
+ }
317
+
318
+ if (opClass === 'workspace' && rules.restrictFsWritePrefixes && rules.restrictFsWritePrefixes.length > 0) {
319
+ restrictedWritePrefixes = intersectPrefixes(restrictedWritePrefixes, rules.restrictFsWritePrefixes)
320
+ }
321
+
322
+ if (toolName && rules.denyTools.includes(toolName)) {
323
+ return {
324
+ decision: 'block',
325
+ stage: 'policy_plugin',
326
+ rule: `policy_plugin:${plugin.id}:deny_tool`,
327
+ pluginId: plugin.id,
328
+ reason: `策略插件「${plugin.name}」明确禁止调用工具 ${toolName}`,
329
+ badge: '🛡️ 策略插件禁工具',
330
+ }
331
+ }
332
+
333
+ if (relTarget && rules.forbidPathPrefixes.length > 0) {
334
+ for (const rawPref of rules.forbidPathPrefixes) {
335
+ const pref = rawPref.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '').toLowerCase()
336
+ if (pref && (relTarget === pref || relTarget.startsWith(pref + '/') || relTarget.includes('/' + pref + '/'))) {
337
+ return {
338
+ decision: 'block',
339
+ stage: 'policy_plugin',
340
+ rule: `policy_plugin:${plugin.id}:forbid_path`,
341
+ pluginId: plugin.id,
342
+ reason: `策略插件「${plugin.name}」禁止访问受保护路径前缀 ${rawPref}`,
343
+ badge: '🛡️ 策略插件拦路径',
344
+ }
345
+ }
346
+ }
347
+ }
348
+
349
+ if (cmdProbes.length > 0 && rules.forbidCommandPatterns.length > 0) {
350
+ for (const pat of rules.forbidCommandPatterns) {
351
+ const re = new RegExp(pat, 'i')
352
+ if (cmdProbes.some(p => re.test(p))) {
353
+ return {
354
+ decision: 'block',
355
+ stage: 'policy_plugin',
356
+ rule: `policy_plugin:${plugin.id}:forbid_cmd`,
357
+ pluginId: plugin.id,
358
+ reason: `策略插件「${plugin.name}」拦截受限命令模式 (${pat})`,
359
+ badge: '🛡️ 策略插件拦命令',
360
+ }
361
+ }
362
+ }
363
+ }
364
+
365
+ if (!forceApproval && toolName && rules.requireApprovalTools.includes(toolName)) {
366
+ forceApproval = true
367
+ forceApprovalPluginId = plugin.id
368
+ forceApprovalReason = `策略插件「${plugin.name}」要求工具 ${toolName} 必须经用户逐项审批`
369
+ }
370
+
371
+ if (!forceApproval && cmdProbes.length > 0 && rules.requireApprovalCommandPatterns.length > 0) {
372
+ for (const pat of rules.requireApprovalCommandPatterns) {
373
+ const re = new RegExp(pat, 'i')
374
+ if (cmdProbes.some(p => re.test(p))) {
375
+ forceApproval = true
376
+ forceApprovalPluginId = plugin.id
377
+ forceApprovalReason = `策略插件「${plugin.name}」要求该命令模式 (${pat}) 经用户逐项审批`
378
+ break
379
+ }
380
+ }
381
+ }
382
+ }
383
+
384
+ return {
385
+ decision: forceApproval ? 'require_approval' : 'pass',
386
+ effectiveMaxRole,
387
+ restrictedWritePrefixes,
388
+ pluginId: forceApprovalPluginId,
389
+ reason: forceApprovalReason,
390
+ }
391
+ }
@@ -0,0 +1,278 @@
1
+ /**
2
+ * safety/tool-gate.js
3
+ *
4
+ * Unified Tool Gate ordering:
5
+ * Hard Guards -> Policy Plugins (restrict-only) -> Role + Capabilities -> CapabilityScope Verification
6
+ */
7
+
8
+ import { evaluateSafetyGuardHardRules } from './invariant-guards.js'
9
+ import { evaluateGuardWalls } from './guard-walls.js'
10
+ import { evaluatePolicyPlugins } from './policy-plugin.js'
11
+ import {
12
+ CHIEF_PERMISSION_META,
13
+ DEFAULT_CHIEF_PERMISSION_MODE,
14
+ normalizePermissionMode,
15
+ resolveRoleCapabilities,
16
+ verifyCapabilityScope,
17
+ } from './policy-engine.js'
18
+
19
+ /** 四级权限与策略门禁判定:advisor(L0) / assistant(L1) / strategist(L2) / chief(L3)。 */
20
+ export function evaluateChiefPermissionGate({
21
+ permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
22
+ hasChiefRiskAck = false,
23
+ opClass = 'read',
24
+ tool = '',
25
+ approvedOnce = false,
26
+ capabilityScope = null,
27
+ actualRequest = null,
28
+ policyPlugins = [],
29
+ targetPath = '',
30
+ command = '',
31
+ cwd = '',
32
+ } = {}) {
33
+ const { role: mode, capabilities } = resolveRoleCapabilities(permissionMode, { hasChiefRiskAck, policyPlugins })
34
+ const meta = CHIEF_PERMISSION_META[mode] || CHIEF_PERMISSION_META.advisor
35
+
36
+ const pluginEval = evaluatePolicyPlugins(policyPlugins, {
37
+ tool,
38
+ opClass,
39
+ targetPath,
40
+ command,
41
+ cwd,
42
+ role: mode,
43
+ })
44
+ if (pluginEval.decision === 'block') {
45
+ return {
46
+ decision: 'deny_policy_plugin',
47
+ mode,
48
+ capabilities,
49
+ rule: pluginEval.rule,
50
+ pluginId: pluginEval.pluginId,
51
+ error: pluginEval.reason,
52
+ badge: pluginEval.badge || '🛡️ 策略插件拦截',
53
+ }
54
+ }
55
+
56
+ if (approvedOnce && capabilityScope) {
57
+ const scopeRes = verifyCapabilityScope(capabilityScope, actualRequest || {
58
+ kind: capabilityScope.kind || 'tool',
59
+ tool,
60
+ cwd,
61
+ })
62
+ if (!scopeRes.ok) {
63
+ return {
64
+ decision: 'deny_scope_mismatch',
65
+ mode,
66
+ capabilities,
67
+ rule: scopeRes.rule,
68
+ error: scopeRes.error,
69
+ badge: '🛡️ 授权作用域不匹配',
70
+ }
71
+ }
72
+ }
73
+
74
+ if (opClass === 'read' || opClass === 'elevation_request') {
75
+ if (pluginEval.decision === 'require_approval' && !approvedOnce && opClass === 'read') {
76
+ return {
77
+ decision: 'require_approval',
78
+ mode,
79
+ capabilities,
80
+ requiredMode: mode,
81
+ rule: 'policy_plugin_require_approval',
82
+ error: pluginEval.reason || `策略插件要求调用 ${tool} 前先经用户确认`,
83
+ badge: '🛡️ 插件要求确认',
84
+ }
85
+ }
86
+ return { decision: 'allow', mode, capabilities }
87
+ }
88
+
89
+ if (opClass === 'chief_system') {
90
+ if (!capabilities.allowBoardAdmin && !capabilities.allowArchiveCurate) {
91
+ return {
92
+ decision: 'deny_mode',
93
+ mode,
94
+ capabilities,
95
+ requiredMode: 'assistant',
96
+ rule: 'role_deny_chief_system',
97
+ error: '当前处于「L0 · 顾问模式(只读)」,仅允许分析与建议,不能修改参谋记忆、档案或看板配置。可向用户申请提权至「L1 · 助手模式」。',
98
+ badge: '🔒 L0禁改参谋系统',
99
+ }
100
+ }
101
+ if (pluginEval.decision === 'require_approval' && !approvedOnce) {
102
+ return {
103
+ decision: 'require_approval',
104
+ mode,
105
+ capabilities,
106
+ requiredMode: mode,
107
+ rule: 'policy_plugin_require_approval',
108
+ error: pluginEval.reason || `策略插件要求调用 ${tool} 前先经用户确认`,
109
+ badge: '🛡️ 插件要求确认',
110
+ }
111
+ }
112
+ return { decision: 'allow', mode, capabilities }
113
+ }
114
+
115
+ // 'workspace' or 'workflow'
116
+ const capPolicy = opClass === 'workspace'
117
+ ? (tool === 'run_command' ? capabilities.allowShellExec : capabilities.allowWorkspaceWrite)
118
+ : (tool === 'session_compact'
119
+ ? capabilities.allowSessionCompact
120
+ : (tool === 'main_agent_control' || tool === 'relay' ? capabilities.allowMainRelay : capabilities.allowSubagentDispatch))
121
+
122
+ if (capPolicy === 'deny' || mode === 'advisor' || mode === 'assistant') {
123
+ const targetDesc = opClass === 'workspace' ? '修改项目工作区或执行系统命令' : '调整主对话及子代理工作流'
124
+ return {
125
+ decision: 'deny_mode',
126
+ mode,
127
+ capabilities,
128
+ requiredMode: 'strategist',
129
+ rule: `role_deny_${opClass}`,
130
+ error: `当前处于「${meta.level} · ${meta.title}」,禁止${targetDesc}(${tool})。如需执行,请向用户申请提权至「L2 · 参谋模式(逐项授权)」或「L3 · 参谋长模式」。`,
131
+ badge: `🔒 ${meta.level}禁止操作`,
132
+ }
133
+ }
134
+
135
+ if (mode === 'strategist' || pluginEval.decision === 'require_approval') {
136
+ if (approvedOnce) {
137
+ return { decision: 'allow_approved', mode, capabilities }
138
+ }
139
+ return {
140
+ decision: 'require_approval',
141
+ mode,
142
+ capabilities,
143
+ requiredMode: mode === 'chief' ? 'chief' : 'strategist',
144
+ rule: pluginEval.decision === 'require_approval' ? 'policy_plugin_require_approval' : 'strategist_require_approval',
145
+ error: pluginEval.decision === 'require_approval'
146
+ ? (pluginEval.reason || '策略插件要求该操作先通过授权弹窗确认。')
147
+ : '「L2 · 参谋模式」要求先通过操作授权弹窗由用户逐项确认。',
148
+ badge: '🛡️ 待逐项确认',
149
+ }
150
+ }
151
+
152
+ // mode === 'chief'
153
+ const rawModeNorm = normalizePermissionMode(permissionMode)
154
+ if (rawModeNorm === 'chief' && !hasChiefRiskAck) {
155
+ return {
156
+ decision: 'deny_unacknowledged_l3',
157
+ mode: 'advisor',
158
+ capabilities: resolveRoleCapabilities('advisor', { policyPlugins }).capabilities,
159
+ requiredMode: 'chief',
160
+ rule: 'unacknowledged_l3',
161
+ error: '未检测到「L3 · 参谋长模式」风险知悉确认状态(chiefRiskAck),后端拒绝高权限自主执行。',
162
+ badge: '🛡️ L3未授权拦截',
163
+ }
164
+ }
165
+ return { decision: approvedOnce ? 'allow_approved' : 'allow', mode: 'chief', capabilities }
166
+ }
167
+
168
+ export function evaluateUnifiedToolGate({
169
+ tool = '',
170
+ opClass = 'read',
171
+ targetPath = '',
172
+ command = '',
173
+ args = null,
174
+ cwd = '',
175
+ board = null,
176
+ permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
177
+ hasChiefRiskAck = false,
178
+ approvedOnce = false,
179
+ capabilityScope = null,
180
+ policyPlugins = [],
181
+ } = {}) {
182
+ const hardGuard = evaluateSafetyGuardHardRules({
183
+ tool,
184
+ opClass,
185
+ targetPath,
186
+ command,
187
+ args,
188
+ cwd,
189
+ board,
190
+ })
191
+ if (hardGuard.blocked) {
192
+ return {
193
+ allowed: false,
194
+ stage: 'safety_guard',
195
+ decision: 'blocked',
196
+ rule: hardGuard.rule || 'hard_guard',
197
+ reason: hardGuard.reason,
198
+ badge: hardGuard.badge,
199
+ blockedBySafetyGuard: true,
200
+ }
201
+ }
202
+
203
+ const wallRes = evaluateGuardWalls({
204
+ tool,
205
+ opClass,
206
+ targetPath,
207
+ command,
208
+ args,
209
+ cwd,
210
+ })
211
+ if (wallRes.decision === 'block') {
212
+ return {
213
+ allowed: false,
214
+ stage: 'guard_wall',
215
+ decision: 'blocked',
216
+ rule: wallRes.rule || 'guard_wall_block',
217
+ wallId: wallRes.wallId,
218
+ wallTitle: wallRes.wallTitle,
219
+ reason: wallRes.reason,
220
+ badge: wallRes.badge || '🧱 物理墙拦截',
221
+ blockedByGuardWall: true,
222
+ blockedBySafetyGuard: true,
223
+ }
224
+ }
225
+ if (wallRes.decision === 'require_approval' && !approvedOnce) {
226
+ return {
227
+ allowed: false,
228
+ stage: 'guard_wall',
229
+ decision: 'require_approval',
230
+ rule: wallRes.rule || 'guard_wall_require_approval',
231
+ wallId: wallRes.wallId,
232
+ wallTitle: wallRes.wallTitle,
233
+ reason: wallRes.reason,
234
+ badge: wallRes.badge || '🧱 物理墙待确认',
235
+ requireApproval: true,
236
+ }
237
+ }
238
+
239
+ const gateRes = evaluateChiefPermissionGate({
240
+ permissionMode,
241
+ hasChiefRiskAck,
242
+ opClass,
243
+ tool,
244
+ approvedOnce,
245
+ capabilityScope,
246
+ actualRequest: { kind: (capabilityScope && capabilityScope.kind) || 'tool', tool, args, cwd },
247
+ policyPlugins,
248
+ targetPath,
249
+ command,
250
+ cwd,
251
+ })
252
+
253
+ if (gateRes.decision === 'allow' || gateRes.decision === 'allow_approved') {
254
+ return {
255
+ allowed: true,
256
+ stage: 'permission_gate',
257
+ decision: gateRes.decision,
258
+ mode: gateRes.mode,
259
+ capabilities: gateRes.capabilities,
260
+ }
261
+ }
262
+
263
+ return {
264
+ allowed: false,
265
+ stage: gateRes.decision === 'deny_policy_plugin' ? 'policy_plugin' : (gateRes.decision === 'deny_scope_mismatch' ? 'scope_guard' : 'permission_gate'),
266
+ decision: gateRes.decision,
267
+ mode: gateRes.mode,
268
+ capabilities: gateRes.capabilities,
269
+ requiredMode: gateRes.requiredMode,
270
+ rule: gateRes.rule || gateRes.decision,
271
+ reason: gateRes.error,
272
+ badge: gateRes.badge,
273
+ deniedByMode: gateRes.decision === 'deny_mode' || gateRes.decision === 'deny_unacknowledged_l3',
274
+ deniedByPolicyPlugin: gateRes.decision === 'deny_policy_plugin',
275
+ deniedByScopeMismatch: gateRes.decision === 'deny_scope_mismatch',
276
+ requireApproval: gateRes.decision === 'require_approval',
277
+ }
278
+ }
@@ -417,12 +417,19 @@ export function createSubagentRuntime(deps) {
417
417
  const dir = path.join(root, bucket)
418
418
  const names = safe(() => fs.readdirSync(dir), [])
419
419
  for (const name of names) {
420
- const file = path.join(dir, name, 'session.v4.jsonl.zstd')
420
+ const dirPath = path.join(dir, name)
421
+ const file = path.join(dirPath, 'session.v4.jsonl.zstd')
421
422
  let at = 0
422
423
  try {
423
424
  at = fs.statSync(file).mtimeMs
424
425
  } catch {
425
- continue
426
+ const entries = safe(() => fs.readdirSync(dirPath), [])
427
+ for (const entName of entries) {
428
+ if (!/^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/.test(entName)) continue
429
+ const mst = safe(() => fs.statSync(path.join(dirPath, entName)).mtimeMs, 0)
430
+ if (mst > at) at = mst
431
+ }
432
+ if (!at) continue
426
433
  }
427
434
  const key = name.indexOf('session-') === 0 ? name : 'session-' + name
428
435
  const previous = found.get(key) || 0