dsh-ruleset 0.0.0-stage → 0.2.2

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/DEVELOPMENT.md +121 -0
  3. package/LICENSE +21 -0
  4. package/README.md +64 -2
  5. package/README.zh.md +131 -0
  6. package/client.js +822 -0
  7. package/cordis.patch.yml +10 -0
  8. package/docs/PREDICATE-PLAYBOOK.md +42 -0
  9. package/docs-schema.md +38 -0
  10. package/examples/policy.example.yaml +50 -0
  11. package/examples/policy.full.yaml +162 -0
  12. package/examples/policy.starter.yaml +65 -0
  13. package/lib/backups.js +77 -0
  14. package/lib/commands.js +38 -0
  15. package/lib/dedupe.js +22 -0
  16. package/lib/explain.js +28 -0
  17. package/lib/export.js +33 -0
  18. package/lib/extract.js +104 -0
  19. package/lib/facts.js +250 -0
  20. package/lib/findings.js +101 -0
  21. package/lib/guard.js +76 -0
  22. package/lib/history.js +71 -0
  23. package/lib/hygiene.js +86 -0
  24. package/lib/index.js +70 -0
  25. package/lib/init.js +29 -0
  26. package/lib/inject.js +64 -0
  27. package/lib/injected-log.js +30 -0
  28. package/lib/introspect.js +55 -0
  29. package/lib/judge.js +73 -0
  30. package/lib/llm-parse.js +131 -0
  31. package/lib/observe.js +132 -0
  32. package/lib/policy.js +57 -0
  33. package/lib/predicates.js +444 -0
  34. package/lib/report.js +66 -0
  35. package/lib/routes.js +62 -0
  36. package/lib/rules-edit.js +140 -0
  37. package/lib/run.js +109 -0
  38. package/lib/service.js +91 -0
  39. package/lib/source.js +93 -0
  40. package/lib/stats.js +63 -0
  41. package/lib/validate.js +73 -0
  42. package/locale/en.json +1 -0
  43. package/locale/zh.json +1 -0
  44. package/package.json +68 -3
  45. package/schema/policy.schema.json +41 -0
  46. package/test/dedupe.test.mjs +19 -0
  47. package/test/guard.test.mjs +30 -0
  48. package/test/load.test.mjs +21 -0
  49. package/test/predicates.test.mjs +49 -0
  50. package/test/source.test.mjs +32 -0
  51. package/test/validate.test.mjs +33 -0
@@ -0,0 +1,444 @@
1
+ /**
2
+ * 六类谓词执行器:规则在 policy 里声明用哪个谓词,这里统一执行。
3
+ * 判据不写在代码里;新增规则 = 改 policy。
4
+ */
5
+ import { isInside } from './facts.js'
6
+
7
+ const norm = (s) => String(s || '').trim().replace(/\s+/g, ' ')
8
+
9
+ /** 取用户原话里最像需求的一行(去掉 system-reminder / Time sampled 之类噪声)。 */
10
+ const NOISE_SUB = [/Time sampled[^\n]*/gi, /Elapsed since[^\n]*/gi, /Browser time zone[^\n]*/gi, /Tokens prefixed[^\n]*/gi, /<system-reminder>[\s\S]*?<\/system-reminder>/gi, /Current DeepSeek Harness[^\n]*/gi]
11
+
12
+ /** 取用户原话里最像需求的一句(去掉系统注入文本)。 */
13
+ function userLine(t) {
14
+ let text = String(t.user || '')
15
+ for (const re of NOISE_SUB) text = text.replace(re, ' ')
16
+ const parts = text.split(/[\n。!?]/).map((x) => x.trim()).filter((x) => x.length >= 4)
17
+ const cjk = parts.filter((x) => /[\u4e00-\u9fa5]/.test(x))
18
+ const pick = (cjk.length ? cjk : parts).sort((a, b) => b.length - a.length)[0] || ''
19
+ return pick.replace(/\s+/g, ' ').slice(0, 70)
20
+ }
21
+
22
+ const when = (ms) => {
23
+ if (!ms) return ''
24
+ const d = new Date(ms)
25
+ const p = (n) => String(n).padStart(2, '0')
26
+ return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
27
+ }
28
+
29
+ // 平台临时区:沙箱允许写,删除脚手架不算破坏性资产操作(可用 strictTemp 关掉)
30
+ const TEMP_PREFIXES = ['/tmp/', '/private/tmp/', '/var/folders/', '/private/var/folders/']
31
+ function isTempPath(p, bind) {
32
+ if (bind?.strictTemp) return false
33
+ const prefixes = Array.isArray(bind?.exemptPaths) && bind.exemptPaths.length ? bind.exemptPaths : TEMP_PREFIXES
34
+ return prefixes.some((pre) => String(p).startsWith(pre))
35
+ }
36
+
37
+ function insideCount(cmd) {
38
+ const inside = cmd.targets.some((t) => isInside(cmd.cwd, t) === true)
39
+ const outside = cmd.targets.some((t) => isInside(cmd.cwd, t) === false)
40
+ return { inside, outside }
41
+ }
42
+
43
+ /** 统一结果:hits / base / rate,对齐上游「分母式」口径。 */
44
+ function result(hits, base, samples = []) {
45
+ const status = base === 0 ? 'unknown' : (hits > 0 ? 'violation' : 'pass')
46
+ const rate = base === 0 ? null : Math.round((hits / base) * 1000) / 1000
47
+ const detail = base === 0 ? '无样本' : `${hits}/${base}${rate === null ? '' : `(${Math.round(rate * 100)}%)`}`
48
+ return { status, hits, base, rate, detail, samples: samples.slice(0, 3) }
49
+ }
50
+
51
+ /** 判据说明:面板据此生成下拉与参数表单(一份真源,别在 UI 里另抄)。 */
52
+ export const PREDICATE_DOCS = {
53
+ 'explain-first': { say: '动手(调工具)之前没有先解释原因与计划', params: [] },
54
+ 'path-boundary': { say: '命令删除了工作区外的路径且没先确认', params: ['pattern', 'requireApproval', 'exemptPaths'] },
55
+ 'field-presence': { say: '文件里缺少指定字段', params: ['ext', 'fields', 'pathPattern', 'excludePath', 'legacyDays'] },
56
+ 'count-threshold': { say: '同一命令连续失败后仍在重试', params: ['consecutiveFailures', 'minSamples'] },
57
+ 'turn-condition': { say: '长任务里没有出现指定动作', params: ['ifTurnCallMin', 'ifTurnDurationSec', 'graceSec', 'thenPattern', 'thenFilePattern'] },
58
+ wal: { say: '收到指令后没有及时落盘', params: ['withinSec', 'thenFilePattern'] },
59
+ 'sequence-order': { say: '诊断/开发任务没先查外部就动手', params: ['taskPattern', 'first', 'then', 'minSamples'] },
60
+ 'requires': { say: '做了 X 就必须有 Y(如高风险交付要有独立复核)', params: ['ifPathPattern', 'ifContentPattern', 'minSamples'] },
61
+ 'duration': { say: '单次调用阻塞超过阈值且没后台化', params: ['minMinutes'] },
62
+ 'metric': { say: '指标超过阈值', params: ['key', 'op', 'threshold'] },
63
+ 'regex': { say: '命令或写入内容里出现指定模式', params: ['sources', 'pattern', 'target', 'requireWrite'] },
64
+ never: { say: '绝对禁止某类内容出现(命中即违规)', params: ['sources', 'pattern'] },
65
+ bypass: { say: '命令尝试绕过沙箱/权限边界', params: ['patterns'] },
66
+ 'approval-gated': { say: '敏感命令没有经过 DSH 审批就执行', params: ['patterns'] },
67
+ 'permission-change': { say: '权限档位变更时没有当轮解释', params: [] },
68
+ 'job-dangling': { say: '后台任务没有正常结算', params: ['minMinutes'] },
69
+ 'command-audit': { say: '斜杠命令没有走到完成', params: [] },
70
+ 'change-gate': { say: '变更记录缺少必需章节', params: ['pathPattern', 'sections', 'ext'] },
71
+ 'per-turn-cap': { say: '单轮最多调用某工具几次', params: ['toolPattern', 'maxPerTurn'] },
72
+ }
73
+
74
+ const compile = (pattern, flags = '') => {
75
+ const src = String(pattern || '').replace(/^\(\?s\)/, '').replace(/\(\?s\)/g, '')
76
+ const needDotAll = /^\(\?s\)/.test(String(pattern || '')) || String(pattern || '').includes('(?s)')
77
+ try { return new RegExp(src, needDotAll ? `${flags}s`.replace(/[^gimsuy]/g, '') : flags) } catch { return null }
78
+ }
79
+
80
+ export const PREDICATES = {
81
+ /** 绝对禁止:命中即违规,不因审批而豁免(OPA deny 语义)。 */
82
+ never: (facts, b) => {
83
+ const re = compile(b.pattern)
84
+ if (!re) return { status: 'unknown', hits: 0, base: 0, rate: null, detail: '正则无法编译', samples: [] }
85
+ const src = Array.isArray(b.sources) ? b.sources : ['commands']
86
+ const pool = []
87
+ if (src.includes('commands')) for (const c of facts.commands) pool.push({ id: c.seq, text: c.cmd, session: c.session, atMs: c.startedAt, at: when(c.startedAt) })
88
+ if (src.includes('fileWrites')) for (const w of facts.fileWrites) pool.push({ id: w.seq, text: w.content, session: w.session, path: w.path, atMs: w.mtimeMs, at: when(w.mtimeMs) })
89
+ const hits = pool.filter((x) => re.test(String(x.text || '')))
90
+ const r = result(hits.length, pool.length, hits.slice(0, 5))
91
+ r.detail = `扫描 ${pool.length} 条,命中绝对禁止模式 ${hits.length} 条`
92
+ return r
93
+ },
94
+
95
+ /** 单轮最多 N 次某类调用(OPA at-most 语义)。 */
96
+ 'per-turn-cap': (facts, b) => {
97
+ const re = compile(b.toolPattern || '.')
98
+ if (!re) return { status: 'unknown', hits: 0, base: 0, rate: null, detail: '正则无法编译', samples: [] }
99
+ const cap = Number(b.maxPerTurn || 3)
100
+ const turns = facts.turns.filter((t) => (t.calls || []).length)
101
+ const bad = turns.filter((t) => t.calls.filter((c) => re.test(c.name)).length > cap)
102
+ const r = result(bad.length, turns.length, bad.slice(0, 5))
103
+ r.detail = `${turns.length} 轮里,${bad.length} 轮单轮调用超过 ${cap} 次`
104
+ return r
105
+ },
106
+
107
+ 'explain-first': (facts, b) => {
108
+ const turns = facts.turns.filter((t) => (t.calls || []).length > 0)
109
+ const hits = turns.filter((t) => !t.saidBeforeCall)
110
+ const samples = hits.slice(0, 5).map((t) => ({ at: when(t.startTime), session: t.session, seq: t.seq, user: userLine(t), calls: (t.calls || []).length, atMs: t.startTime }))
111
+ const r = result(hits.length, turns.length, samples)
112
+ r.detail = `有工具调用的轮次里,${hits.length} 轮在第一次调用前没有解释文本`
113
+ return r
114
+ },
115
+ /** 绕过检测:只看命令段开头是否是提权/伪装执行,避免匹配脚本正文里的字面量。 */
116
+ bypass: (facts, b) => {
117
+ const res = (Array.isArray(b.patterns) && b.patterns.length ? b.patterns : [
118
+ '(?:^|[;&|]\\s*)(?:[A-Za-z_]+=\\S+\\s+)*sudo\\b',
119
+ '(?:^|[;&|]\\s*)(?:[A-Za-z_]+=\\S+\\s+)*chmod\\s+777\\b',
120
+ '(?:^|[;&|]\\s*)(?:[A-Za-z_]+=\\S+\\s+)*osascript\\b',
121
+ 'curl\\b[^;|]*\\|\\s*(?:ba)?sh\\b',
122
+ '(?:^|[;&|]\\s*)(?:>|tee\\s+)\\s*/(?:etc|usr|System|Library)/',
123
+ '\\blaunchctl\\s+(?:load|bootstrap)\\b[^;]*LaunchDaemons',
124
+ ]).map((x) => compile(x, 'm')).filter(Boolean)
125
+ const hits = facts.commands.filter((c) => res.some((re) => re.test(String(c.cmd || ''))))
126
+ const samples = hits.slice(0, 5).map((c) => ({ at: when(c.startedAt), atMs: c.startedAt, session: c.session, cmd: String(c.cmd).slice(0, 90) }))
127
+ const r = result(hits.length, facts.commands.length, samples)
128
+ r.detail = `${facts.commands.length} 条命令里,${hits.length} 条命中绕过模式(只看命令段开头)`
129
+ return r
130
+ },
131
+
132
+ /** 变更门:变更记录必须含指定章节(移植自 OpenClaw change-gate.py)。 */
133
+ 'change-gate': (facts, b) => {
134
+ const re = compile(b.pathPattern || '变更|change|change-log')
135
+ const sections = Array.isArray(b.sections) && b.sections.length ? b.sections : ['双评估', '落', '收尾']
136
+ const legacyMs = Number(b.legacyDays || 7) * 86400 * 1000
137
+ const files = facts.fileWrites.filter((w) => w.path.endsWith(b.ext || '.md') && (!re || re.test(w.path)) && !(w.mtimeMs && w.mtimeMs < Date.now() - legacyMs))
138
+ const seen = new Map()
139
+ for (const f of files) if (!seen.has(f.path)) seen.set(f.path, f)
140
+ const bad = []
141
+ for (const [p, f] of seen) {
142
+ const lacks = sections.filter((x) => !String(f.content || '').includes(x))
143
+ if (lacks.length) bad.push({ path: p, lacks, at: when(f.mtimeMs), atMs: f.mtimeMs })
144
+ }
145
+ const r = result(bad.length, seen.size, bad.slice(0, 5))
146
+ r.detail = seen.size === 0 ? '没有匹配的变更记录' : `${seen.size} 份变更记录里,${bad.length} 份缺章节`
147
+ return r
148
+ },
149
+
150
+ /** 权限档位变更必须当轮解释。 */
151
+ 'permission-change': (facts, b) => {
152
+ const list = facts.permissionChanges || []
153
+ const bad = list.filter((x) => !x.said)
154
+ const samples = bad.slice(0, 5).map((x) => ({ at: x.at, atMs: x.atMs, session: x.session, extra: `${x.from} → ${x.to}` }))
155
+ const r = result(bad.length, list.length, samples)
156
+ r.detail = `权限档位变更 ${list.length} 次,其中 ${bad.length} 次当轮没有解释`
157
+ return r
158
+ },
159
+
160
+ /** 后台任务必须有结算。 */
161
+ 'job-dangling': (facts, b) => {
162
+ const limit = Number(b.minMinutes || 30) * 60000
163
+ const list = facts.jobs || []
164
+ const bad = list.filter((j) => !j.settledAt || (j.settledAt && j.settledAt - j.atMs > limit * 10))
165
+ const samples = bad.slice(0, 5).map((j) => ({ at: j.at, atMs: j.atMs, session: j.session, extra: j.settledAt ? '结算过晚' : '未结算' }))
166
+ const r = result(bad.length, list.length, samples)
167
+ r.detail = `后台任务 ${list.length} 个,其中 ${bad.length} 个没有正常结算`
168
+ return r
169
+ },
170
+
171
+ /** 斜杠命令必须走到完成。 */
172
+ 'command-audit': (facts, b) => {
173
+ const list = facts.commandsRun || []
174
+ const bad = list.filter((x) => !x.done)
175
+ const samples = bad.slice(0, 5).map((x) => ({ at: x.at, atMs: x.atMs, session: x.session, extra: `/ ${x.name}` }))
176
+ const r = result(bad.length, list.length, samples)
177
+ r.detail = `斜杠命令 ${list.length} 次,其中 ${bad.length} 次没有完成记录`
178
+ return r
179
+ },
180
+
181
+ /** 审批门:敏感命令必须留下 DSH 的审批痕迹(approval/asked|decided),否则视为绕过。 */
182
+ 'approval-gated': (facts, b) => {
183
+ const res = (Array.isArray(b.patterns) && b.patterns.length ? b.patterns : [
184
+ '(?:^|[;&|]\\s*)(?:[A-Za-z_]+=\\S+\\s+)*sudo\\b',
185
+ '(?:^|[;&|]\\s*)(?:[A-Za-z_]+=\\S+\\s+)*chmod\\s+777\\b',
186
+ '(?:>|tee\\s+)\\s*/(?:etc|usr|System|Library)/',
187
+ ]).map((x) => compile(x, 'm')).filter(Boolean)
188
+ const inString = (cmd, idx) => {
189
+ let q = 0
190
+ for (let i = 0; i < idx; i += 1) {
191
+ const ch = cmd[i]
192
+ if (ch === '\\' && cmd[i + 1] === '"') { i += 1; continue }
193
+ if (ch === '"' || ch === "'") q += 1
194
+ }
195
+ return q % 2 === 1
196
+ }
197
+ const matched = (cmd) => res.some((re) => {
198
+ const m = re.exec(cmd)
199
+ return Boolean(m) && !inString(cmd, m.index)
200
+ })
201
+ const pool = facts.commands.filter((c) => matched(String(c.cmd || '')))
202
+ const bad = pool.filter((c) => c.approval !== 'asked' && c.approval !== 'allowed')
203
+ const samples = bad.slice(0, 5).map((c) => ({ at: when(c.startedAt), atMs: c.startedAt, session: c.session, cmd: String(c.cmd).slice(0, 80), extra: c.approval ? `审批=${c.approval}` : '无审批记录' }))
204
+ const r = result(bad.length, pool.length, samples)
205
+ r.detail = `敏感命令 ${pool.length} 条,其中 ${bad.length} 条没有 DSH 审批记录`
206
+ return r
207
+ },
208
+
209
+ /** 正则命中 + 可选边界/审批要求 */
210
+ regex(facts, b) {
211
+ const sources = Array.isArray(b.sources) ? b.sources : [b.source || 'commands']
212
+ if (sources.length > 1) {
213
+ const results = sources.map((src) => PREDICATES.regex(facts, { ...b, sources: [src], source: src, target: src === 'fileWrites' ? 'content' : undefined }))
214
+ const violation = results.find((r) => r.status === 'violation')
215
+ if (violation) return violation
216
+ if (results.every((r) => r.status === 'pass')) return { status: 'pass', detail: results.map((r) => r.detail).join(';'), samples: [] }
217
+ return { status: 'unknown', detail: results.map((r) => r.detail).join(';'), samples: [] }
218
+ }
219
+ const source = b.source === 'fileWrites' ? facts.fileWrites.filter((w) => !(b.excludeDelegated && w.delegated)) : facts.commands
220
+ const writeOnly = b.requireWrite ? source.filter((r) => /(^|\s)(?:>|>>|tee)\s/.test(String(r.cmd || ''))) : source
221
+ const re = compile(b.pattern) || new RegExp('(?!x)x')
222
+ const strip = (text) => {
223
+ if (!b.skeleton) return text
224
+ let out = []
225
+ let end = null
226
+ for (const line of String(text).split('\n')) {
227
+ if (end) { if (line.trim() === end) end = null; continue }
228
+ const m = /<<-?\s*['"]?([A-Za-z_]\w*)['"]?/.exec(line)
229
+ if (m) { end = m[1]; out.push(line.replace(/<<-?.*$/, '')); continue }
230
+ out.push(line)
231
+ }
232
+ return out.join('\n').replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, ' ')
233
+ }
234
+ const hits = writeOnly.filter((r) => {
235
+ const text = b.target === 'content' ? r.content : b.target === 'path' ? r.path : r.cmd
236
+ if (b.excludeLocalUrl && /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])/i.test(String(text)) && !/https?:\/\/(?!127\.0\.0\.1|localhost|\[::1\])/i.test(String(text))) return false
237
+ return re.test(strip(text))
238
+ })
239
+ if (hits.length === 0) return { status: 'pass', hits: 0, base: source.length, rate: 0, detail: `扫描 ${source.length} 条,0 命中`, samples: [] }
240
+ const samples = []
241
+ let exempted = 0
242
+ for (const h of hits) {
243
+ if (b.boundary === 'outside-cwd') {
244
+ const { inside, outside } = insideCount(h)
245
+ if (inside && !outside) continue // 工作区内删除/写入不要求审批
246
+ if (!outside) continue
247
+ const outsideTargets = (h.targets || []).filter((t) => isInside(h.cwd, t) === false)
248
+ if (outsideTargets.length > 0 && outsideTargets.every((t) => isTempPath(t, b))) { exempted += 1; continue }
249
+ }
250
+ if (b.requireUserPermit && h.user && new RegExp(b.requireUserPermit).test(h.user)) continue
251
+ if (b.requireApproval) {
252
+ if (h.approval && /^allowed/.test(h.approval)) continue
253
+ if (h.approval && /denied/.test(h.approval)) continue
254
+ if (h.isError) continue // 被沙箱拒/命令失败,未实际执行
255
+ }
256
+ samples.push({ ...h, atMs: h.startedAt, at: when(h.startedAt) })
257
+ }
258
+ const r = result(samples.length, hits.length, samples)
259
+ if (exempted > 0) r.detail += `;其中 ${exempted} 条在临时区已豁免`
260
+ return r
261
+ },
262
+
263
+ /** 目标是否越出会话工作区 */
264
+ 'path-boundary'(facts, b) {
265
+ return PREDICATES.regex(facts, { ...b, source: 'commands', boundary: 'outside-cwd' })
266
+ },
267
+
268
+ /** 文件必须有指定标签/字段 */
269
+ 'field-presence'(facts, b) {
270
+ let legacy = 0
271
+ const win = Number(facts.windowStart || 0)
272
+ const files = facts.fileWrites.filter((w) => {
273
+ const exts = Array.isArray(b.exts) ? b.exts : (b.ext ? [b.ext] : [])
274
+ if (exts.length && !exts.some((e) => w.path.endsWith(e))) return false
275
+ if (b.pathPattern && !compile(b.pathPattern)?.test(w.path)) return false
276
+ if (b.excludePath && compile(b.excludePath)?.test(w.path)) return false
277
+ if (win && w.mtimeMs && w.mtimeMs < win) { legacy += 1; return false }
278
+ return true
279
+ })
280
+ const seen = new Map()
281
+ for (const f of files) if (!seen.has(f.path)) seen.set(f.path, f)
282
+ if (seen.size === 0) return { status: 'unknown', hits: 0, base: 0, rate: null, detail: `窗口内无对象(窗口外 ${legacy} 个不计)`, samples: [] }
283
+ const missing = []
284
+ for (const [p, f] of seen) {
285
+ const lacks = (b.fields || []).filter((field) => !new RegExp(`(?:^|\\n)\\s*(?:[-*]\\s*)?(?:\\*\\*)?${field}(?:\\*\\*)?\\s*[::]`, 'm').test(f.content))
286
+ if (lacks.length) missing.push({ path: p, lacks, atMs: f.mtimeMs, at: when(f.mtimeMs) })
287
+ }
288
+ const r = result(missing.length, seen.size, missing)
289
+ if (legacy) r.detail += `(窗口外 ${legacy} 个不计)`
290
+ return r
291
+ },
292
+
293
+ /** A 类调用是否早于 B 类(如先检索再查本地) */
294
+ 'sequence-order'(facts, b) {
295
+ const tasks = facts.turns.filter((t) => !t.delegated && t.user && compile(b.taskPattern || '.') || new RegExp('(?!x)x').test(t.user.slice(0, 400)))
296
+ let total = 0
297
+ const bad = []
298
+ for (const t of tasks) {
299
+ const firstAt = Math.min(...t.calls.filter((c) => (b.then || []).includes(c.name)).map((c) => c.seq))
300
+ if (!Number.isFinite(firstAt)) continue
301
+ total += 1
302
+ const webAt = Math.min(...t.calls.filter((c) => (b.first || ['web_search', 'web_fetch']).includes(c.name)).map((c) => c.seq))
303
+ if (!(webAt < firstAt)) bad.push({ at: when(t.startTime), session: t.session, seq: t.seq, user: userLine(t), atMs: t.startTime })
304
+ }
305
+ if (total === 0) return { status: 'unknown', hits: 0, base: 0, rate: null, detail: '无样本', samples: [] }
306
+ if (total < Number(b.minSamples || 1)) return { status: 'unknown', hits: bad.length, base: total, rate: null, detail: `样本不足(${total}/${b.minSamples})`, samples: bad }
307
+ return result(bad.length, total, bad)
308
+ },
309
+
310
+ /** 同命令连续失败后重试 */
311
+ 'count-threshold'(facts, b) {
312
+ const limit = Number(b.consecutiveFailures || 2)
313
+ const streak = new Map()
314
+ let total = 0
315
+ const bad = []
316
+ for (const c of facts.commands) {
317
+ const key = norm(c.cmd)
318
+ total += 1
319
+ if (!c.isError) { streak.delete(key); continue }
320
+ const n = (streak.get(key) || 0) + 1
321
+ streak.set(key, n)
322
+ if (n > limit) bad.push({ seq: c.seq, session: c.session, cmd: key.slice(0, 80) })
323
+ }
324
+ if (total < Number(b.minSamples || 1)) return { status: 'unknown', hits: 0, base: total, rate: null, detail: `样本不足(${total})`, samples: [] }
325
+ return result(bad.length, total, bad)
326
+ },
327
+
328
+ /** 做了 X 就必须有 Y(如高风险交付要有独立复核) */
329
+ requires(facts, b) {
330
+ const files = facts.fileWrites.filter((w) => {
331
+ if (w.delegated) return false
332
+ const byPath = b.ifPathPattern ? new RegExp(b.ifPathPattern).test(w.path) : false
333
+ const byContent = b.ifContentPattern ? new RegExp(b.ifContentPattern).test(w.content) : false
334
+ if (b.ifPathPattern || b.ifContentPattern) return byPath || byContent
335
+ return new RegExp(b.ifPattern || '.').test(w.path) || new RegExp(b.ifPattern || '.').test(w.content)
336
+ })
337
+ if (files.length === 0) return { status: 'unknown', hits: 0, base: 0, rate: null, detail: '无样本', samples: [] }
338
+ const bad = []
339
+ for (const f of files) {
340
+ const key = `${f.session}#${f.turn}`
341
+ if (!facts.subagentTurns.has(key)) bad.push({ path: f.path, session: f.session })
342
+ }
343
+ return result(bad.length, files.length, bad)
344
+ },
345
+ }
346
+
347
+ /**
348
+ * 长任务轮次必须出现某类收尾动作(turn-condition)。
349
+ * 注意:这里只认可观测动作(归档/查上下文/lint),第四步「跑收尾命令」口径模糊不计。
350
+ */
351
+ PREDICATES['turn-condition'] = function (facts, b) {
352
+ const minCalls = Number(b.ifTurnCallMin || 0)
353
+ const minSec = Number(b.ifTurnDurationSec || 0)
354
+ const grace = Number(b.graceSec || 0)
355
+ const matches = (t) => {
356
+ const re = b.thenPattern ? new RegExp(b.thenPattern) : null
357
+ const fre = b.thenFilePattern ? new RegExp(b.thenFilePattern) : null
358
+ if (re && (t.calls || []).some((c) => re.test(`${c.name} ${String(c.args?.command || '')} ${String(c.args?.file_path || '')}`))) return true
359
+ if (fre && (t.writes || []).some((w) => fre.test(w.path))) return true
360
+ return false
361
+ }
362
+ const long = facts.turns.filter((t) => {
363
+ if (t.delegated) return false
364
+ const calls = (t.calls || []).length
365
+ const sec = t.startTime && t.endTime ? (t.endTime - t.startTime) / 1000 : 0
366
+ return (minCalls && calls >= minCalls) || (minSec && sec >= minSec)
367
+ })
368
+ if (long.length === 0) return { status: 'unknown', hits: 0, base: 0, rate: null, detail: '无长任务样本', samples: [] }
369
+ const graceOk = (t) => {
370
+ if (!grace) return false
371
+ const from = (t.startTime || 0) - grace * 1000
372
+ return facts.turns.some((o) => o !== t && matches(o) && (o.startTime || 0) >= from && (o.startTime || 0) <= (t.startTime || 0))
373
+ }
374
+ const bad = long.filter((t) => !matches(t) && !graceOk(t))
375
+ const samples = bad.slice(0, 5).map((t) => ({ at: when(t.startTime), session: t.session, seq: t.seq, user: userLine(t), calls: (t.calls || []).length, atMs: t.startTime }))
376
+ const r = result(bad.length, long.length, samples)
377
+ r.detail = `长任务 ${long.length} 轮,${bad.length} 轮缺少收尾动作`
378
+ if (grace) r.detail += `(前 ${grace}s 内已收尾视为覆盖)`
379
+ return r
380
+ }
381
+
382
+ /** WAL:收到用户指令后,必须在窗口内落盘(OpenClaw m5 迁移版)。 */
383
+ PREDICATES.wal = function (facts, b) {
384
+ const within = Number(b.withinSec || 600) * 1000
385
+ const fre = new RegExp(b.thenFilePattern || '.')
386
+ const userRe = b.whenUserPattern ? new RegExp(b.whenUserPattern) : null
387
+ const turns = facts.turns.filter((t) => String(t.user || '').trim() && !t.delegated && (!userRe || userRe.test(t.user)))
388
+ if (turns.length === 0) return { status: 'unknown', hits: 0, base: 0, rate: null, detail: '无带指令的轮次', samples: [] }
389
+ const bad = turns.filter((t) => !(t.writes || []).some((w) => fre.test(w.path) && (w.mtimeMs || 0) - (t.startTime || 0) <= within))
390
+ const samples = bad.slice(0, 5).map((t) => ({ at: when(t.startTime), session: t.session, seq: t.seq, user: userLine(t), atMs: t.startTime }))
391
+ const r = result(bad.length, turns.length, samples)
392
+ r.detail = `${turns.length} 个带指令轮次里,${bad.length} 轮在 ${Math.round(within / 1000)}s 内没有落盘`
393
+ return r
394
+ }
395
+
396
+ /** 单次调用阻塞超阈值且未后台化(duration)。 */
397
+ PREDICATES.duration = function (facts, b) {
398
+ const limit = Number(b.minMinutes || 10) * 60000
399
+ const measured = facts.commands.filter((c) => c.endAt > c.startedAt && (c.endAt - c.startedAt) < 4 * 3600 * 1000)
400
+ if (measured.length === 0) return { status: 'unknown', hits: 0, base: 0, rate: null, detail: '无耗时样本', samples: [] }
401
+ const bad = measured.filter((c) => (c.endAt - c.startedAt) >= limit && !c.backgrounded)
402
+ const longest = Math.max(...measured.map((c) => c.endAt - c.startedAt))
403
+ const r = result(bad.length, measured.length, bad)
404
+ r.detail += `;最长 ${Math.round(longest / 1000)}s`
405
+ return r
406
+ }
407
+
408
+ /** 平台指标阈值(metric)。 */
409
+ PREDICATES.metric = function (facts, b) {
410
+ const v = facts.metrics?.[b.key]
411
+ if (v === undefined || v === null) return { status: 'unknown', hits: 0, base: 0, rate: null, detail: `指标 ${b.key} 不可得`, samples: [] }
412
+ const ok = b.op === '<=' ? v <= Number(b.threshold) : v >= Number(b.threshold)
413
+ return { status: ok ? 'pass' : 'violation', hits: ok ? 0 : 1, base: 1, rate: ok ? 0 : 1, detail: `${b.key}=${(v * 100).toFixed(1)}%(阈值 ${b.op} ${b.threshold * 100}%)`, samples: [] }
414
+ }
415
+
416
+ const NEED = {
417
+ 'path-boundary': ['pattern'],
418
+ 'field-presence': ['fields'],
419
+ 'count-threshold': ['consecutiveFailures'],
420
+ 'turn-condition': [],
421
+ 'sequence-order': ['taskPattern', 'first', 'then'],
422
+ duration: ['minMinutes'],
423
+ metric: ['key', 'threshold'],
424
+ regex: ['pattern'],
425
+ never: ['pattern'],
426
+ 'per-turn-cap': ['toolPattern', 'maxPerTurn'],
427
+ 'change-gate': ['sections'],
428
+ }
429
+
430
+ export function runPredicate(facts, bind) {
431
+ const need = NEED[bind?.type] || []
432
+ const missing = need.filter((k) => {
433
+ const v = bind[k]
434
+ if (Array.isArray(v)) return v.length === 0
435
+ return v === undefined || v === null || v === ''
436
+ })
437
+ if (missing.length) {
438
+ return { status: 'unknown', hits: 0, base: 0, rate: null, detail: `判据参数缺失:${missing.join('、')}(${bind?.type}),不予判定`, samples: [] }
439
+ }
440
+
441
+ const fn = bind && PREDICATES[bind.type]
442
+ if (!fn) return { status: 'unknown', detail: `未实现谓词:${bind?.type || '(无)'}`, samples: [] }
443
+ try { return fn(facts, bind) } catch (e) { return { status: 'unknown', detail: `谓词执行失败:${e.message}`, samples: [] } }
444
+ }
package/lib/report.js ADDED
@@ -0,0 +1,66 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ /** 判定层:规则来自 policy,判据来自 rule.observe.bind(六类谓词之一)。 */
4
+ import { PREDICATES } from './predicates.js'
5
+ import { runPredicate } from './predicates.js'
6
+ import { guidanceFor } from './source.js'
7
+ import { dedupeRules } from './dedupe.js'
8
+
9
+ const SEVERITY = { violation: 3, warn: 2, stat: 1, pass: 2, unknown: 0 }
10
+
11
+ /** 按容忍度收敛结论:小比例违规降级为 warn/pass,避免满屏飘红。 */
12
+ /** 严重度映射(照 OpenClaw 的口径):red=客观不可争议,yellow=判据明确但非阻塞,stat=只统计。 */
13
+ function statusFor(hits, base, rule) {
14
+ if (!hits) return 'pass'
15
+ const sev = rule.severity || (rule.kind === 'constraint' ? 'red' : 'yellow')
16
+ if (sev === 'stat') return 'stat'
17
+ if (sev === 'red') return 'violation'
18
+ return 'warn'
19
+ }
20
+
21
+ export function evaluate(policy, facts) {
22
+ const rules = Array.isArray(policy?.rules) ? policy.rules : []
23
+ return rules.map((r) => {
24
+ const binds = []
25
+ if (Array.isArray(r.observe?.binds)) binds.push(...r.observe.binds.filter((b) => b && b.type))
26
+ else if (r.observe?.bind?.type) binds.push(r.observe.bind)
27
+ if (!binds.length) {
28
+ return { id: r.id, title: r.title, kind: r.kind, status: 'unknown', detail: '未声明谓词绑定(semantic 规则,仅提示)', metric: r.observe?.metric || '', hits: 0, base: 0, rate: null }
29
+ }
30
+ const vs = binds.map((b) => {
31
+ const v = runPredicate(facts, b)
32
+ const status = v.status === 'unknown' ? 'unknown' : statusFor(v.hits ?? 0, v.base ?? 0, { ...r, severity: r.severity || b.severity })
33
+ return { bind: b, v: { ...v, status } }
34
+ })
35
+ const worst = vs.reduce((a, b) => (SEVERITY[b.v.status] > SEVERITY[a.v.status] ? b : a), vs[0])
36
+ const detail = vs.length === 1 ? worst.v.detail : vs.map((x) => `[${x.bind.type}] ${x.v.status} · ${x.v.detail}`).join(';')
37
+ return {
38
+ id: r.id, title: r.title, kind: r.kind, status: worst.v.status, detail,
39
+ metric: r.observe?.metric || '', samples: worst.v.samples,
40
+ hits: worst.v.hits ?? 0, base: worst.v.base ?? 0, rate: worst.v.rate ?? null,
41
+ bindTypes: binds.map((b) => b.type),
42
+ }
43
+ })
44
+ }
45
+
46
+ export function render(policy, facts, rows, source = { kind: 'policy', warnings: [] }) {
47
+ const draft = source?.kind === 'agents-draft'
48
+ if (draft) rows = rows.map((r) => ({ ...r, status: 'unknown', detail: `草稿未确认(${r.detail})` }))
49
+ const unknown = rows.filter((r) => r.status === 'unknown').length
50
+ const L = ['观测报告(dsh-ruleset)',
51
+ `数据源:${facts.dir || '-'}(HOME=${facts.home || '-'};${facts.sessions}/${facts.files || 0} 会话,解压 ${facts.bytes || 0}B,失败 ${(facts.unavailable || []).length})`,
52
+ `样本:${facts.sample ? `原 ${facts.sample.rawSize}B → 解 ${facts.sample.decoded}B(${facts.sample.rows} 行,zstd=${facts.sample.zstd})` : '无'}`,
53
+ `事实:${facts.sessions} 会话 / ${facts.turns.length} 轮 / ${facts.commands.length} 命令 / ${facts.fileWrites.length} 写文件`,
54
+ '', '规则状态:']
55
+ for (const r of rows) {
56
+ const num = r.base && !String(r.detail).includes('/') ? ` (${r.hits}/${r.base}${r.rate === null ? '' : ` = ${Math.round(r.rate * 100)}%`})` : ''
57
+ L.push(`- [${r.status}] ${r.title || r.id}${num} — ${r.detail}`)
58
+ }
59
+ L.push('', `汇总:${rows.length - unknown} 条可判定,${unknown} 条 unknown`)
60
+ const ded = dedupeRules(policy?.rules || [], source?.agentsText)
61
+ L.push(`注入:${ded.kept.length} 条进提示词,${ded.skipped.length} 条与 AGENTS.md 重复已跳过(源:${source?.kind || 'none'})`)
62
+ for (const w of (source?.warnings || [])) L.push(`⚠️ ${w}`)
63
+ const guide = guidanceFor(source)
64
+ if (guide.length) L.push('', ...guide)
65
+ return L.join('\n')
66
+ }
package/lib/routes.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * HTTP 适配层(薄):路由只做请求解析与 JSON 包装,实现全部在 service.js。
3
+ * 桌面端 dsh-app:// 下部分路径曾出现 404,客户端已支持回退到工具/命令通道。
4
+ */
5
+ import { createService } from './service.js'
6
+
7
+ const json = (value) => Response.json(value, { headers: { 'cache-control': 'no-store' } })
8
+
9
+ export function registerRoutes(ctx, log) {
10
+ if (typeof ctx?.inject !== 'function') return () => {}
11
+ return ctx.inject(['connection'], (scope) => {
12
+ try { log?.('info', 'connection 注入成功') } catch { /* ignore */ }
13
+ const conn = scope.get?.('connection')
14
+ if (!conn?.fetch?.register) return () => {}
15
+ const svc = createService(ctx)
16
+ const reg = (p, name, label) => {
17
+ let dispose
18
+ scope.effect(() => {
19
+ dispose = conn.fetch.register({
20
+ path: p,
21
+ methods: ['POST'],
22
+ requestBody: 'buffered',
23
+ label,
24
+ fetch: async (req) => {
25
+ let body = {}
26
+ try { body = await req.json() } catch { /* 允许空 body */ }
27
+ try { return json(await svc[name](body)) } catch (e) {
28
+ return json({ ok: false, error: { code: `dsh-ruleset/${name}-failed`, message: e?.message || String(e) } })
29
+ }
30
+ },
31
+ })
32
+ }, label)
33
+ return () => dispose?.()
34
+ }
35
+
36
+ const disposers = [
37
+ reg('/api/dsh-ruleset/report', 'report', 'dsh-ruleset: report'),
38
+ reg('/api/dsh-ruleset/audit', 'audit', 'dsh-ruleset: audit'),
39
+ reg('/api/dsh-ruleset/rules', 'rules', 'dsh-ruleset: rules'),
40
+ reg('/api/dsh-ruleset/add-rule', 'addRule', 'dsh-ruleset: add-rule'),
41
+ reg('/api/dsh-ruleset/remove-rule', 'removeRule', 'dsh-ruleset: remove-rule'),
42
+ reg('/api/dsh-ruleset/update-rule', 'updateRule', 'dsh-ruleset: update-rule'),
43
+ reg('/api/dsh-ruleset/set-tier', 'setTier', 'dsh-ruleset: set-tier'),
44
+ reg('/api/dsh-ruleset/dedupe', 'dedupe', 'dsh-ruleset: dedupe'),
45
+ reg('/api/dsh-ruleset/init', 'init', 'dsh-ruleset: init'),
46
+ reg('/api/dsh-ruleset/predicates', 'predicates', 'dsh-ruleset: predicates'),
47
+ reg('/api/dsh-ruleset/parse', 'parse', 'dsh-ruleset: parse'),
48
+ reg('/api/dsh-ruleset/judge', 'judge', 'dsh-ruleset: judge'),
49
+ reg('/api/dsh-ruleset/introspect', 'introspect', 'dsh-ruleset: introspect'),
50
+ reg('/api/dsh-ruleset/suggest', 'suggest', 'dsh-ruleset: suggest'),
51
+ reg('/api/dsh-ruleset/baseline', 'baseline', 'dsh-ruleset: baseline'),
52
+ reg('/api/dsh-ruleset/finding-status', 'findingStatus', 'dsh-ruleset: finding-status'),
53
+ reg('/api/dsh-ruleset/hygiene', 'hygiene', 'dsh-ruleset: hygiene'),
54
+ reg('/api/dsh-ruleset/guard-log', 'guardLog', 'dsh-ruleset: guard-log'),
55
+ reg('/api/dsh-ruleset/injected', 'injected', 'dsh-ruleset: injected'),
56
+ reg('/api/dsh-ruleset/backups', 'backups', 'dsh-ruleset: backups'),
57
+ reg('/api/dsh-ruleset/restore', 'restore', 'dsh-ruleset: restore'),
58
+ reg('/api/dsh-ruleset/export', 'exportKeep', 'dsh-ruleset: export'),
59
+ ]
60
+ return () => disposers.forEach((d) => d?.())
61
+ })
62
+ }