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-executor.js CHANGED
@@ -1,121 +1,98 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { spawn } from 'node:child_process'
4
-
5
- export const CHIEF_PERMISSION_MODES = ['advisor', 'assistant', 'strategist', 'chief']
6
- export const DEFAULT_CHIEF_PERMISSION_MODE = 'advisor'
7
-
8
- export const CHIEF_PERMISSION_META = {
9
- advisor: {
10
- key: 'advisor',
11
- rank: 0,
12
- level: 'L0',
13
- icon: '👁',
14
- shortLabel: 'L0 顾问',
15
- title: '顾问模式',
16
- enTitle: 'READ ONLY',
17
- badge: '默认模式',
18
- tagline: '只观察、只分析、只建议。',
19
- desc: 'L0 默认只读档:仅读取看板与允许访问的项目状态,分析任务并提建议,绝不修改工作区或任何工作流。',
20
- bullets: [
21
- '读取看板和允许访问的项目状态',
22
- '分析任务、提供建议',
23
- '不修改工作区',
24
- '不修改主代理和子代理工作流',
25
- ],
26
- },
27
- assistant: {
28
- key: 'assistant',
29
- rank: 1,
30
- level: 'L1',
31
- icon: '🗂',
32
- shortLabel: 'L1 助手',
33
- title: '助手模式',
34
- enTitle: 'ASSISTANT',
35
- badge: '',
36
- tagline: '允许自主维护参谋系统。',
37
- desc: 'L1 参谋内务档:具备顾问全部能力,允许维护自身记忆、档案与看板配置,但不改工作区、不接管主子代理工作流。',
38
- bullets: [
39
- '顾问模式全部能力',
40
- '管理自己的参谋系统',
41
- '修改自己的记忆、档案和看板配置',
42
- '不直接修改项目工作区',
43
- '不接管主代理工作流',
44
- ],
45
- },
46
- strategist: {
47
- key: 'strategist',
48
- rank: 2,
49
- level: 'L2',
50
- icon: '🛡️',
51
- shortLabel: 'L2 参谋',
52
- title: '参谋模式',
53
- enTitle: 'ADVISOR WITH APPROVAL',
54
- badge: '逐项授权',
55
- tagline: 'Agent 提出操作,用户决定是否执行。',
56
- desc: 'L2 逐项确认档:可申请修改工作区文件、运行系统命令及调整主对话/子代理工作流,每项受控操作执行前均弹窗由您逐项确认。',
57
- bullets: [
58
- '助手模式全部能力',
59
- '可以申请修改工作区文件',
60
- '可以申请修改主对话和子代理工作流',
61
- '每项受控操作执行前弹窗',
62
- '用户确认后才能执行',
63
- ],
64
- },
65
- chief: {
66
- key: 'chief',
67
- rank: 3,
68
- level: 'L3',
69
- icon: '⚡',
70
- shortLabel: 'L3 参谋长',
71
- title: '参谋长模式',
72
- enTitle: 'CHIEF OF STAFF',
73
- badge: '主动风险知悉',
74
- tagline: '用户明确接受更高自主权带来的操作风险。',
75
- desc: 'L3 高权限自主档:可自主修改工作区、执行命令、切换主代理并协调子代理工作流;启用前必须阅读风险声明并主动勾选确认。',
76
- bullets: [
77
- '参谋模式全部能力',
78
- '获得更高的自主执行权限',
79
- '可以切换主代理',
80
- '可以协调子代理及其工作流',
81
- '启用前必须阅读风险声明并主动勾选确认',
82
- ],
83
- },
84
- }
85
-
86
- const PERM_ALIAS_MAP = {
87
- advisor: 'advisor',
88
- l0: 'advisor',
89
- 'read-only': 'advisor',
90
- assistant: 'assistant',
91
- l1: 'assistant',
92
- strategist: 'strategist',
93
- counselor: 'strategist',
94
- l2: 'strategist',
95
- 'workspace-write': 'strategist',
96
- 'auto-review': 'strategist',
97
- chief: 'chief',
98
- 'chief-of-staff': 'chief',
99
- l3: 'chief',
100
- }
101
-
102
- export function normalizePermissionMode(raw, opts = {}) {
103
- const v = String(raw || '').trim().toLowerCase()
104
- const hasAck = Boolean(opts && opts.hasChiefRiskAck)
105
- const requireAck = Boolean(opts && opts.requireAck)
106
- if (v === 'danger-full-access') {
107
- return hasAck ? 'chief' : DEFAULT_CHIEF_PERMISSION_MODE
108
- }
109
- const mapped = PERM_ALIAS_MAP[v] || DEFAULT_CHIEF_PERMISSION_MODE
110
- if (mapped === 'chief' && requireAck && !hasAck) {
111
- return DEFAULT_CHIEF_PERMISSION_MODE
112
- }
113
- return mapped
114
- }
115
-
116
- export function permissionRank(mode) {
117
- const norm = normalizePermissionMode(mode)
118
- return (CHIEF_PERMISSION_META[norm] && CHIEF_PERMISSION_META[norm].rank) ?? 0
4
+ import { performance } from 'node:perf_hooks'
5
+ import {
6
+ CHIEF_PERMISSION_MODES,
7
+ DEFAULT_CHIEF_PERMISSION_MODE,
8
+ CHIEF_PERMISSION_META,
9
+ normalizePermissionMode,
10
+ permissionRank,
11
+ getToolOpClass,
12
+ resolveRoleCapabilities,
13
+ buildCapabilityScope,
14
+ verifyCapabilityScope,
15
+ HUMAN_BOUNDS_CONFIRM_TOKEN,
16
+ safeRealpath,
17
+ isPathInsideWorkspace,
18
+ hasWindowsReservedDeviceName,
19
+ hasForbiddenNtfsAds,
20
+ isSensitiveCredentialPath,
21
+ validateWorkspacePath,
22
+ verifyBoundsWriteAuth,
23
+ decodeEncodedPowerShell,
24
+ normalizeCommandForSecurity,
25
+ splitCompoundCommand,
26
+ extractInlineScriptPayloads,
27
+ analyzeCommand,
28
+ HARD_GUARD_RULE_IDS,
29
+ isDestructiveShellCommand,
30
+ commandTouchesSensitiveCredential,
31
+ checkForbiddenBounds,
32
+ evaluateSafetyGuardHardRules,
33
+ FORBIDDEN_WEAKENING_KEYS,
34
+ validatePolicyPlugin,
35
+ validatePolicyPluginList,
36
+ evaluatePolicyPlugins,
37
+ evaluateChiefPermissionGate,
38
+ evaluateUnifiedToolGate,
39
+ GUARD_WALL_RULE_TYPES,
40
+ GUARD_WALL_SCOPES,
41
+ guardWallsFilePath,
42
+ validateGuardWallInput,
43
+ normalizeGuardWall,
44
+ isGuardWallActiveForCwd,
45
+ listGuardWalls,
46
+ mutateGuardWalls,
47
+ evaluateGuardWalls,
48
+ evaluatePreExecuteDefense,
49
+ redactAuditText,
50
+ } from './safety/index.js'
51
+
52
+ export {
53
+ CHIEF_PERMISSION_MODES,
54
+ DEFAULT_CHIEF_PERMISSION_MODE,
55
+ CHIEF_PERMISSION_META,
56
+ normalizePermissionMode,
57
+ permissionRank,
58
+ getToolOpClass,
59
+ resolveRoleCapabilities,
60
+ buildCapabilityScope,
61
+ verifyCapabilityScope,
62
+ HUMAN_BOUNDS_CONFIRM_TOKEN,
63
+ safeRealpath,
64
+ isPathInsideWorkspace,
65
+ hasWindowsReservedDeviceName,
66
+ hasForbiddenNtfsAds,
67
+ isSensitiveCredentialPath,
68
+ validateWorkspacePath,
69
+ verifyBoundsWriteAuth,
70
+ decodeEncodedPowerShell,
71
+ normalizeCommandForSecurity,
72
+ splitCompoundCommand,
73
+ extractInlineScriptPayloads,
74
+ analyzeCommand,
75
+ HARD_GUARD_RULE_IDS,
76
+ isDestructiveShellCommand,
77
+ commandTouchesSensitiveCredential,
78
+ checkForbiddenBounds,
79
+ evaluateSafetyGuardHardRules,
80
+ FORBIDDEN_WEAKENING_KEYS,
81
+ validatePolicyPlugin,
82
+ validatePolicyPluginList,
83
+ evaluatePolicyPlugins,
84
+ evaluateChiefPermissionGate,
85
+ evaluateUnifiedToolGate,
86
+ GUARD_WALL_RULE_TYPES,
87
+ GUARD_WALL_SCOPES,
88
+ guardWallsFilePath,
89
+ validateGuardWallInput,
90
+ normalizeGuardWall,
91
+ isGuardWallActiveForCwd,
92
+ listGuardWalls,
93
+ mutateGuardWalls,
94
+ evaluateGuardWalls,
95
+ evaluatePreExecuteDefense,
119
96
  }
120
97
 
121
98
  export const CHIEF_TOOLS_PROMPT_GUIDE = [
@@ -259,130 +236,6 @@ function truncateMiddle(text, maxBytes = 12_288) {
259
236
  return s.slice(0, head) + `\n...[已截断 ${s.length - maxBytes} 字符]...\n` + s.slice(-tail)
260
237
  }
261
238
 
262
- function safeRealpath(targetPath) {
263
- try {
264
- return fs.realpathSync.native ? fs.realpathSync.native(targetPath) : fs.realpathSync(targetPath)
265
- } catch {
266
- return path.resolve(targetPath)
267
- }
268
- }
269
-
270
- export function isPathInsideWorkspace(workspaceRoot, targetPath) {
271
- if (!workspaceRoot || !targetPath) return false
272
- const rootAbs = safeRealpath(workspaceRoot)
273
- let probe = path.resolve(rootAbs, targetPath)
274
- if (!fs.existsSync(probe)) {
275
- const parent = path.dirname(probe)
276
- probe = fs.existsSync(parent) ? path.join(safeRealpath(parent), path.basename(probe)) : path.resolve(probe)
277
- } else {
278
- probe = safeRealpath(probe)
279
- }
280
- const cmpRoot = process.platform === 'win32' ? rootAbs.toLowerCase() : rootAbs
281
- const cmpTarget = process.platform === 'win32' ? probe.toLowerCase() : probe
282
- const rel = path.relative(cmpRoot, cmpTarget)
283
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
284
- }
285
-
286
- function isSensitiveCredentialPath(filePath) {
287
- const base = path.basename(String(filePath || '')).toLowerCase()
288
- const normalized = String(filePath || '').replace(/\\/g, '/').toLowerCase()
289
- if (base === '.env' || base.startsWith('.env.') || base === '.credentials.yaml' || base.startsWith('.credentials.')) {
290
- return true
291
- }
292
- if (/(?:id_rsa|id_ed25519|id_dsa|\.pem$|\.p12$|\.pfx$|credentials\.json$|secrets?\.(?:json|ya?ml)$)/.test(normalized)) {
293
- return true
294
- }
295
- return false
296
- }
297
-
298
- const DESTRUCTIVE_COMMAND_PATTERNS = [
299
- /\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/])|~|\*|\.\.)/i,
300
- /\bgit\s+(?:reset\s+--hard|clean\s+-[a-z]*f[a-z]*d|push\s+(?:--force|-f)\b)/i,
301
- /\b(?:format|diskpart|cipher\s+\/w|bcdedit)\b/i,
302
- /\bdel\s+\/[fqs][^\n]*[a-z]:\\/i,
303
- /\bRemove-Item\b[^\n]*-Recurse[^\n]*-Force[^\n]*(?:[a-z]:\\|\*)/i,
304
- /\b(?:shutdown(?:\.exe)?|restart-computer|stop-computer|mkfs|dd\s+if=.*of=\/dev\/)\b/i,
305
- /\breg(?:\.exe)?\s+delete\s+(?:hklm|hkcr|hkcu\\software\\microsoft)\b/i,
306
- /\bdrop\s+(?:database|schema)\b/i,
307
- ]
308
-
309
- function isDestructiveShellCommand(command) {
310
- const cmd = String(command || '').trim()
311
- if (!cmd) return false
312
- return DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(cmd))
313
- }
314
-
315
- function commandTouchesSensitiveCredential(command) {
316
- const cmd = String(command || '')
317
- return /(?:^|[\s"'=/\\])(?:\.env(?:\.[a-z0-9_-]+)?|\.credentials\.(?:ya?ml|json)|id_rsa|id_ed25519|id_dsa|\.pem|\.p12|\.pfx)(?:$|[\s"';&|])/i.test(cmd)
318
- }
319
-
320
- /**
321
- * 无论当前处于何种权限级别(包括 danger-full-access),都坚决守住用户在看板中设定的禁止红线。
322
- */
323
- export function checkForbiddenBounds(board, actionDesc = '', commandOrPath = '') {
324
- const forbidden = [
325
- ...((board && board.bounds && Array.isArray(board.bounds.forbidden)) ? board.bounds.forbidden : []),
326
- ...((board && board.pinnedBounds && Array.isArray(board.pinnedBounds.forbidden)) ? board.pinnedBounds.forbidden : []),
327
- ]
328
- if (!forbidden.length) return { blocked: false }
329
- const haystack = `${actionDesc} ${commandOrPath}`.replace(/\\/g, '/').toLowerCase()
330
-
331
- for (const rule of forbidden) {
332
- const rText = String(rule || '').trim()
333
- if (!rText) continue
334
- const ruleNorm = rText.replace(/\\/g, '/')
335
- const ruleLower = ruleNorm.toLowerCase()
336
-
337
- // 1. 提取反引号或引号内的受禁命令或路径字面量,如 `git push`、`npm publish`、"secret.env"
338
- const quoted = [
339
- ...[...ruleNorm.matchAll(/`([^`]{2,80})`/g)].map(m => m[1]),
340
- ...[...ruleNorm.matchAll(/["'「『]([^"'」』]{2,80})["'」』]/g)].map(m => m[1]),
341
- ].map(s => s.trim().toLowerCase())
342
- for (const token of quoted) {
343
- if (token && haystack.includes(token)) {
344
- return { blocked: true, matchedRule: rText, trigger: token }
345
- }
346
- }
347
-
348
- // 2. 提取不带反引号的文件名、路径片段、点文件或扩展名(如 secret.env、src/auth.js、package.json、.env)
349
- const pathTokens = [...ruleLower.matchAll(/(?:[a-z0-9_.-]+\/[a-z0-9_.\-\/]+|\.[a-z0-9_-]{2,16}|[a-z0-9_-]{2,40}\.[a-z0-9]{1,10})/g)]
350
- .map(m => m[0].trim())
351
- for (const tok of pathTokens) {
352
- if (tok && tok.length >= 3 && haystack.includes(tok)) {
353
- return { blocked: true, matchedRule: rText, trigger: tok }
354
- }
355
- }
356
-
357
- // 3. 匹配常见高危动词组合
358
- const dangerousCmds = [
359
- 'git push',
360
- 'npm publish',
361
- 'git reset --hard',
362
- 'rm -rf',
363
- 'del /f',
364
- 'format ',
365
- 'drop table',
366
- 'drop database',
367
- ]
368
- for (const cmdTok of dangerousCmds) {
369
- if (ruleLower.includes(cmdTok) && haystack.includes(cmdTok)) {
370
- return { blocked: true, matchedRule: rText, trigger: cmdTok }
371
- }
372
- }
373
-
374
- // 4. 若用户直接写了极短裸禁止词(去前缀后 >= 4 字符的命令行或目录标记)
375
- const stripped = ruleLower
376
- .replace(/^(?:严禁|禁止|不得|切勿|不要|不能|不可|不允许|勿|do\s+not|never|forbid)\s*/i, '')
377
- .replace(/^(?:改动|修改|编辑|写入|删除|覆盖|执行|运行|推送|发布|触碰)\s*/i, '')
378
- .trim()
379
- if (stripped.length >= 4 && /^[a-z0-9_.\-\/:\s]{4,64}$/.test(stripped) && haystack.includes(stripped)) {
380
- return { blocked: true, matchedRule: rText, trigger: stripped }
381
- }
382
- }
383
- return { blocked: false }
384
- }
385
-
386
239
  function runSubprocess(command, cwd, timeoutMs = 20_000) {
387
240
  return new Promise((resolve) => {
388
241
  const clampedTimeout = Math.min(45_000, Math.max(2_000, Number(timeoutMs) || 20_000))
@@ -530,143 +383,6 @@ function runRgSearch(rootDir, pattern, maxHits = 30) {
530
383
  })
531
384
  }
532
385
 
533
- export function getToolOpClass(tool) {
534
- switch (String(tool || '').trim()) {
535
- case 'read_file':
536
- case 'list_dir':
537
- case 'search_files':
538
- return 'read'
539
- case 'request_permission_elevation':
540
- return 'elevation_request'
541
- case 'archive_write':
542
- return 'chief_system'
543
- case 'write_file':
544
- case 'edit_file':
545
- case 'run_command':
546
- return 'workspace'
547
- case 'subagent_dispatch':
548
- case 'subagent_steer':
549
- case 'subagent_interrupt':
550
- case 'main_agent_control':
551
- case 'session_compact':
552
- return 'workflow'
553
- default:
554
- return 'workflow'
555
- }
556
- }
557
-
558
- /** 安全卫兵硬性规则:优先于四级权限判定,L3 与逐项放行均不可绕过。 */
559
- export function evaluateSafetyGuardHardRules({ tool = '', opClass = '', targetPath = '', command = '', board = null } = {}) {
560
- if (targetPath && isSensitiveCredentialPath(targetPath)) {
561
- return {
562
- blocked: true,
563
- stage: 'safety_guard',
564
- rule: 'sensitive_credential',
565
- reason: `安全卫兵拦截访问敏感凭据文件:${path.basename(targetPath)}`,
566
- badge: '🛡️ 卫兵拦凭据',
567
- }
568
- }
569
- if (command && commandTouchesSensitiveCredential(command)) {
570
- return {
571
- blocked: true,
572
- stage: 'safety_guard',
573
- rule: 'sensitive_credential_cmd',
574
- reason: '安全卫兵拦截触及敏感凭据路径(.env / .credentials / 私钥证书)的终端命令',
575
- badge: '🛡️ 卫兵拦凭据命令',
576
- }
577
- }
578
- if (command && isDestructiveShellCommand(command)) {
579
- return {
580
- blocked: true,
581
- stage: 'safety_guard',
582
- rule: 'destructive_command',
583
- reason: `安全卫兵拦截高危毁灭性系统命令:${clamp(command, 80)}`,
584
- badge: '🛡️ 卫兵拦高危命令',
585
- }
586
- }
587
- if (opClass !== 'read' && opClass !== 'elevation_request') {
588
- const checkInput = targetPath || command
589
- const boundCheck = checkForbiddenBounds(board, tool, checkInput)
590
- if (boundCheck.blocked) {
591
- return {
592
- blocked: true,
593
- stage: 'safety_guard',
594
- rule: 'forbidden_bound',
595
- matchedRule: boundCheck.matchedRule,
596
- reason: `安全卫兵命中禁止红线【${boundCheck.matchedRule}】,坚决拦截:${clamp(checkInput || tool, 80)}`,
597
- badge: '🛡️ 卫兵拦红线',
598
- }
599
- }
600
- }
601
- return { blocked: false }
602
- }
603
-
604
- /** 四级权限门禁判定:advisor(L0) / assistant(L1) / strategist(L2) / chief(L3)。 */
605
- export function evaluateChiefPermissionGate({
606
- permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
607
- hasChiefRiskAck = false,
608
- opClass = 'read',
609
- tool = '',
610
- approvedOnce = false,
611
- } = {}) {
612
- const mode = normalizePermissionMode(permissionMode, { requireAck: true, hasChiefRiskAck })
613
- const meta = CHIEF_PERMISSION_META[mode] || CHIEF_PERMISSION_META.advisor
614
-
615
- if (opClass === 'read' || opClass === 'elevation_request') {
616
- return { decision: 'allow', mode }
617
- }
618
-
619
- if (opClass === 'chief_system') {
620
- if (mode === 'advisor') {
621
- return {
622
- decision: 'deny_mode',
623
- mode,
624
- requiredMode: 'assistant',
625
- error: '当前处于「L0 · 顾问模式(只读)」,仅允许分析与建议,不能修改参谋记忆、档案或看板配置。可向用户申请提权至「L1 · 助手模式」。',
626
- badge: '🔒 L0禁改参谋系统',
627
- }
628
- }
629
- return { decision: 'allow', mode }
630
- }
631
-
632
- // 'workspace' or 'workflow'
633
- if (mode === 'advisor' || mode === 'assistant') {
634
- const targetDesc = opClass === 'workspace' ? '修改项目工作区或执行系统命令' : '调整主对话及子代理工作流'
635
- return {
636
- decision: 'deny_mode',
637
- mode,
638
- requiredMode: 'strategist',
639
- error: `当前处于「${meta.level} · ${meta.title}」,禁止${targetDesc}(${tool})。如需执行,请向用户申请提权至「L2 · 参谋模式(逐项授权)」或「L3 · 参谋长模式」。`,
640
- badge: `🔒 ${meta.level}禁止操作`,
641
- }
642
- }
643
-
644
- if (mode === 'strategist') {
645
- if (approvedOnce) {
646
- return { decision: 'allow_approved', mode }
647
- }
648
- return {
649
- decision: 'require_approval',
650
- mode,
651
- requiredMode: 'strategist',
652
- error: '「L2 · 参谋模式」要求先通过操作授权弹窗由用户逐项确认。',
653
- badge: '🛡️ 待逐项确认',
654
- }
655
- }
656
-
657
- // mode === 'chief'
658
- if (!hasChiefRiskAck) {
659
- return {
660
- decision: 'deny_unacknowledged_l3',
661
- mode: 'advisor',
662
- requiredMode: 'chief',
663
- error: '未检测到「L3 · 参谋长模式」风险知悉确认状态(chiefRiskAck),后端拒绝高权限自主执行。',
664
- badge: '🛡️ L3未授权拦截',
665
- }
666
- }
667
- return { decision: 'allow', mode: 'chief' }
668
- }
669
-
670
386
  function displayRelTarget(cwd, rawTarget) {
671
387
  const raw = String(rawTarget || '').trim()
672
388
  if (!raw) return '工作区'
@@ -795,22 +511,28 @@ export function describeControlledOperationMeta(tool, args = {}, cwd = '') {
795
511
  * 用户模式 -> 操作请求 -> 安全卫兵硬性规则 -> 权限判定 -> 执行器 -> 审计日志
796
512
  */
797
513
  export async function executeChiefToolCall(deps, call, execCtx = {}) {
514
+ const startedAt = performance.now()
798
515
  const tool = String(call && (call.tool || call.name) || '').trim()
799
516
  const args = (call && call.args && typeof call.args === 'object') ? call.args : (call && typeof call === 'object' ? call : {})
800
517
  const hasChiefRiskAck = Boolean(execCtx.hasChiefRiskAck)
518
+ const policyPlugins = Array.isArray(execCtx.policyPlugins) ? execCtx.policyPlugins : []
801
519
  const permissionMode = normalizePermissionMode(execCtx.permissionMode, { requireAck: true, hasChiefRiskAck })
802
520
  const cwd = String(execCtx.cwd || process.cwd())
803
521
  const rootId = String(execCtx.rootId || '')
804
522
  const board = execCtx.board || {}
805
523
  const readOnlyToolsOnly = Boolean(execCtx.readOnlyToolsOnly)
806
524
  const approvedOnce = Boolean(execCtx.approvedOnce)
525
+ const capabilityScope = execCtx.capabilityScope || null
807
526
 
808
527
  const writeAudit = (entry) => {
809
528
  if (typeof execCtx.recordAuditFn === 'function') {
810
529
  try {
530
+ const durationMs = Math.max(0, Math.round(performance.now() - startedAt))
811
531
  execCtx.recordAuditFn({
812
532
  mode: permissionMode,
813
533
  tool,
534
+ durationMs,
535
+ summary: redactAuditText(entry.summary || entry.reason || '', 220),
814
536
  by: execCtx.by || 'chief',
815
537
  ...entry,
816
538
  })
@@ -831,7 +553,7 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
831
553
 
832
554
  const opClass = getToolOpClass(tool)
833
555
  if (readOnlyToolsOnly && opClass !== 'read') {
834
- writeAudit({ stage: 'read_only_guard', decision: 'denied', operation: tool, target: '', reason: '后台复盘仅允许只读核验', outcome: 'blocked' })
556
+ writeAudit({ stage: 'read_only_guard', rule: 'read_only_guard', decision: 'denied', operation: tool, target: '', reason: '后台复盘仅允许只读核验', outcome: 'blocked' })
835
557
  return deny(`后台复盘轮次仅允许只读核验工具(${tool} 已跳过)`)
836
558
  }
837
559
 
@@ -841,38 +563,141 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
841
563
  const resolvedAbsTarget = rawTargetPath ? path.resolve(cwd, rawTargetPath) : ''
842
564
  const rawCommand = tool === 'run_command' ? String(args.command || args.cmd || '').trim() : ''
843
565
 
844
- // Stage 3: 安全卫兵硬性规则(优先于任何权限等级与逐项批准)
566
+ // Stage 3: 安全卫兵硬性规则(优先于任何权限等级、策略插件与逐项批准)
845
567
  const guardRes = evaluateSafetyGuardHardRules({
846
568
  tool,
847
569
  opClass,
848
570
  targetPath: resolvedAbsTarget,
849
571
  command: rawCommand,
572
+ args,
850
573
  cwd,
851
574
  board,
852
575
  })
853
576
  if (guardRes.blocked) {
854
577
  writeAudit({
855
578
  stage: 'safety_guard',
579
+ rule: guardRes.rule || 'hard_guard',
856
580
  decision: 'blocked',
857
581
  operation: tool,
858
582
  target: displayRelTarget(cwd, resolvedAbsTarget) || clamp(rawCommand, 80) || tool,
859
583
  reason: guardRes.reason,
860
584
  outcome: 'blocked',
861
585
  })
862
- return deny(guardRes.reason, guardRes.badge, { blockedBySafetyGuard: true })
586
+ return deny(guardRes.reason, guardRes.badge, { blockedBySafetyGuard: true, rule: guardRes.rule || 'hard_guard' })
863
587
  }
864
588
 
865
- // Stage 4: 四级权限判定
589
+ // Stage 3.5: 动态物理驻墙检验(同样不受 L3 与逐项放行绕过,require_approval_cmd 转为弹窗确认)
590
+ const wallRes = evaluateGuardWalls({
591
+ tool,
592
+ opClass,
593
+ targetPath: resolvedAbsTarget,
594
+ command: rawCommand,
595
+ args,
596
+ cwd,
597
+ })
598
+ if (wallRes.decision === 'block') {
599
+ writeAudit({
600
+ stage: 'guard_wall',
601
+ rule: wallRes.rule || 'guard_wall_block',
602
+ decision: 'blocked',
603
+ operation: tool,
604
+ target: displayRelTarget(cwd, resolvedAbsTarget) || clamp(rawCommand, 80) || tool,
605
+ reason: wallRes.reason,
606
+ outcome: 'blocked',
607
+ })
608
+ return deny(wallRes.reason, wallRes.badge || '🧱 物理墙拦截', {
609
+ blockedByGuardWall: true,
610
+ blockedBySafetyGuard: true,
611
+ rule: wallRes.rule || 'guard_wall_block',
612
+ wallId: wallRes.wallId,
613
+ })
614
+ }
615
+ if (wallRes.decision === 'require_approval' && !approvedOnce) {
616
+ const meta = describeControlledOperationMeta(tool, args, cwd)
617
+ const computedScope = buildCapabilityScope({ kind: 'tool', tool, args, cwd })
618
+ const approvalObj = typeof execCtx.queueApprovalFn === 'function'
619
+ ? await execCtx.queueApprovalFn({
620
+ category: meta.category,
621
+ operationLabel: meta.operationLabel,
622
+ targetLabel: meta.targetLabel,
623
+ reason: wallRes.reason,
624
+ impact: meta.impact,
625
+ preview: meta.preview,
626
+ kind: 'tool',
627
+ capabilityScope: computedScope,
628
+ payload: { tool, args: { ...args }, cwd, rootId, sessionId: execCtx.sessionId || rootId },
629
+ by: execCtx.by || 'guard_wall',
630
+ })
631
+ : null
632
+ writeAudit({
633
+ stage: 'guard_wall',
634
+ rule: wallRes.rule || 'guard_wall_require_approval',
635
+ decision: 'pending_approval',
636
+ operation: meta.operationLabel,
637
+ target: meta.targetLabel,
638
+ reason: wallRes.reason,
639
+ outcome: 'pending',
640
+ })
641
+ return {
642
+ tool,
643
+ ok: false,
644
+ pendingApproval: true,
645
+ approvalId: (approvalObj && approvalObj.id) || '',
646
+ approval: approvalObj || null,
647
+ error: `${wallRes.reason}。已为您弹出「操作授权请求」弹窗,等待点击「允许本次操作」。`,
648
+ badge: wallRes.badge || '🧱 物理墙待确认',
649
+ }
650
+ }
651
+
652
+ // Stage 4: 四级权限 + capabilities + Policy Plugin + 单次作用域判定
866
653
  const gateRes = evaluateChiefPermissionGate({
867
654
  permissionMode,
868
655
  hasChiefRiskAck,
869
656
  opClass,
870
657
  tool,
871
658
  approvedOnce,
659
+ capabilityScope,
660
+ actualRequest: { kind: 'tool', tool, args, cwd },
661
+ policyPlugins,
662
+ targetPath: resolvedAbsTarget,
663
+ command: rawCommand,
664
+ cwd,
872
665
  })
666
+ if (gateRes.decision === 'deny_policy_plugin') {
667
+ writeAudit({
668
+ stage: 'policy_plugin',
669
+ rule: gateRes.rule || 'policy_plugin',
670
+ decision: 'blocked',
671
+ operation: tool,
672
+ target: rawTargetPath || clamp(rawCommand, 60) || tool,
673
+ reason: gateRes.error,
674
+ outcome: 'blocked',
675
+ })
676
+ return deny(gateRes.error, gateRes.badge, {
677
+ blockedByPolicyPlugin: true,
678
+ pluginId: gateRes.pluginId || '',
679
+ rule: gateRes.rule || 'policy_plugin',
680
+ })
681
+ }
682
+ if (gateRes.decision === 'deny_scope_mismatch') {
683
+ writeAudit({
684
+ stage: 'scope_guard',
685
+ rule: gateRes.rule || 'capability_scope_mismatch',
686
+ decision: 'rejected',
687
+ operation: tool,
688
+ target: rawTargetPath || clamp(rawCommand, 60) || tool,
689
+ reason: gateRes.error,
690
+ outcome: 'rejected',
691
+ })
692
+ return deny(gateRes.error, gateRes.badge, {
693
+ deniedByScopeMismatch: true,
694
+ rule: gateRes.rule || 'capability_scope_mismatch',
695
+ })
696
+ }
873
697
  if (gateRes.decision === 'deny_mode' || gateRes.decision === 'deny_unacknowledged_l3') {
874
698
  writeAudit({
875
699
  stage: 'permission_gate',
700
+ rule: gateRes.rule || gateRes.decision,
876
701
  decision: gateRes.decision,
877
702
  operation: tool,
878
703
  target: rawTargetPath || clamp(rawCommand, 60) || String(args.agent || args.op || tool),
@@ -887,6 +712,7 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
887
712
  }
888
713
  if (gateRes.decision === 'require_approval') {
889
714
  const meta = describeControlledOperationMeta(tool, args, cwd)
715
+ const computedScope = buildCapabilityScope({ kind: 'tool', tool, args, cwd })
890
716
  const approvalObj = typeof execCtx.queueApprovalFn === 'function'
891
717
  ? await execCtx.queueApprovalFn({
892
718
  category: meta.category,
@@ -896,12 +722,14 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
896
722
  impact: meta.impact,
897
723
  preview: meta.preview,
898
724
  kind: 'tool',
725
+ capabilityScope: computedScope,
899
726
  payload: { tool, args: { ...args }, cwd, rootId, sessionId: execCtx.sessionId || rootId },
900
727
  by: execCtx.by || 'chief',
901
728
  })
902
729
  : null
903
730
  writeAudit({
904
731
  stage: 'permission_gate',
732
+ rule: gateRes.rule || 'require_approval',
905
733
  decision: 'pending_approval',
906
734
  operation: meta.operationLabel,
907
735
  target: meta.targetLabel,
@@ -914,15 +742,41 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
914
742
  pendingApproval: true,
915
743
  approvalId: (approvalObj && approvalObj.id) || '',
916
744
  approval: approvalObj || null,
917
- error: `当前处于「L2 · 参谋模式」,操作「${meta.operationLabel} → ${meta.targetLabel}」已提交操作授权弹窗,等待用户点击「允许本次操作」。`,
745
+ error: `当前处于「${CHIEF_PERMISSION_META[gateRes.mode]?.level || 'L2'} · ${CHIEF_PERMISSION_META[gateRes.mode]?.title || '参谋模式'}」,操作「${meta.operationLabel} → ${meta.targetLabel}」已提交操作授权弹窗,等待用户点击「允许本次操作」。`,
918
746
  badge: `🛡️ 待确认 ${clamp(meta.targetLabel, 18)}`,
919
747
  }
920
748
  }
921
749
 
922
- // Stage 5: 执行器
750
+ // Stage 5: 执行器(包含写入路径能力前缀二次确认)
751
+ const allowedWritePrefixes = gateRes && gateRes.capabilities && Array.isArray(gateRes.capabilities.fsWritePrefixes)
752
+ ? gateRes.capabilities.fsWritePrefixes
753
+ : null
754
+ if ((tool === 'write_file' || tool === 'edit_file') && rawTargetPath) {
755
+ const writePathCheck = validateWorkspacePath(cwd, resolvedAbsTarget, {
756
+ mode: 'write',
757
+ allowedSubPrefixes: allowedWritePrefixes,
758
+ })
759
+ if (writePathCheck.blocked) {
760
+ writeAudit({
761
+ stage: writePathCheck.stage || 'safety_guard',
762
+ rule: writePathCheck.rule || 'workspace_write_denied',
763
+ decision: 'blocked',
764
+ operation: tool,
765
+ target: displayRelTarget(cwd, resolvedAbsTarget),
766
+ reason: writePathCheck.reason,
767
+ outcome: 'blocked',
768
+ })
769
+ return deny(writePathCheck.reason, writePathCheck.badge, {
770
+ blockedBySafetyGuard: writePathCheck.stage === 'safety_guard',
771
+ rule: writePathCheck.rule,
772
+ })
773
+ }
774
+ }
775
+
923
776
  const finish = (res, opLabel, targetLabel) => {
924
777
  writeAudit({
925
778
  stage: 'executor',
779
+ rule: approvedOnce ? 'approved_once' : 'role_allow',
926
780
  decision: approvedOnce ? 'executed_approved' : 'executed',
927
781
  operation: opLabel || tool,
928
782
  target: targetLabel || '',
@@ -1235,10 +1089,12 @@ export async function runChiefAgenticLoop(deps, {
1235
1089
  allowTextFallbackOnVisionMiss = false,
1236
1090
  permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
1237
1091
  hasChiefRiskAck = false,
1092
+ policyPlugins = [],
1238
1093
  board = null,
1239
1094
  maxSteps = 4,
1240
1095
  readOnlyToolsOnly = false,
1241
1096
  disableTools = false,
1097
+ lazyDeferWorkspaceWritesToLead = false,
1242
1098
  callLlmFn,
1243
1099
  extractJsonFn,
1244
1100
  upsertArchiveFn,
@@ -1316,12 +1172,54 @@ export async function runChiefAgenticLoop(deps, {
1316
1172
  ranToolsOnLastStep = true
1317
1173
  const stepOutputs = []
1318
1174
  for (const c of calls) {
1175
+ const cToolName = String(c && (c.tool || c.name) || '').trim()
1176
+ if (
1177
+ lazyDeferWorkspaceWritesToLead
1178
+ && (cToolName === 'write_file' || cToolName === 'edit_file' || cToolName === 'run_command')
1179
+ ) {
1180
+ const preDef = evaluatePreExecuteDefense({
1181
+ tool: cToolName,
1182
+ args: (c && c.args && typeof c.args === 'object') ? c.args : {},
1183
+ cwd,
1184
+ board,
1185
+ })
1186
+ if (!preDef || preDef.decision !== 'deny') {
1187
+ if (typeof recordAuditFn === 'function') {
1188
+ try {
1189
+ recordAuditFn({
1190
+ mode: perm,
1191
+ stage: 'lazy_intervention',
1192
+ rule: 'lead_first_defer',
1193
+ decision: 'deferred_to_lead',
1194
+ operation: cToolName,
1195
+ target: clamp(String((c.args && (c.args.path || c.args.command || c.args.cmd)) || cToolName), 80),
1196
+ reason: '懒介入机制生效:主对话在线且用户未指定参谋长亲自操作,改为派发 @lead 执行请求',
1197
+ outcome: 'deferred',
1198
+ by: 'chief',
1199
+ })
1200
+ } catch {}
1201
+ }
1202
+ const deferRes = {
1203
+ tool: cToolName,
1204
+ ok: false,
1205
+ denied: true,
1206
+ deferredByLazyIntervention: true,
1207
+ badge: '🤝 懒介入转主对话',
1208
+ error: '懒介入机制生效:当前主对话 (@lead) 在线可用且用户未指定参谋长亲自操刀,已遏制直接改动工作区或跑终端命令。请去掉工作区 toolCalls,改为在最终 JSON 的 relays 中向 target="lead" 下发结构化执行请求!',
1209
+ }
1210
+ toolRecords.push({ step: step + 1, call: c, result: deferRes })
1211
+ if (!toolBadges.includes(deferRes.badge)) toolBadges.push(deferRes.badge)
1212
+ stepOutputs.push({ tool: cToolName, args: c.args || {}, result: deferRes })
1213
+ continue
1214
+ }
1215
+ }
1319
1216
  const execRes = await executeChiefToolCall(deps, c, {
1320
1217
  rootId,
1321
1218
  sessionId: sessionId || rootId,
1322
1219
  cwd,
1323
1220
  permissionMode: perm,
1324
1221
  hasChiefRiskAck,
1222
+ policyPlugins,
1325
1223
  board,
1326
1224
  readOnlyToolsOnly,
1327
1225
  upsertArchiveFn,