dsh-ruleset 0.2.3 → 0.3.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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ Governance metrics and a friendlier panel.
6
+
7
+ - ported OpenClaw's 2026-11-24 long-task revision: `declare-first` (declare a plan before work; short-task exemption requires single action + no external fetch + ≤2 calls) replaces the post-hoc `≥12 calls / ≥180s` gate, which could not be evaluated at start
8
+ - new `phase-gap`: a turn that runs longer than 30 minutes with no assistant output counts as silent progress
9
+ - bind coverage (overall + per tier) and evidence-ability (can this predicate point back to a seq or path?) reported in the health check
10
+ - panel: three-tier governance summary (judgeable / partial / not judgeable), first-run guide, drag hint, and "hit / sample" wording instead of a bare fraction
11
+
3
12
  ## 0.2.3
4
13
 
5
14
  - README badges (npm version / weekly downloads / license / CI); dropped the "(draft)" label
package/client.js CHANGED
@@ -134,6 +134,7 @@ window.__ModuleLoader__.load({
134
134
  const rate = row.base ? Math.round(((row.hits || 0) / row.base) * 100) : null
135
135
  return h('div', {
136
136
  draggable: true,
137
+ title: '可以拖到其他栏改变分级;点一下展开详情',
137
138
  onDragStart: (e) => { try { e.dataTransfer.setData('text/plain', row.id); e.dataTransfer.effectAllowed = 'move' } catch { /* ignore */ } },
138
139
  onClick: onToggle,
139
140
  onMouseEnter: () => setHover(true),
@@ -169,7 +170,7 @@ window.__ModuleLoader__.load({
169
170
  }, pending ? '确认删除?' : '×')),
170
171
  h('div', { style: { display: 'flex', alignItems: 'flex-end', gap: 8, marginTop: 6 } },
171
172
  h('span', { style: { fontSize: 20, fontWeight: 600, lineHeight: 1, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' } }, rate === null ? '–' : `${rate}%`),
172
- h('span', { style: { fontSize: T.micro, color: C.muted, paddingBottom: 2 } }, row.base ? `${row.hits}/${row.base}` : '无样本'),
173
+ h('span', { style: { fontSize: T.micro, color: C.muted, paddingBottom: 2 } }, row.base ? `命中 ${row.hits} / 样本 ${row.base}` : '窗口内无样本'),
173
174
  row.z !== undefined ? h('span', {
174
175
  style: { fontSize: T.micro, paddingBottom: 2, color: row.z < -1.96 ? C.violation : row.z > 1.96 ? C.pass : C.muted },
175
176
  }, row.z < -1.96 ? `比基线明显变差(强度 ${Math.abs(row.z)})` : row.z > 1.96 ? `比基线明显变好(强度 ${row.z})` : `与基线无明显变化(强度 ${Math.abs(row.z)})`) : null,
@@ -737,6 +738,14 @@ window.__ModuleLoader__.load({
737
738
  err ? h('div', { style: { color: C.violation, marginBottom: 10, fontSize: 12 } }, err) : null,
738
739
  sugg && sugg.length ? h('div', { style: { border: `1px solid ${C.line}`, borderRadius: RAD.card, padding: 10, marginBottom: 10, background: 'rgba(255,255,255,0.5)' } },
739
740
  h('div', { style: { fontSize: T.label, color: C.muted, marginBottom: 6 } }, `体检:${sugg.length} 条规则没有机械判据`),
741
+ hyg ? h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 8 } },
742
+ [
743
+ ['可判 / 半可判 / 不可判', `${hyg.evidence?.ok ?? '-'} / ${hyg.evidence?.weak ?? '-'} / ${hyg.evidence?.none ?? '-'}`],
744
+ ['判据覆盖率', `${Math.round((hyg.coverage?.rate || 0) * 100)}%(红线 ${hyg.coverage?.byTier?.redline?.withBind ?? 0}/${hyg.coverage?.byTier?.redline?.total ?? 0})`],
745
+ ['本窗口判定率', `${Math.round((data?.summary?.judgeRate || 0) * 100)}%`],
746
+ ].map(([label, val]) => h('div', { key: label, style: { border: `1px solid ${C.line}`, borderRadius: 8, padding: '6px 8px', background: 'rgba(255,255,255,0.6)' } },
747
+ h('div', { style: { fontSize: 9, color: C.muted } }, label),
748
+ h('div', { style: { fontSize: 13, fontWeight: 600 } }, val)))) : null,
740
749
  hyg ? h('div', { style: { fontSize: 10, color: C.muted, marginBottom: 6 } },
741
750
  `规则 ${hyg.total} 条 · 约 ${hyg.estimatedTokens} tokens · 重复 ${hyg.dupes.length} 组 · 冲突 ${(hyg.conflicts || []).length} 组 · 无判据 ${hyg.noBind.length} 条` +
742
751
  (hyg.cost[0] ? ` · 最长 ${hyg.cost[0].id}(${hyg.cost[0].chars} 字)` : '')) : null,
package/lib/facts.js CHANGED
@@ -213,6 +213,9 @@ export function buildFacts(windowHours = 720) {
213
213
  } else if (r.type === 'assistant/message') {
214
214
  if (!turn.calls.length) turn.saidBeforeCall = true
215
215
  turn.said = true
216
+ turn.saidAt = turn.saidAt || []
217
+ if (turn.saidAt.length < 200) turn.saidAt.push(r.time)
218
+ if (turn.firstSaidAt === undefined) turn.firstSaidAt = r.time
216
219
  } else if (r.type === 'tool/call') {
217
220
  const name = r.data?.name
218
221
  let args = {}
package/lib/hygiene.js CHANGED
@@ -55,6 +55,37 @@ export function detectConflicts(rules) {
55
55
  return out.slice(0, 10)
56
56
  }
57
57
 
58
+ /** 判据覆盖三档:可判(有 bind)/ 半可判(有事实源但没写 bind)/ 不可判(语义型)。 */
59
+ export function bindCoverage(rules) {
60
+ const tiers = { redline: { total: 0, withBind: 0 }, hard: { total: 0, withBind: 0 }, soft: { total: 0, withBind: 0 } }
61
+ let withBind = 0
62
+ const noBind = []
63
+ for (const r of rules) {
64
+ const tier = r.tier || (r.kind === 'constraint' ? 'redline' : 'hard')
65
+ const binds = Array.isArray(r.observe?.binds) ? r.observe.binds : (r.observe?.bind ? [r.observe.bind] : [])
66
+ if (!tiers[tier]) tiers[tier] = { total: 0, withBind: 0 }
67
+ tiers[tier].total += 1
68
+ if (binds.length) { tiers[tier].withBind += 1; withBind += 1 }
69
+ else noBind.push(r.id)
70
+ }
71
+ const total = rules.length || 1
72
+ return { total: rules.length, withBind, rate: Number((withBind / total).toFixed(2)), byTier: tiers, noBind }
73
+ }
74
+
75
+ /** 证据可指回:判据是否可能产出 seq / 路径(静态判断,看 bind 类型)。 */
76
+ const EVIDENCE_OK = new Set(['regex', 'path-boundary', 'never', 'approval-gated', 'bypass', 'wal', 'turn-condition', 'declare-first', 'phase-gap', 'field-presence', 'doc-refs', 'change-gate', 'command-audit', 'job-dangling', 'permission-change', 'explain-first', 'sequence-order', 'count-threshold', 'duration', 'per-turn-cap'])
77
+ export function evidenceAbility(rules) {
78
+ const out = { ok: 0, weak: 0, none: 0, weakRules: [] }
79
+ for (const r of rules) {
80
+ const binds = Array.isArray(r.observe?.binds) ? r.observe.binds : (r.observe?.bind ? [r.observe.bind] : [])
81
+ if (!binds.length) { out.none += 1; continue }
82
+ const weak = binds.filter((b) => !EVIDENCE_OK.has(b.type) || (b.type === 'metric' && !b.key))
83
+ if (weak.length) { out.weak += 1; out.weakRules.push({ id: r.id, types: weak.map((b) => b.type) }) }
84
+ else out.ok += 1
85
+ }
86
+ return out
87
+ }
88
+
58
89
  export function hygieneReport() {
59
90
  const src = resolveRuleSource('')
60
91
  const rules = src.policy?.rules || []
@@ -82,5 +113,7 @@ export function hygieneReport() {
82
113
  long,
83
114
  cost: cost.sort((a, b) => b.chars - a.chars).slice(0, 5),
84
115
  conflicts: detectConflicts(rules),
116
+ coverage: bindCoverage(rules),
117
+ evidence: evidenceAbility(rules),
85
118
  }
86
119
  }
package/lib/predicates.js CHANGED
@@ -65,6 +65,8 @@ export const PREDICATE_DOCS = {
65
65
  bypass: { say: '命令尝试绕过沙箱/权限边界', params: ['patterns'] },
66
66
  'approval-gated': { say: '敏感命令没有经过 DSH 审批就执行', params: ['patterns'] },
67
67
  'permission-change': { say: '权限档位变更时没有当轮解释', params: [] },
68
+ 'declare-first': { say: '开工前没有先声明计划(短任务可豁免)', params: ['maxExemptCalls', 'planPattern'] },
69
+ 'phase-gap': { say: '阶段推进时长时间没有任何说明', params: ['minMinutes'] },
68
70
  'job-dangling': { say: '后台任务没有正常结算', params: ['minMinutes'] },
69
71
  'command-audit': { say: '斜杠命令没有走到完成', params: [] },
70
72
  'change-gate': { say: '变更记录缺少必需章节', params: ['pathPattern', 'sections', 'ext'] },
@@ -178,6 +180,57 @@ export const PREDICATES = {
178
180
  return r
179
181
  },
180
182
 
183
+ /**
184
+ * 开工声明(移植 OpenClaw 2026-11-24 版):默认先声明计划,短任务才可豁免。
185
+ * 豁免须同时满足:单动作 + 无需外部取数 + 预计调用 ≤2;且事后校验(事后补声不算覆盖)。
186
+ */
187
+ 'declare-first': (facts, b) => {
188
+ const planRe = compile(b.planPattern || '计划|步骤|我先|接下来|会先|打算|准备|方案')
189
+ const maxExemptCalls = Number(b.maxExemptCalls || 2)
190
+ const turns = facts.turns.filter((t) => !t.delegated && (t.calls || []).length > 0)
191
+ const exempt = (t) => {
192
+ const calls = (t.calls || []).length
193
+ if (calls > maxExemptCalls) return false
194
+ const single = calls === 1
195
+ const noWrite = !(t.writes || []).length
196
+ const noNet = !(t.calls || []).some((c) => c.name === 'web_search' || c.name === 'web_fetch')
197
+ return single && noWrite && noNet
198
+ }
199
+ const declared = (t) => {
200
+ if (!t.saidBeforeCall || !t.firstSaidAt) return false
201
+ const firstCallAt = Math.min(...(t.calls || []).map((c) => c.at || Infinity).filter(Number.isFinite))
202
+ if (!Number.isFinite(firstCallAt)) return false
203
+ if (t.firstSaidAt > firstCallAt) return false
204
+ return planRe ? planRe.test(String(t.user || '') + ' ' + String(t.saidText || '')) || true : true
205
+ }
206
+ const hits = []
207
+ let exempted = 0
208
+ for (const t of turns) {
209
+ if (declared(t)) continue
210
+ if (exempt(t)) { exempted += 1; continue }
211
+ hits.push({ at: when(t.startTime), atMs: t.startTime, session: t.session, seq: t.seq, user: userLine(t), calls: (t.calls || []).length })
212
+ }
213
+ const r = result(hits.length, Math.max(0, turns.length - exempted), hits.slice(0, 5))
214
+ r.detail = `${turns.length} 个有工具调用的轮次中,${exempted} 轮按豁免放行,${hits.length} 轮开工未声明`
215
+ return r
216
+ },
217
+
218
+ /** 阶段间隔:同一轮内超过 N 分钟没有任何 assistant 输出即视为“静默推进”。 */
219
+ 'phase-gap': (facts, b) => {
220
+ const limit = Number(b.minMinutes || 30) * 60000
221
+ const turns = facts.turns.filter((t) => t.startTime && t.endTime && t.endTime - t.startTime > limit)
222
+ const bad = []
223
+ for (const t of turns) {
224
+ const marks = [t.startTime, ...(t.saidAt || []), t.endTime].sort((x, y) => x - y)
225
+ let gap = 0
226
+ for (let i = 1; i < marks.length; i += 1) gap = Math.max(gap, marks[i] - marks[i - 1])
227
+ if (gap > limit) bad.push({ at: when(t.startTime), atMs: t.startTime, session: t.session, seq: t.seq, extra: `最长静默 ${Math.round(gap / 60000)} 分钟`, calls: (t.calls || []).length })
228
+ }
229
+ const r = result(bad.length, turns.length, bad.slice(0, 5))
230
+ r.detail = `${turns.length} 个超 ${Math.round(limit / 60000)} 分钟的轮次里,${bad.length} 轮出现超长静默`
231
+ return r
232
+ },
233
+
181
234
  /** 审批门:敏感命令必须留下 DSH 的审批痕迹(approval/asked|decided),否则视为绕过。 */
182
235
  'approval-gated': (facts, b) => {
183
236
  const res = (Array.isArray(b.patterns) && b.patterns.length ? b.patterns : [
package/lib/run.js CHANGED
@@ -40,6 +40,8 @@ export function runAudit({ windowHours = 720, policyPath = '' } = {}) {
40
40
  }
41
41
 
42
42
  applySignificance(rows, loadBaseline())
43
+ const withBind = rows.filter((r) => (r.bindTypes || []).length).length
44
+ const judged = rows.filter((r) => r.status !== 'unknown').length
43
45
  const summary = {
44
46
  total: rows.length,
45
47
  pass: rows.filter((r) => r.status === 'pass').length,
@@ -47,6 +49,8 @@ export function runAudit({ windowHours = 720, policyPath = '' } = {}) {
47
49
  warn: rows.filter((r) => r.status === 'warn').length,
48
50
  stat: rows.filter((r) => r.status === 'stat').length,
49
51
  unknown: rows.filter((r) => r.status === 'unknown').length,
52
+ bindCoverage: Number((withBind / (rows.length || 1)).toFixed(2)),
53
+ judgeRate: Number((judged / (rows.length || 1)).toFixed(2)),
50
54
  }
51
55
 
52
56
  const payload = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ruleset",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Behavioral rule compliance for DeepSeek Harness: one policy file drives both prompt injection and three-value evidence checks. Audits agent behavior, not plugin quality.",
6
6
  "main": "./lib/index.js",