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.
- package/CHANGELOG.md +42 -12
- package/README.en.md +143 -116
- package/README.md +134 -142
- package/api-routes.js +19 -2
- package/board-actions.js +72 -1
- package/board-schema.js +1 -1
- package/chief-approvals.js +241 -81
- package/chief-archives.js +35 -0
- package/chief-commands.js +615 -108
- package/chief-executor.js +279 -555
- package/chief-network.js +157 -8
- package/chief-review.js +33 -1
- package/chief-state.js +497 -81
- package/chief-view.js +21 -6
- package/client.js +1953 -506
- package/model-tools.js +78 -2
- package/package.json +35 -24
- package/runtime-hooks.js +108 -2
- package/safety/audit-log.js +95 -0
- package/safety/command-analyzer.js +339 -0
- package/safety/guard-walls.js +993 -0
- package/safety/index.js +78 -0
- package/safety/invariant-guards.js +280 -0
- package/safety/path-guard.js +227 -0
- package/safety/policy-engine.js +387 -0
- package/safety/policy-plugin.js +391 -0
- package/safety/tool-gate.js +278 -0
- package/subagent-runtime.js +9 -2
|
@@ -0,0 +1,993 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* safety/guard-walls.js
|
|
3
|
+
*
|
|
4
|
+
* Dynamic, reusable physical guard walls (`guard-walls.json`) and whole-session
|
|
5
|
+
* `tools/pre-execute` physical defense gate for DSH Chief.
|
|
6
|
+
*
|
|
7
|
+
* Walls persist independently of individual conversations (supporting `global`,
|
|
8
|
+
* `workspace`, and `paused` states) and require human confirmation to mutate.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import fs from 'node:fs'
|
|
12
|
+
import os from 'node:os'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import crypto from 'node:crypto'
|
|
15
|
+
import { threadId } from 'node:worker_threads'
|
|
16
|
+
import { analyzeCommand, normalizeCommandForSecurity } from './command-analyzer.js'
|
|
17
|
+
import {
|
|
18
|
+
HUMAN_BOUNDS_CONFIRM_TOKEN,
|
|
19
|
+
hasForbiddenNtfsAds,
|
|
20
|
+
hasWindowsReservedDeviceName,
|
|
21
|
+
isSensitiveCredentialPath,
|
|
22
|
+
safeRealpath,
|
|
23
|
+
validateWorkspacePath,
|
|
24
|
+
verifyBoundsWriteAuth,
|
|
25
|
+
} from './path-guard.js'
|
|
26
|
+
import {
|
|
27
|
+
checkForbiddenBounds,
|
|
28
|
+
commandTouchesSensitiveCredential,
|
|
29
|
+
isDestructiveShellCommand,
|
|
30
|
+
} from './invariant-guards.js'
|
|
31
|
+
|
|
32
|
+
const GUARD_WALLS_CAP = 80
|
|
33
|
+
const GUARD_WALL_LOCK_STALE_MS = 10_000
|
|
34
|
+
const GUARD_WALL_LOCK_WAIT_MS = 3_500
|
|
35
|
+
const heldGuardWallLocks = new Set()
|
|
36
|
+
|
|
37
|
+
let cachedGuardWallStore = null
|
|
38
|
+
|
|
39
|
+
export const GUARD_WALL_RULE_TYPES = Object.freeze([
|
|
40
|
+
'forbid_path',
|
|
41
|
+
'restrict_write',
|
|
42
|
+
'forbid_cmd',
|
|
43
|
+
'require_approval_cmd',
|
|
44
|
+
'deny_tool',
|
|
45
|
+
])
|
|
46
|
+
|
|
47
|
+
export const GUARD_WALL_SCOPES = Object.freeze(['global', 'workspace', 'paused'])
|
|
48
|
+
|
|
49
|
+
const SAFE_META_TOOLS = new Set([
|
|
50
|
+
'chief_board',
|
|
51
|
+
'chief_memory',
|
|
52
|
+
'chief_boundaries',
|
|
53
|
+
'chief_handoff',
|
|
54
|
+
'todo_write',
|
|
55
|
+
'create_goal',
|
|
56
|
+
'update_goal',
|
|
57
|
+
'team_task_list',
|
|
58
|
+
])
|
|
59
|
+
|
|
60
|
+
const READ_ONLY_FS_TOOLS = new Set([
|
|
61
|
+
'read',
|
|
62
|
+
'read_image',
|
|
63
|
+
'read_file',
|
|
64
|
+
'view_file',
|
|
65
|
+
'list_dir',
|
|
66
|
+
'glob',
|
|
67
|
+
'grep',
|
|
68
|
+
'search_files',
|
|
69
|
+
'find_by_name',
|
|
70
|
+
])
|
|
71
|
+
|
|
72
|
+
const SHELL_TOOLS = new Set([
|
|
73
|
+
'run_command',
|
|
74
|
+
'bash',
|
|
75
|
+
'sh',
|
|
76
|
+
'shell',
|
|
77
|
+
'powershell',
|
|
78
|
+
'pwsh',
|
|
79
|
+
'cmd',
|
|
80
|
+
'terminal',
|
|
81
|
+
'exec',
|
|
82
|
+
'execute_command',
|
|
83
|
+
])
|
|
84
|
+
|
|
85
|
+
const WORKSPACE_WRITE_TOOLS = new Set([
|
|
86
|
+
'write',
|
|
87
|
+
'edit',
|
|
88
|
+
'write_file',
|
|
89
|
+
'edit_file',
|
|
90
|
+
'multi_edit',
|
|
91
|
+
'replace_file_content',
|
|
92
|
+
'multi_replace_file_content',
|
|
93
|
+
'apply_patch',
|
|
94
|
+
'create_file',
|
|
95
|
+
'delete_file',
|
|
96
|
+
'remove_file',
|
|
97
|
+
'move_file',
|
|
98
|
+
'rename_file',
|
|
99
|
+
'notebook_edit',
|
|
100
|
+
])
|
|
101
|
+
|
|
102
|
+
function sleepSync(ms) {
|
|
103
|
+
if (!ms || ms <= 0) return
|
|
104
|
+
try {
|
|
105
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
|
106
|
+
} catch {
|
|
107
|
+
const deadline = Date.now() + ms
|
|
108
|
+
while (Date.now() < deadline) {
|
|
109
|
+
// spin fallback
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function guardWallsFilePath() {
|
|
115
|
+
const override = String(process.env.DSH_CHIEF_WALLS_FILE || '').trim()
|
|
116
|
+
if (override) return path.resolve(override)
|
|
117
|
+
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
118
|
+
return path.join(home, 'chief', 'guard-walls.json')
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function normalizeCmpPath(rawPath) {
|
|
122
|
+
if (!rawPath) return ''
|
|
123
|
+
const resolved = safeRealpath(String(rawPath).trim())
|
|
124
|
+
const slash = resolved.replace(/\\/g, '/').replace(/\/+$/, '')
|
|
125
|
+
return process.platform === 'win32' ? slash.toLowerCase() : slash
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function isSubOrEqualPath(baseCmp, targetCmp) {
|
|
129
|
+
if (!baseCmp || !targetCmp) return false
|
|
130
|
+
if (baseCmp === targetCmp) return true
|
|
131
|
+
return targetCmp.startsWith(baseCmp + '/')
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function acquireGuardWallLock(file) {
|
|
135
|
+
const lockFile = file + '.lock'
|
|
136
|
+
fs.mkdirSync(path.dirname(lockFile), { recursive: true })
|
|
137
|
+
const deadline = Date.now() + GUARD_WALL_LOCK_WAIT_MS
|
|
138
|
+
let spin = 0
|
|
139
|
+
while (true) {
|
|
140
|
+
try {
|
|
141
|
+
const fd = fs.openSync(lockFile, 'wx')
|
|
142
|
+
try {
|
|
143
|
+
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, threadId, at: Date.now() }))
|
|
144
|
+
} finally {
|
|
145
|
+
fs.closeSync(fd)
|
|
146
|
+
}
|
|
147
|
+
heldGuardWallLocks.add(lockFile)
|
|
148
|
+
let released = false
|
|
149
|
+
return () => {
|
|
150
|
+
if (released) return
|
|
151
|
+
released = true
|
|
152
|
+
heldGuardWallLocks.delete(lockFile)
|
|
153
|
+
try { fs.unlinkSync(lockFile) } catch {}
|
|
154
|
+
}
|
|
155
|
+
} catch (err) {
|
|
156
|
+
const code = err && err.code
|
|
157
|
+
if (code === 'EEXIST' || code === 'EPERM' || code === 'EACCES' || code === 'EBUSY') {
|
|
158
|
+
try {
|
|
159
|
+
const st = fs.statSync(lockFile)
|
|
160
|
+
if (Date.now() - st.mtimeMs > GUARD_WALL_LOCK_STALE_MS) {
|
|
161
|
+
try { fs.unlinkSync(lockFile) } catch {}
|
|
162
|
+
continue
|
|
163
|
+
}
|
|
164
|
+
} catch {}
|
|
165
|
+
if (Date.now() >= deadline) {
|
|
166
|
+
throw new Error('guard-walls.json 并发写锁超时')
|
|
167
|
+
}
|
|
168
|
+
sleepSync(Math.min(25, 4 + spin * 2 + Math.floor(Math.random() * 6)))
|
|
169
|
+
spin += 1
|
|
170
|
+
continue
|
|
171
|
+
}
|
|
172
|
+
throw err
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function atomicWriteGuardWalls(file, payload) {
|
|
178
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
179
|
+
const tmp = `${file}.${process.pid}.${threadId}.${Date.now()}.tmp`
|
|
180
|
+
const json = JSON.stringify(payload, null, 2)
|
|
181
|
+
fs.writeFileSync(tmp, json, 'utf8')
|
|
182
|
+
for (let i = 0; i < 6; i += 1) {
|
|
183
|
+
try {
|
|
184
|
+
fs.renameSync(tmp, file)
|
|
185
|
+
break
|
|
186
|
+
} catch (err) {
|
|
187
|
+
const code = err && err.code
|
|
188
|
+
if ((code === 'EPERM' || code === 'EACCES' || code === 'EBUSY') && i < 5) {
|
|
189
|
+
sleepSync(12 * (i + 1))
|
|
190
|
+
continue
|
|
191
|
+
}
|
|
192
|
+
try { fs.unlinkSync(tmp) } catch {}
|
|
193
|
+
throw err
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
let mtimeMs = 0
|
|
197
|
+
try { mtimeMs = fs.statSync(file).mtimeMs } catch {}
|
|
198
|
+
cachedGuardWallStore = { file, mtimeMs, data: payload }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function clampStr(text, maxLen = 160) {
|
|
202
|
+
return String(text == null ? '' : text).replace(/\s+/g, ' ').trim().slice(0, maxLen)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const GUARD_WALL_TYPE_LABELS = Object.freeze({
|
|
206
|
+
forbid_path: '禁碰路径',
|
|
207
|
+
restrict_write: '仅限目录可写',
|
|
208
|
+
forbid_cmd: '禁跑命令',
|
|
209
|
+
require_approval_cmd: '高危命令先请示',
|
|
210
|
+
deny_tool: '禁用工具',
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
function validatePatternsForRule(ruleType, patterns) {
|
|
214
|
+
if (!Array.isArray(patterns) || patterns.length === 0) {
|
|
215
|
+
return { ok: false, error: '物理驻墙必须至少包含 1 条有效匹配规则 (patterns)' }
|
|
216
|
+
}
|
|
217
|
+
const clean = []
|
|
218
|
+
for (const entry of patterns.slice(0, 96)) {
|
|
219
|
+
if (typeof entry !== 'string') {
|
|
220
|
+
return { ok: false, error: '物理驻墙规则条目必须为字符串' }
|
|
221
|
+
}
|
|
222
|
+
const trimmed = entry.trim()
|
|
223
|
+
if (!trimmed) continue
|
|
224
|
+
if (trimmed.length > 200) {
|
|
225
|
+
return { ok: false, error: '单条物理驻墙规则长度不可超过 200 字符' }
|
|
226
|
+
}
|
|
227
|
+
if (ruleType === 'restrict_write' && (trimmed === '*' || trimmed === '**' || trimmed === '/' || trimmed === '.')) {
|
|
228
|
+
return { ok: false, error: 'restrict_write 仅限收窄子目录白名单,禁止通配放宽符' }
|
|
229
|
+
}
|
|
230
|
+
if (ruleType === 'forbid_cmd' || ruleType === 'require_approval_cmd') {
|
|
231
|
+
if (/\([^)]*[+*][^)]*\)[+*{]/.test(trimmed)) {
|
|
232
|
+
return { ok: false, error: `物理墙命令规则含不安全嵌套量词:${trimmed}` }
|
|
233
|
+
}
|
|
234
|
+
try {
|
|
235
|
+
// eslint-disable-next-line no-new
|
|
236
|
+
new RegExp(trimmed, 'i')
|
|
237
|
+
} catch {
|
|
238
|
+
return { ok: false, error: `物理墙命令正则语法无效:${trimmed}` }
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
clean.push(trimmed)
|
|
242
|
+
}
|
|
243
|
+
if (!clean.length) {
|
|
244
|
+
return { ok: false, error: '物理驻墙必须至少包含 1 条非空规则' }
|
|
245
|
+
}
|
|
246
|
+
return { ok: true, list: [...new Set(clean)] }
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export function validateGuardWallInput(raw, { cwd = '' } = {}) {
|
|
250
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
251
|
+
return { ok: false, error: '物理驻墙对象格式无效' }
|
|
252
|
+
}
|
|
253
|
+
const title = clampStr(raw.title || '', 100)
|
|
254
|
+
if (!title) {
|
|
255
|
+
return { ok: false, error: '物理驻墙缺少名称 (title)' }
|
|
256
|
+
}
|
|
257
|
+
const ruleTypeRaw = String(raw.ruleType || 'forbid_path').trim()
|
|
258
|
+
const ruleType = GUARD_WALL_RULE_TYPES.includes(ruleTypeRaw) ? ruleTypeRaw : ''
|
|
259
|
+
if (!ruleType) {
|
|
260
|
+
return { ok: false, error: `不支持的物理驻墙规则类型:${ruleTypeRaw}` }
|
|
261
|
+
}
|
|
262
|
+
const scopeRaw = String(raw.scope || 'global').trim().toLowerCase()
|
|
263
|
+
const scope = GUARD_WALL_SCOPES.includes(scopeRaw) ? scopeRaw : 'global'
|
|
264
|
+
const rawPatterns = Array.isArray(raw.patterns)
|
|
265
|
+
? raw.patterns
|
|
266
|
+
: (typeof raw.pattern === 'string'
|
|
267
|
+
? raw.pattern.split(/[\r\n,;,;]+/).map(s => s.trim()).filter(Boolean)
|
|
268
|
+
: [])
|
|
269
|
+
const patCheck = validatePatternsForRule(ruleType, rawPatterns)
|
|
270
|
+
if (!patCheck.ok) return patCheck
|
|
271
|
+
|
|
272
|
+
const rawProj = String(raw.projectKey || raw.workspaceRoot || (scope === 'workspace' ? cwd : '') || '').trim()
|
|
273
|
+
const projectKey = rawProj ? normalizeCmpPath(rawProj) : ''
|
|
274
|
+
if (scope === 'workspace' && !projectKey) {
|
|
275
|
+
return { ok: false, error: '按工程绑定的物理驻墙需要有效的当前工程目录 (projectKey / cwd)' }
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const now = Date.now()
|
|
279
|
+
const idRaw = String(raw.id || '').trim()
|
|
280
|
+
const id = idRaw && /^[a-zA-Z0-9._-]{2,64}$/.test(idRaw)
|
|
281
|
+
? idRaw
|
|
282
|
+
: ('wall-' + crypto.randomBytes(4).toString('hex'))
|
|
283
|
+
|
|
284
|
+
return {
|
|
285
|
+
ok: true,
|
|
286
|
+
wall: {
|
|
287
|
+
id,
|
|
288
|
+
title,
|
|
289
|
+
scope,
|
|
290
|
+
projectKey,
|
|
291
|
+
ruleType,
|
|
292
|
+
patterns: patCheck.list,
|
|
293
|
+
writeOnly: Boolean(raw.writeOnly),
|
|
294
|
+
source: raw.source === 'chief_crafted' ? 'chief_crafted' : 'manual',
|
|
295
|
+
pinnedByUser: raw.pinnedByUser !== false,
|
|
296
|
+
reason: clampStr(raw.reason || '', 200),
|
|
297
|
+
createdAt: Number(raw.createdAt) || now,
|
|
298
|
+
updatedAt: now,
|
|
299
|
+
},
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export function normalizeGuardWall(raw, cwd = '') {
|
|
304
|
+
const checked = validateGuardWallInput(raw, { cwd })
|
|
305
|
+
return checked.ok ? checked.wall : null
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function loadGuardWallStoreFromDisk(file) {
|
|
309
|
+
if (!fs.existsSync(file)) {
|
|
310
|
+
return { version: 1, walls: [] }
|
|
311
|
+
}
|
|
312
|
+
try {
|
|
313
|
+
const st = fs.statSync(file)
|
|
314
|
+
if (cachedGuardWallStore && cachedGuardWallStore.file === file && cachedGuardWallStore.mtimeMs === st.mtimeMs) {
|
|
315
|
+
return cachedGuardWallStore.data
|
|
316
|
+
}
|
|
317
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
318
|
+
const walls = (Array.isArray(parsed && parsed.walls) ? parsed.walls : [])
|
|
319
|
+
.map(w => normalizeGuardWall(w, w && w.projectKey ? w.projectKey : ''))
|
|
320
|
+
.filter(Boolean)
|
|
321
|
+
.slice(0, GUARD_WALLS_CAP)
|
|
322
|
+
const data = { version: 1, walls }
|
|
323
|
+
cachedGuardWallStore = { file, mtimeMs: st.mtimeMs, data }
|
|
324
|
+
return data
|
|
325
|
+
} catch {
|
|
326
|
+
return { version: 1, walls: [] }
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export function isGuardWallActiveForCwd(wall, cwd = '') {
|
|
331
|
+
if (!wall || wall.scope === 'paused') return false
|
|
332
|
+
if (wall.scope === 'global') return true
|
|
333
|
+
if (wall.scope === 'workspace') {
|
|
334
|
+
const wallRoot = String(wall.projectKey || '').trim()
|
|
335
|
+
const curCmp = normalizeCmpPath(cwd)
|
|
336
|
+
if (!wallRoot || !curCmp) return false
|
|
337
|
+
return isSubOrEqualPath(wallRoot, curCmp) || isSubOrEqualPath(curCmp, wallRoot)
|
|
338
|
+
}
|
|
339
|
+
return false
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function listGuardWalls({ cwd = '' } = {}) {
|
|
343
|
+
const file = guardWallsFilePath()
|
|
344
|
+
const store = loadGuardWallStoreFromDisk(file)
|
|
345
|
+
const list = Array.isArray(store && store.walls) ? store.walls : []
|
|
346
|
+
return list.map(w => ({
|
|
347
|
+
...w,
|
|
348
|
+
activeNow: isGuardWallActiveForCwd(w, cwd),
|
|
349
|
+
}))
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function mergeSameTypeWallGroup(group, customTitle, cwd, now) {
|
|
353
|
+
if (!Array.isArray(group) || group.length < 2) {
|
|
354
|
+
return { ok: false, error: '合并同类物理驻墙需要至少 2 条同类型规则' }
|
|
355
|
+
}
|
|
356
|
+
const ruleType = group[0].ruleType
|
|
357
|
+
const seenPat = new Set()
|
|
358
|
+
const mergedPatterns = []
|
|
359
|
+
for (const w of group) {
|
|
360
|
+
for (const pat of (Array.isArray(w.patterns) ? w.patterns : [])) {
|
|
361
|
+
const s = String(pat || '').trim()
|
|
362
|
+
if (!s || seenPat.has(s)) continue
|
|
363
|
+
seenPat.add(s)
|
|
364
|
+
mergedPatterns.push(s)
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (mergedPatterns.length > 96) {
|
|
368
|
+
return { ok: false, error: '合并后的规则条目超出单墙上限(96 条),请分批合并' }
|
|
369
|
+
}
|
|
370
|
+
const patCheck = validatePatternsForRule(ruleType, mergedPatterns)
|
|
371
|
+
if (!patCheck.ok) return patCheck
|
|
372
|
+
|
|
373
|
+
const hasGlobal = group.some(w => w.scope === 'global')
|
|
374
|
+
const hasWorkspace = group.some(w => w.scope === 'workspace')
|
|
375
|
+
const scope = hasGlobal ? 'global' : (hasWorkspace ? 'workspace' : 'paused')
|
|
376
|
+
const firstProj = group.map(w => w.projectKey).find(Boolean) || normalizeCmpPath(cwd)
|
|
377
|
+
const projectKey = scope === 'workspace' ? firstProj : ''
|
|
378
|
+
if (scope === 'workspace' && !projectKey) {
|
|
379
|
+
return { ok: false, error: '合并本工程物理驻墙缺少有效工程路径' }
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const typeLabel = GUARD_WALL_TYPE_LABELS[ruleType] || ruleType
|
|
383
|
+
const uniqueTitles = [...new Set(group.map(w => clampStr(w.title || '', 36)).filter(Boolean))]
|
|
384
|
+
const previewTitles = uniqueTitles.slice(0, 2).join(' + ') + (uniqueTitles.length > 2 ? ' 等' : '')
|
|
385
|
+
const finalTitle = clampStr(customTitle || '', 100)
|
|
386
|
+
|| clampStr(`${typeLabel}合集(${group.length} 合 1)${previewTitles ? ':' + previewTitles : ''}`, 100)
|
|
387
|
+
const uniqueReasons = [...new Set(group.map(w => clampStr(w.reason || '', 120)).filter(Boolean))]
|
|
388
|
+
const mergedReason = clampStr(uniqueReasons.join(';'), 200)
|
|
389
|
+
const earliestCreated = group.reduce((min, w) => {
|
|
390
|
+
const t = Number(w.createdAt) || now
|
|
391
|
+
return t < min ? t : min
|
|
392
|
+
}, now)
|
|
393
|
+
|
|
394
|
+
return {
|
|
395
|
+
ok: true,
|
|
396
|
+
wall: {
|
|
397
|
+
id: 'wall-' + crypto.randomBytes(4).toString('hex'),
|
|
398
|
+
title: finalTitle,
|
|
399
|
+
scope,
|
|
400
|
+
projectKey,
|
|
401
|
+
ruleType,
|
|
402
|
+
patterns: patCheck.list,
|
|
403
|
+
writeOnly: group.every(w => Boolean(w.writeOnly)),
|
|
404
|
+
source: group.every(w => w.source === 'chief_crafted') ? 'chief_crafted' : 'manual',
|
|
405
|
+
pinnedByUser: group.some(w => w.pinnedByUser !== false),
|
|
406
|
+
reason: mergedReason,
|
|
407
|
+
createdAt: earliestCreated,
|
|
408
|
+
updatedAt: now,
|
|
409
|
+
},
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export function mutateGuardWalls({
|
|
414
|
+
op = 'save',
|
|
415
|
+
wall = null,
|
|
416
|
+
wallId = '',
|
|
417
|
+
wallIds = [],
|
|
418
|
+
autoGroup = false,
|
|
419
|
+
title = '',
|
|
420
|
+
scope = '',
|
|
421
|
+
cwd = '',
|
|
422
|
+
callerOrigin = '',
|
|
423
|
+
humanConfirmToken = null,
|
|
424
|
+
} = {}) {
|
|
425
|
+
const isHumanVerified = humanConfirmToken === HUMAN_BOUNDS_CONFIRM_TOKEN
|
|
426
|
+
&& (callerOrigin === 'human_ui' || callerOrigin === 'human_approval')
|
|
427
|
+
const auth = isHumanVerified
|
|
428
|
+
? verifyBoundsWriteAuth({ action: 'bounds.set', callerOrigin, humanConfirmToken })
|
|
429
|
+
: { ok: false }
|
|
430
|
+
if (!auth.ok) {
|
|
431
|
+
return {
|
|
432
|
+
ok: false,
|
|
433
|
+
blockedBySafetyGuard: true,
|
|
434
|
+
rule: 'guard_wall_human_only',
|
|
435
|
+
error: '安全卫兵硬拦截:物理驻墙仅允许人类在面板确认筑墙或调整状态,严禁任何模型私自改动或解除物理墙!',
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const file = guardWallsFilePath()
|
|
440
|
+
const release = acquireGuardWallLock(file)
|
|
441
|
+
try {
|
|
442
|
+
const store = loadGuardWallStoreFromDisk(file)
|
|
443
|
+
const walls = Array.isArray(store.walls) ? store.walls.map(w => ({ ...w })) : []
|
|
444
|
+
const now = Date.now()
|
|
445
|
+
let targetWall = null
|
|
446
|
+
let mergedCount = 0
|
|
447
|
+
let createdCount = 0
|
|
448
|
+
|
|
449
|
+
if (op === 'save') {
|
|
450
|
+
const res = validateGuardWallInput(wall, { cwd })
|
|
451
|
+
if (!res.ok) return { ok: false, error: res.error }
|
|
452
|
+
const nextWall = res.wall
|
|
453
|
+
const idx = walls.findIndex(w => w.id === nextWall.id)
|
|
454
|
+
if (idx >= 0) {
|
|
455
|
+
nextWall.createdAt = walls[idx].createdAt || nextWall.createdAt
|
|
456
|
+
walls[idx] = nextWall
|
|
457
|
+
} else {
|
|
458
|
+
if (walls.length >= GUARD_WALLS_CAP) {
|
|
459
|
+
walls.shift()
|
|
460
|
+
}
|
|
461
|
+
walls.push(nextWall)
|
|
462
|
+
}
|
|
463
|
+
targetWall = nextWall
|
|
464
|
+
} else if (op === 'set_scope') {
|
|
465
|
+
const id = String(wallId || (wall && wall.id) || '').trim()
|
|
466
|
+
const idx = walls.findIndex(w => w.id === id)
|
|
467
|
+
if (idx < 0) return { ok: false, error: `未找到物理驻墙:${id || '空 ID'}` }
|
|
468
|
+
const nextScope = String(scope || '').trim().toLowerCase()
|
|
469
|
+
if (!GUARD_WALL_SCOPES.includes(nextScope)) {
|
|
470
|
+
return { ok: false, error: `无效的物理驻墙状态:${scope}` }
|
|
471
|
+
}
|
|
472
|
+
const nextProj = nextScope === 'workspace'
|
|
473
|
+
? (walls[idx].projectKey || normalizeCmpPath(cwd))
|
|
474
|
+
: walls[idx].projectKey
|
|
475
|
+
if (nextScope === 'workspace' && !nextProj) {
|
|
476
|
+
return { ok: false, error: '切换为「仅当前工程」前缺少有效工程路径' }
|
|
477
|
+
}
|
|
478
|
+
walls[idx] = {
|
|
479
|
+
...walls[idx],
|
|
480
|
+
scope: nextScope,
|
|
481
|
+
projectKey: nextProj,
|
|
482
|
+
updatedAt: now,
|
|
483
|
+
}
|
|
484
|
+
targetWall = walls[idx]
|
|
485
|
+
} else if (op === 'remove') {
|
|
486
|
+
const id = String(wallId || (wall && wall.id) || '').trim()
|
|
487
|
+
const idx = walls.findIndex(w => w.id === id)
|
|
488
|
+
if (idx < 0) return { ok: false, error: `未找到物理驻墙:${id || '空 ID'}` }
|
|
489
|
+
targetWall = walls[idx]
|
|
490
|
+
walls.splice(idx, 1)
|
|
491
|
+
} else if (op === 'merge') {
|
|
492
|
+
if (autoGroup) {
|
|
493
|
+
const buckets = new Map()
|
|
494
|
+
for (const w of walls) {
|
|
495
|
+
if (!w || !w.ruleType) continue
|
|
496
|
+
if (w.scope !== 'paused' && w.scope !== 'global' && !isGuardWallActiveForCwd(w, cwd)) continue
|
|
497
|
+
const bucketKey = (w.scope === 'paused' ? 'paused|' : 'active|') + w.ruleType
|
|
498
|
+
if (!buckets.has(bucketKey)) buckets.set(bucketKey, [])
|
|
499
|
+
buckets.get(bucketKey).push(w)
|
|
500
|
+
}
|
|
501
|
+
const mergeGroups = [...buckets.values()].filter(g => g.length >= 2)
|
|
502
|
+
if (!mergeGroups.length) {
|
|
503
|
+
return { ok: false, code: 'NOTHING_TO_MERGE', error: '当前没有 2 条及以上相同类型的物理驻墙可供合并' }
|
|
504
|
+
}
|
|
505
|
+
const replaceAtFirstId = new Map()
|
|
506
|
+
const dropIds = new Set()
|
|
507
|
+
for (const g of mergeGroups) {
|
|
508
|
+
const built = mergeSameTypeWallGroup(g, '', cwd, now)
|
|
509
|
+
if (!built.ok) return built
|
|
510
|
+
replaceAtFirstId.set(g[0].id, built.wall)
|
|
511
|
+
for (let i = 1; i < g.length; i += 1) dropIds.add(g[i].id)
|
|
512
|
+
mergedCount += g.length
|
|
513
|
+
createdCount += 1
|
|
514
|
+
targetWall = built.wall
|
|
515
|
+
}
|
|
516
|
+
const rebuiltWalls = []
|
|
517
|
+
for (const w of walls) {
|
|
518
|
+
if (dropIds.has(w.id)) continue
|
|
519
|
+
rebuiltWalls.push(replaceAtFirstId.get(w.id) || w)
|
|
520
|
+
}
|
|
521
|
+
walls.length = 0
|
|
522
|
+
walls.push(...rebuiltWalls)
|
|
523
|
+
} else {
|
|
524
|
+
const cleanIds = [...new Set((Array.isArray(wallIds) ? wallIds : []).map(x => String(x || '').trim()).filter(Boolean))]
|
|
525
|
+
if (cleanIds.length < 2) {
|
|
526
|
+
return { ok: false, code: 'MERGE_MIN_TWO', error: '请至少勾选 2 条相同类型的物理驻墙后再合并' }
|
|
527
|
+
}
|
|
528
|
+
const idSet = new Set(cleanIds)
|
|
529
|
+
const picked = walls.filter(w => idSet.has(w.id))
|
|
530
|
+
if (picked.length !== cleanIds.length) {
|
|
531
|
+
return { ok: false, error: '部分所选物理驻墙不存在或已被移除,请刷新后重试' }
|
|
532
|
+
}
|
|
533
|
+
const distinctTypes = [...new Set(picked.map(w => w.ruleType))]
|
|
534
|
+
if (distinctTypes.length > 1) {
|
|
535
|
+
const distinctLabels = distinctTypes.map(t => GUARD_WALL_TYPE_LABELS[t] || t).join('、')
|
|
536
|
+
return {
|
|
537
|
+
ok: false,
|
|
538
|
+
code: 'CROSS_TYPE_MERGE_FORBIDDEN',
|
|
539
|
+
error: `⛔ 禁止跨类型合并物理驻墙:您同时勾选了「${distinctLabels}」,仅允许相同拦截类型的物理驻墙合并!`,
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const built = mergeSameTypeWallGroup(picked, title, cwd, now)
|
|
543
|
+
if (!built.ok) return built
|
|
544
|
+
const firstIdx = walls.findIndex(w => w.id === picked[0].id)
|
|
545
|
+
const rebuiltWalls = []
|
|
546
|
+
for (let i = 0; i < walls.length; i += 1) {
|
|
547
|
+
if (i === firstIdx) {
|
|
548
|
+
rebuiltWalls.push(built.wall)
|
|
549
|
+
continue
|
|
550
|
+
}
|
|
551
|
+
if (idSet.has(walls[i].id)) continue
|
|
552
|
+
rebuiltWalls.push(walls[i])
|
|
553
|
+
}
|
|
554
|
+
walls.length = 0
|
|
555
|
+
walls.push(...rebuiltWalls)
|
|
556
|
+
targetWall = built.wall
|
|
557
|
+
mergedCount = picked.length
|
|
558
|
+
createdCount = 1
|
|
559
|
+
}
|
|
560
|
+
} else {
|
|
561
|
+
return { ok: false, error: `不支持的物理墙操作:${op}` }
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
const nextPayload = { version: 1, walls }
|
|
565
|
+
atomicWriteGuardWalls(file, nextPayload)
|
|
566
|
+
return {
|
|
567
|
+
ok: true,
|
|
568
|
+
op,
|
|
569
|
+
mergedCount,
|
|
570
|
+
createdCount,
|
|
571
|
+
wall: targetWall ? { ...targetWall, activeNow: isGuardWallActiveForCwd(targetWall, cwd) } : null,
|
|
572
|
+
walls: walls.map(w => ({ ...w, activeNow: isGuardWallActiveForCwd(w, cwd) })),
|
|
573
|
+
}
|
|
574
|
+
} finally {
|
|
575
|
+
release()
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function extractPathFromArgs(args = {}) {
|
|
580
|
+
if (!args || typeof args !== 'object') return ''
|
|
581
|
+
const raw = args.path
|
|
582
|
+
|| args.file_path
|
|
583
|
+
|| args.filePath
|
|
584
|
+
|| args.target_file
|
|
585
|
+
|| args.targetFile
|
|
586
|
+
|| args.destination
|
|
587
|
+
|| args.TargetFile
|
|
588
|
+
|| args.AbsolutePath
|
|
589
|
+
|| args.SearchPath
|
|
590
|
+
|| ''
|
|
591
|
+
return typeof raw === 'string' ? raw.trim() : ''
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function extractPatchPaths(patchText) {
|
|
595
|
+
const text = String(patchText || '')
|
|
596
|
+
if (!text) return []
|
|
597
|
+
const out = []
|
|
598
|
+
const seen = new Set()
|
|
599
|
+
const re = /^\*\*\*\s+(?:Add|Update|Delete)\s+File:\s*(.+)$|^\*\*\*\s+Move\s+to:\s*(.+)$/gm
|
|
600
|
+
let m
|
|
601
|
+
while ((m = re.exec(text)) !== null) {
|
|
602
|
+
const p = String(m[1] || m[2] || '').trim()
|
|
603
|
+
if (p && !seen.has(p)) {
|
|
604
|
+
seen.add(p)
|
|
605
|
+
out.push(p)
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
return out
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function extractAllPathsFromArgs(toolLower, args = {}) {
|
|
612
|
+
const out = []
|
|
613
|
+
const seen = new Set()
|
|
614
|
+
const pushPath = (p) => {
|
|
615
|
+
const clean = String(p || '').trim()
|
|
616
|
+
if (clean && !seen.has(clean)) {
|
|
617
|
+
seen.add(clean)
|
|
618
|
+
out.push(clean)
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
pushPath(extractPathFromArgs(args))
|
|
622
|
+
const patchBody = args && typeof args === 'object' ? (args.input || args.patch || '') : ''
|
|
623
|
+
if (
|
|
624
|
+
toolLower === 'apply_patch'
|
|
625
|
+
|| (typeof patchBody === 'string' && /^\*\*\*\s+(?:Begin\s+Patch|(?:Add|Update|Delete)\s+File:)/m.test(patchBody))
|
|
626
|
+
) {
|
|
627
|
+
for (const p of extractPatchPaths(patchBody)) pushPath(p)
|
|
628
|
+
}
|
|
629
|
+
return out
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function extractCmdFromArgs(args = {}, toolLower = '') {
|
|
633
|
+
if (!args || typeof args !== 'object') return ''
|
|
634
|
+
// `str_replace_editor` uses `args.command` as editor subcommand (`view`/`create`/`str_replace`/`insert`), NOT a shell command.
|
|
635
|
+
if (toolLower === 'str_replace_editor') return ''
|
|
636
|
+
const raw = args.command || args.cmd || args.CommandLine || args.script || ''
|
|
637
|
+
return typeof raw === 'string' ? raw.trim() : ''
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function matchPathAgainstPattern(resolvedAbsPath, cwd, pattern) {
|
|
641
|
+
const patRaw = String(pattern || '').trim()
|
|
642
|
+
if (!patRaw || !resolvedAbsPath) return false
|
|
643
|
+
const cmpTarget = normalizeCmpPath(resolvedAbsPath)
|
|
644
|
+
if (!cmpTarget) return false
|
|
645
|
+
|
|
646
|
+
// Direct absolute path or workspace-relative path match
|
|
647
|
+
const baseForRel = cwd || process.cwd()
|
|
648
|
+
const patAbs = path.isAbsolute(patRaw) ? patRaw : path.resolve(baseForRel, patRaw)
|
|
649
|
+
const cmpPat = normalizeCmpPath(patAbs)
|
|
650
|
+
if (cmpPat && isSubOrEqualPath(cmpPat, cmpTarget)) return true
|
|
651
|
+
|
|
652
|
+
// Segment / relative path token match (for cross-project guards such as `DSHGuard` or `.github/workflows`)
|
|
653
|
+
const normPatToken = patRaw.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '').toLowerCase()
|
|
654
|
+
if (!normPatToken) return false
|
|
655
|
+
if (normPatToken.includes('/')) {
|
|
656
|
+
return cmpTarget === normPatToken || cmpTarget.endsWith('/' + normPatToken) || cmpTarget.includes('/' + normPatToken + '/')
|
|
657
|
+
}
|
|
658
|
+
const segs = cmpTarget.split('/').filter(Boolean)
|
|
659
|
+
return segs.includes(normPatToken)
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function matchCommandAgainstPathPattern(command, pattern) {
|
|
663
|
+
const patRaw = String(pattern || '').trim()
|
|
664
|
+
const cmdRaw = String(command || '').trim()
|
|
665
|
+
if (!patRaw || !cmdRaw) return false
|
|
666
|
+
const normPat = patRaw.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '').toLowerCase()
|
|
667
|
+
if (!normPat || normPat.length < 2) return false
|
|
668
|
+
const analysis = analyzeCommand(cmdRaw)
|
|
669
|
+
const probes = [
|
|
670
|
+
cmdRaw,
|
|
671
|
+
analysis.normalized,
|
|
672
|
+
...analysis.segments,
|
|
673
|
+
...analysis.inlinePayloads,
|
|
674
|
+
]
|
|
675
|
+
.filter(Boolean)
|
|
676
|
+
.map(p => p.replace(/\\/g, '/').toLowerCase())
|
|
677
|
+
|
|
678
|
+
for (const probe of probes) {
|
|
679
|
+
if (probe.includes(normPat)) return true
|
|
680
|
+
}
|
|
681
|
+
return false
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
export function evaluateGuardWalls({
|
|
685
|
+
tool = '',
|
|
686
|
+
opClass = 'read',
|
|
687
|
+
targetPath = '',
|
|
688
|
+
command = '',
|
|
689
|
+
args = null,
|
|
690
|
+
cwd = '',
|
|
691
|
+
walls = null,
|
|
692
|
+
} = {}) {
|
|
693
|
+
const argObj = args && typeof args === 'object' ? args : {}
|
|
694
|
+
const resolvedTool = String(tool || '').trim()
|
|
695
|
+
const toolLower = resolvedTool.toLowerCase()
|
|
696
|
+
const allRawPaths = extractAllPathsFromArgs(toolLower, argObj)
|
|
697
|
+
const explicitRaw = String(targetPath || '').trim()
|
|
698
|
+
if (explicitRaw && !allRawPaths.includes(explicitRaw)) allRawPaths.unshift(explicitRaw)
|
|
699
|
+
const rawPath = allRawPaths[0] || ''
|
|
700
|
+
const rawCmd = String(command || extractCmdFromArgs(argObj, toolLower) || '').trim()
|
|
701
|
+
const rawExecCwd = toolLower === 'run_command' || SHELL_TOOLS.has(toolLower)
|
|
702
|
+
? String(argObj.cwd || argObj.Cwd || '').trim()
|
|
703
|
+
: ''
|
|
704
|
+
const activeWalls = (Array.isArray(walls) ? walls : listGuardWalls({ cwd }))
|
|
705
|
+
.filter(w => w && w.scope !== 'paused' && (Array.isArray(walls) ? isGuardWallActiveForCwd(w, cwd) : w.activeNow !== false))
|
|
706
|
+
|
|
707
|
+
if (!activeWalls.length) return { decision: 'allow' }
|
|
708
|
+
|
|
709
|
+
const absTargetPaths = allRawPaths.map(p => path.resolve(cwd || process.cwd(), p))
|
|
710
|
+
const absExecCwd = rawExecCwd ? path.resolve(cwd || process.cwd(), rawExecCwd) : ''
|
|
711
|
+
|
|
712
|
+
for (const w of activeWalls) {
|
|
713
|
+
if (w.ruleType === 'deny_tool') {
|
|
714
|
+
if (w.patterns.some(p => p.toLowerCase() === toolLower)) {
|
|
715
|
+
return {
|
|
716
|
+
decision: 'block',
|
|
717
|
+
wallId: w.id,
|
|
718
|
+
wallTitle: w.title,
|
|
719
|
+
rule: 'guard_wall_deny_tool',
|
|
720
|
+
reason: `动态物理墙「${w.title}」禁止调用工具 \`${resolvedTool}\``,
|
|
721
|
+
badge: '🧱 物理墙禁调工具',
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
continue
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
if (w.ruleType === 'forbid_path') {
|
|
728
|
+
if (w.writeOnly && opClass === 'read' && !rawCmd) continue
|
|
729
|
+
const hitTargetPath = absTargetPaths.some(absP => w.patterns.some(p => matchPathAgainstPattern(absP, cwd, p)))
|
|
730
|
+
const hitExecCwd = absExecCwd && w.patterns.some(p => matchPathAgainstPattern(absExecCwd, cwd, p))
|
|
731
|
+
const hitCmdPath = rawCmd && w.patterns.some(p => matchCommandAgainstPathPattern(rawCmd, p))
|
|
732
|
+
if (hitTargetPath || hitExecCwd || hitCmdPath) {
|
|
733
|
+
return {
|
|
734
|
+
decision: 'block',
|
|
735
|
+
wallId: w.id,
|
|
736
|
+
wallTitle: w.title,
|
|
737
|
+
rule: 'guard_wall_forbid_path',
|
|
738
|
+
reason: `动态物理墙「${w.title}」已锁死禁止触碰该路径/目标(${w.patterns.join(', ')})`,
|
|
739
|
+
badge: '🧱 物理墙锁路径',
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
continue
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
if (w.ruleType === 'restrict_write' && opClass !== 'read' && absTargetPaths.length > 0) {
|
|
746
|
+
const violatedIdx = absTargetPaths.findIndex(absP => !w.patterns.some(p => matchPathAgainstPattern(absP, cwd, p)))
|
|
747
|
+
if (violatedIdx >= 0) {
|
|
748
|
+
return {
|
|
749
|
+
decision: 'block',
|
|
750
|
+
wallId: w.id,
|
|
751
|
+
wallTitle: w.title,
|
|
752
|
+
rule: 'guard_wall_restrict_write',
|
|
753
|
+
reason: `动态物理墙「${w.title}」将写入范围严格限定于 [${w.patterns.join(', ')}],禁止写入 ${allRawPaths[violatedIdx] || rawPath}`,
|
|
754
|
+
badge: '🧱 物理墙收窄写区',
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
continue
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
if ((w.ruleType === 'forbid_cmd' || w.ruleType === 'require_approval_cmd') && rawCmd) {
|
|
761
|
+
const analysis = analyzeCommand(rawCmd)
|
|
762
|
+
const probes = [
|
|
763
|
+
rawCmd,
|
|
764
|
+
analysis.normalized,
|
|
765
|
+
...analysis.segments,
|
|
766
|
+
...analysis.inlinePayloads,
|
|
767
|
+
].filter(Boolean)
|
|
768
|
+
|
|
769
|
+
for (const pat of w.patterns) {
|
|
770
|
+
let re = null
|
|
771
|
+
try { re = new RegExp(pat, 'i') } catch { re = null }
|
|
772
|
+
if (!re) continue
|
|
773
|
+
if (probes.some(probe => re.test(probe) || re.test(normalizeCommandForSecurity(probe)))) {
|
|
774
|
+
if (w.ruleType === 'forbid_cmd') {
|
|
775
|
+
return {
|
|
776
|
+
decision: 'block',
|
|
777
|
+
wallId: w.id,
|
|
778
|
+
wallTitle: w.title,
|
|
779
|
+
rule: 'guard_wall_forbid_cmd',
|
|
780
|
+
reason: `动态物理墙「${w.title}」事前拦截高危/受禁命令规则 (${pat})`,
|
|
781
|
+
badge: '🧱 物理墙拦命令',
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return {
|
|
785
|
+
decision: 'require_approval',
|
|
786
|
+
wallId: w.id,
|
|
787
|
+
wallTitle: w.title,
|
|
788
|
+
rule: 'guard_wall_require_approval_cmd',
|
|
789
|
+
reason: `动态物理墙「${w.title}」要求执行该命令前先获人工确认 (${pat})`,
|
|
790
|
+
badge: '🧱 物理墙待确认',
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
return { decision: 'allow' }
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* Unified pre-execution physical defense gate for ALL agents (`@lead`, subagents,
|
|
802
|
+
* and Chief tools), triggered directly on host `tools/pre-execute`.
|
|
803
|
+
*/
|
|
804
|
+
export function evaluatePreExecuteDefense({
|
|
805
|
+
tool = '',
|
|
806
|
+
args = null,
|
|
807
|
+
cwd = '',
|
|
808
|
+
board = null,
|
|
809
|
+
walls = null,
|
|
810
|
+
} = {}) {
|
|
811
|
+
const toolName = String(tool || '').trim()
|
|
812
|
+
const lower = toolName.toLowerCase()
|
|
813
|
+
if (!toolName || SAFE_META_TOOLS.has(lower)) {
|
|
814
|
+
return { decision: 'allow' }
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
const argObj = args && typeof args === 'object' ? args : {}
|
|
818
|
+
const allPaths = extractAllPathsFromArgs(lower, argObj)
|
|
819
|
+
const resolvedPath = allPaths[0] || ''
|
|
820
|
+
const resolvedCmd = extractCmdFromArgs(argObj, lower)
|
|
821
|
+
|
|
822
|
+
const isStrReplaceRead = lower === 'str_replace_editor' && String(argObj.command || '').trim().toLowerCase() === 'view'
|
|
823
|
+
const isShell = SHELL_TOOLS.has(lower) || (Boolean(resolvedCmd) && !READ_ONLY_FS_TOOLS.has(lower) && !isStrReplaceRead)
|
|
824
|
+
const isWrite = !isStrReplaceRead && (
|
|
825
|
+
WORKSPACE_WRITE_TOOLS.has(lower)
|
|
826
|
+
|| (lower === 'str_replace_editor' && Boolean(argObj.command))
|
|
827
|
+
|| /(?:write|edit|patch|delete|remove|unlink|mkdir|rmdir|move|rename)/i.test(lower)
|
|
828
|
+
)
|
|
829
|
+
const opClass = (isShell || isWrite) ? 'workspace' : 'read'
|
|
830
|
+
|
|
831
|
+
// 1) Dynamic Guard Walls check first (covers read/read_file/list_dir on forbidden global walls + writes/shell)
|
|
832
|
+
const wallVerdict = evaluateGuardWalls({
|
|
833
|
+
tool: toolName,
|
|
834
|
+
opClass,
|
|
835
|
+
targetPath: resolvedPath,
|
|
836
|
+
command: resolvedCmd,
|
|
837
|
+
args: argObj,
|
|
838
|
+
cwd,
|
|
839
|
+
walls,
|
|
840
|
+
})
|
|
841
|
+
if (wallVerdict.decision === 'block') {
|
|
842
|
+
return {
|
|
843
|
+
decision: 'deny',
|
|
844
|
+
stage: 'guard_wall',
|
|
845
|
+
rule: wallVerdict.rule,
|
|
846
|
+
wallId: wallVerdict.wallId,
|
|
847
|
+
wallTitle: wallVerdict.wallTitle,
|
|
848
|
+
reason: wallVerdict.reason,
|
|
849
|
+
badge: wallVerdict.badge,
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
if (wallVerdict.decision === 'require_approval') {
|
|
853
|
+
return {
|
|
854
|
+
decision: 'ask',
|
|
855
|
+
stage: 'guard_wall',
|
|
856
|
+
rule: wallVerdict.rule,
|
|
857
|
+
wallId: wallVerdict.wallId,
|
|
858
|
+
wallTitle: wallVerdict.wallTitle,
|
|
859
|
+
reason: `${wallVerdict.reason}(受动态物理墙保护,需要人工单次批准后方可执行)`,
|
|
860
|
+
displayReason: `🧱 物理驻墙「${wallVerdict.wallTitle}」:${wallVerdict.reason}`,
|
|
861
|
+
badge: wallVerdict.badge,
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
const extraText = [
|
|
866
|
+
argObj.content,
|
|
867
|
+
argObj.new_string,
|
|
868
|
+
argObj.new_str,
|
|
869
|
+
argObj.insert_text,
|
|
870
|
+
argObj.file_text,
|
|
871
|
+
argObj.input,
|
|
872
|
+
argObj.target,
|
|
873
|
+
argObj.replacement,
|
|
874
|
+
argObj.TargetContent,
|
|
875
|
+
argObj.ReplacementContent,
|
|
876
|
+
argObj.CodeContent,
|
|
877
|
+
argObj.text,
|
|
878
|
+
]
|
|
879
|
+
.filter(v => v !== undefined && v !== null && String(v).trim())
|
|
880
|
+
.map(v => String(v).slice(0, 8192))
|
|
881
|
+
.join('\n')
|
|
882
|
+
.slice(0, 12_288)
|
|
883
|
+
|
|
884
|
+
// 2) Built-in non-overridable pre-execute invariant checks for commands
|
|
885
|
+
if (resolvedCmd) {
|
|
886
|
+
const credTouch = commandTouchesSensitiveCredential(resolvedCmd)
|
|
887
|
+
if (credTouch.touched) {
|
|
888
|
+
return {
|
|
889
|
+
decision: 'deny',
|
|
890
|
+
stage: 'safety_guard',
|
|
891
|
+
rule: credTouch.viaInline ? 'inline_script_credential' : 'sensitive_credential_cmd',
|
|
892
|
+
reason: credTouch.viaInline
|
|
893
|
+
? '安全卫兵事前拦截内联脚本(node -e / python -c / pwsh)触及敏感凭据路径'
|
|
894
|
+
: '安全卫兵事前拦截触及敏感凭据路径的终端命令',
|
|
895
|
+
badge: '🛡️ 事前拦凭据命令',
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
if (isDestructiveShellCommand(resolvedCmd)) {
|
|
899
|
+
return {
|
|
900
|
+
decision: 'deny',
|
|
901
|
+
stage: 'safety_guard',
|
|
902
|
+
rule: 'destructive_command',
|
|
903
|
+
reason: `安全卫兵事前拦截高危破坏性系统命令:${clampStr(resolvedCmd, 80)}`,
|
|
904
|
+
badge: '🛡️ 事前拦高危命令',
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
if (isShell && cwd) {
|
|
908
|
+
const rawRunCwd = String(argObj.cwd || argObj.Cwd || '').trim()
|
|
909
|
+
if (rawRunCwd) {
|
|
910
|
+
const cwdCheck = validateWorkspacePath(cwd, path.resolve(cwd, rawRunCwd), { mode: 'write' })
|
|
911
|
+
if (cwdCheck.blocked) {
|
|
912
|
+
return {
|
|
913
|
+
decision: 'deny',
|
|
914
|
+
stage: 'safety_guard',
|
|
915
|
+
rule: cwdCheck.rule || 'workspace_escape',
|
|
916
|
+
reason: `安全卫兵事前拦截越界执行目录 (${rawRunCwd})`,
|
|
917
|
+
badge: '🛡️ 事前拦越界目录',
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
const boundCmdCheck = checkForbiddenBounds(board, toolName, resolvedCmd, extraText)
|
|
923
|
+
if (boundCmdCheck.blocked) {
|
|
924
|
+
return {
|
|
925
|
+
decision: 'deny',
|
|
926
|
+
stage: 'safety_guard',
|
|
927
|
+
rule: 'forbidden_bound',
|
|
928
|
+
matchedRule: boundCmdCheck.matchedRule,
|
|
929
|
+
reason: `安全卫兵命中禁止红线【${boundCmdCheck.matchedRule}】,事前拒止执行`,
|
|
930
|
+
badge: '🛡️ 事前拦红线',
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// 3) Built-in invariant checks for file paths (all paths including apply_patch targets)
|
|
936
|
+
for (const pathItem of allPaths) {
|
|
937
|
+
if (hasWindowsReservedDeviceName(pathItem)) {
|
|
938
|
+
return {
|
|
939
|
+
decision: 'deny',
|
|
940
|
+
stage: 'safety_guard',
|
|
941
|
+
rule: 'windows_reserved_device',
|
|
942
|
+
reason: `安全卫兵事前拦截 Windows 保留设备名路径:${pathItem}`,
|
|
943
|
+
badge: '🛡️ 事前拦设备名',
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
if (hasForbiddenNtfsAds(pathItem)) {
|
|
947
|
+
return {
|
|
948
|
+
decision: 'deny',
|
|
949
|
+
stage: 'safety_guard',
|
|
950
|
+
rule: 'ntfs_ads_stream',
|
|
951
|
+
reason: `安全卫兵事前拦截 NTFS 备用数据流 (ADS):${pathItem}`,
|
|
952
|
+
badge: '🛡️ 事前拦 ADS',
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
if (isSensitiveCredentialPath(pathItem)) {
|
|
956
|
+
return {
|
|
957
|
+
decision: 'deny',
|
|
958
|
+
stage: 'safety_guard',
|
|
959
|
+
rule: 'sensitive_credential',
|
|
960
|
+
reason: `安全卫兵事前拦截敏感凭据文件触及(${path.basename(pathItem)})`,
|
|
961
|
+
badge: '🛡️ 事前拦凭据',
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
if (opClass !== 'read') {
|
|
965
|
+
const absTarget = path.resolve(cwd || process.cwd(), pathItem)
|
|
966
|
+
const writeCheck = validateWorkspacePath(cwd, absTarget, { mode: 'write' })
|
|
967
|
+
if (writeCheck.blocked) {
|
|
968
|
+
return {
|
|
969
|
+
decision: 'deny',
|
|
970
|
+
stage: 'safety_guard',
|
|
971
|
+
rule: writeCheck.rule || 'workspace_escape',
|
|
972
|
+
reason: writeCheck.reason,
|
|
973
|
+
badge: writeCheck.badge || '🛡️ 事前拦越界写',
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
const boundPathCheck = checkForbiddenBounds(board, toolName, absTarget, extraText)
|
|
977
|
+
if (boundPathCheck.blocked) {
|
|
978
|
+
return {
|
|
979
|
+
decision: 'deny',
|
|
980
|
+
stage: 'safety_guard',
|
|
981
|
+
rule: 'forbidden_bound',
|
|
982
|
+
matchedRule: boundPathCheck.matchedRule,
|
|
983
|
+
reason: `安全卫兵命中禁止红线【${boundPathCheck.matchedRule}】,事前拒止改动 ${path.basename(pathItem)}`,
|
|
984
|
+
badge: '🛡️ 事前拦红线',
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
return { decision: 'allow' }
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
export { HUMAN_BOUNDS_CONFIRM_TOKEN }
|