dsh-ruleset 0.0.0-stage → 0.2.1

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 +36 -0
  2. package/DEVELOPMENT.md +121 -0
  3. package/LICENSE +21 -0
  4. package/README.md +68 -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,140 @@
1
+ /** 规则编辑:只在用户从面板显式提交时写 policy.yaml;写前备份、写后校验。 */
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { createRequire } from 'node:module'
5
+ import { validatePolicy } from './validate.js'
6
+ import { resolveRuleSource } from './source.js'
7
+ import { backupPolicy } from './backups.js'
8
+
9
+ const require = createRequire(import.meta.url)
10
+ const yaml = require('js-yaml')
11
+
12
+ export function policyFile() {
13
+ return path.join(process.env.HOME || '', '.dsh', 'workspace', 'policy.yaml')
14
+ }
15
+
16
+ export function listRules() {
17
+ const src = resolveRuleSource('')
18
+ const rules = (src.policy?.rules || []).map((r) => ({
19
+ id: r.id, kind: r.kind, title: r.title, text: r.text,
20
+ predicate: r.observe?.bind?.type || null,
21
+ bind: r.observe?.bind || null,
22
+ }))
23
+ return { file: src.file, kind: src.kind, draft: src.kind === 'agents-draft', rules }
24
+ }
25
+
26
+ export function addRule({ id, title, text, kind = 'protocol', bind, binds, tier } = {}) {
27
+ if (!id || !/^[a-z][a-z0-9-]*$/.test(id)) return { ok: false, error: 'id 必须是 kebab-case' }
28
+ if (!title || !text) return { ok: false, error: 'title 与 text 必填' }
29
+ const file = policyFile()
30
+ let policy
31
+ try { policy = yaml.load(fs.readFileSync(file, 'utf8')) } catch { policy = { version: 1, rules: [] } }
32
+ if (!policy || !Array.isArray(policy.rules)) policy = { version: 1, rules: [] }
33
+ if (policy.rules.some((r) => r.id === id)) return { ok: false, error: `规则 ${id} 已存在` }
34
+ const norm = (x) => String(x || '').replace(/\s+/g, '').trim()
35
+ if (policy.rules.some((r) => norm(r.text) === norm(text) || norm(r.title) === norm(title))) {
36
+ return { ok: false, error: '已经有内容相同的规则了,不重复创建' }
37
+ }
38
+ const rule = { id, kind, title, text, tier: ['redline','hard','soft'].includes(tier) ? tier : 'hard', observe: { metric: id.replace(/-/g, '_') } }
39
+ const list = Array.isArray(binds) ? binds.filter((b) => b && b.type) : []
40
+ if (list.length > 1) rule.observe.binds = list
41
+ else if (list.length === 1) rule.observe.bind = list[0]
42
+ else if (bind && bind.type) rule.observe.bind = bind
43
+ policy.rules.push(rule)
44
+ const v = validatePolicy(policy)
45
+ if (!v.ok) return { ok: false, error: v.errors.join('; ') }
46
+ try {
47
+ backupPolicy('add-rule')
48
+ fs.mkdirSync(path.dirname(file), { recursive: true })
49
+ fs.writeFileSync(file, yaml.dump(policy, { noRefs: true, lineWidth: 200 }))
50
+ } catch (e) { return { ok: false, error: `写入失败:${e.message}` } }
51
+ return { ok: true, file, total: policy.rules.length, rule }
52
+ }
53
+
54
+ export function updateRule({ id, title, text, bind, binds } = {}) {
55
+ if (!id) return { ok: false, error: '缺少 id' }
56
+ const file = policyFile()
57
+ let policy
58
+ try { policy = yaml.load(fs.readFileSync(file, 'utf8')) } catch { return { ok: false, error: 'policy.yaml 读不出来' } }
59
+ if (!policy || !Array.isArray(policy.rules)) return { ok: false, error: 'policy.yaml 结构异常' }
60
+ const rule = policy.rules.find((r) => r.id === id)
61
+ if (!rule) return { ok: false, error: `没有找到规则 ${id}` }
62
+ if (title) rule.title = title
63
+ if (text) rule.text = text
64
+ if (Array.isArray(binds)) {
65
+ const list = binds.filter((b) => b && b.type)
66
+ const next = { ...(rule.observe || {}) }
67
+ delete next.binds
68
+ delete next.bind
69
+ if (list.length > 1) next.binds = list
70
+ else if (list.length === 1) next.bind = list[0]
71
+ rule.observe = next
72
+ } else if (bind && bind.type) rule.observe = { ...(rule.observe || {}), bind }
73
+ const v = validatePolicy(policy)
74
+ if (!v.ok) return { ok: false, error: v.errors.join('; ') }
75
+ try {
76
+ backupPolicy('write')
77
+ fs.writeFileSync(file, yaml.dump(policy, { noRefs: true, lineWidth: 200 }))
78
+ } catch (e) { return { ok: false, error: `写入失败:${e.message}` } }
79
+ return { ok: true, rule }
80
+ }
81
+
82
+ export function setTier({ id, tier } = {}) {
83
+ const TIERS = ['redline', 'hard', 'soft']
84
+ if (!id || !TIERS.includes(tier)) return { ok: false, error: `tier 必须是 ${TIERS.join('|')}` }
85
+ const file = policyFile()
86
+ let policy
87
+ try { policy = yaml.load(fs.readFileSync(file, 'utf8')) } catch { return { ok: false, error: 'policy.yaml 读不出来' } }
88
+ const rule = (policy.rules || []).find((r) => r.id === id)
89
+ if (!rule) return { ok: false, error: `没有找到规则 ${id}` }
90
+ rule.tier = tier
91
+ try {
92
+ backupPolicy('write')
93
+ fs.writeFileSync(file, yaml.dump(policy, { noRefs: true, lineWidth: 200 }))
94
+ } catch (e) { return { ok: false, error: `写入失败:${e.message}` } }
95
+ return { ok: true, id, tier }
96
+ }
97
+
98
+ export function removeRule({ id } = {}) {
99
+ if (!id) return { ok: false, error: '缺少 id' }
100
+ const file = policyFile()
101
+ let policy
102
+ try { policy = yaml.load(fs.readFileSync(file, 'utf8')) } catch { return { ok: false, error: 'policy.yaml 读不出来' } }
103
+ if (!policy || !Array.isArray(policy.rules)) return { ok: false, error: 'policy.yaml 结构异常' }
104
+ const before = policy.rules.length
105
+ policy.rules = policy.rules.filter((r) => r.id !== id)
106
+ if (policy.rules.length === before) return { ok: false, error: `没有找到规则 ${id}` }
107
+ const v = validatePolicy(policy)
108
+ if (!v.ok) return { ok: false, error: v.errors.join('; ') }
109
+ try {
110
+ backupPolicy('write')
111
+ fs.writeFileSync(file, yaml.dump(policy, { noRefs: true, lineWidth: 200 }))
112
+ } catch (e) { return { ok: false, error: `写入失败:${e.message}` } }
113
+ return { ok: true, removed: id, total: policy.rules.length }
114
+ }
115
+
116
+ export function dedupeRules() {
117
+ const file = policyFile()
118
+ let policy
119
+ try { policy = yaml.load(fs.readFileSync(file, 'utf8')) } catch { return { ok: false, error: 'policy.yaml 读不出来' } }
120
+ if (!policy || !Array.isArray(policy.rules)) return { ok: false, error: 'policy.yaml 结构异常' }
121
+ // 同组里优先保留“有判据”的那条,其次保留最早出现的
122
+ const groups = new Map()
123
+ for (const r of policy.rules) {
124
+ const k = `${String(r.title || '').trim()}|${String(r.text || '').trim()}`
125
+ const cur = groups.get(k)
126
+ if (!cur) { groups.set(k, r); continue }
127
+ const curHas = Boolean(cur.observe?.bind)
128
+ const newHas = Boolean(r.observe?.bind)
129
+ if (!curHas && newHas) groups.set(k, r)
130
+ }
131
+ const kept = [...groups.values()]
132
+ const removed = policy.rules.length - kept.length
133
+ if (removed === 0) return { ok: true, removed: 0, total: kept.length }
134
+ policy.rules = kept
135
+ try {
136
+ backupPolicy('write')
137
+ fs.writeFileSync(file, yaml.dump(policy, { noRefs: true, lineWidth: 200 }))
138
+ } catch (e) { return { ok: false, error: `写入失败:${e.message}` } }
139
+ return { ok: true, removed, total: kept.length }
140
+ }
package/lib/run.js ADDED
@@ -0,0 +1,109 @@
1
+ /** 审计执行器:facts → policy → 判定 → 扣减已标记 → 快照 → 发现 → 趋势。 */
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { buildFacts } from './facts.js'
5
+ import { evaluate, render } from './report.js'
6
+ import { resolveRuleSource } from './source.js'
7
+ import { saveHistory, readHistory, readSeries, seriesByTime } from './history.js'
8
+ import { explainBind } from './explain.js'
9
+ import { collectFindings, loadFindings, findingSummary } from './findings.js'
10
+ import { guardHits } from './hygiene.js'
11
+ import { readInjected } from './injected-log.js'
12
+ import { loadBaseline, applySignificance, buildBaseline, saveBaseline } from './stats.js'
13
+
14
+ export function snapshotPath() {
15
+ return path.join(process.env.HOME || '', '.dsh', 'workspace', '.ruleset', 'report.json')
16
+ }
17
+
18
+ const TRIAGED = new Set(['false_positive', 'fixed', 'accepted'])
19
+
20
+ export function runAudit({ windowHours = 720, policyPath = '' } = {}) {
21
+ const source = resolveRuleSource(policyPath)
22
+ const policy = source.policy
23
+ const facts = buildFacts(windowHours)
24
+ const rows = evaluate(policy, facts)
25
+
26
+ // 已被标记的发现要从命中里扣掉,否则计数永远不动
27
+ const prior = loadFindings()
28
+ const triaged = {}
29
+ for (const f of Object.values(prior)) {
30
+ if (f && TRIAGED.has(f.status)) triaged[f.ruleId] = (triaged[f.ruleId] || 0) + 1
31
+ }
32
+ for (const r of rows) {
33
+ const sub = triaged[r.id] || 0
34
+ if (!sub) continue
35
+ const hits = Math.max(0, (r.hits || 0) - sub)
36
+ r.hits = hits
37
+ r.rate = r.base > 0 ? hits / r.base : null
38
+ if (hits === 0 && r.status !== 'unknown') r.status = 'pass'
39
+ r.detail = hits === 0 ? `命中已被标记处理(${sub} 条)` : `${r.detail}(已扣减 ${sub} 条已标记)`
40
+ }
41
+
42
+ applySignificance(rows, loadBaseline())
43
+ const summary = {
44
+ total: rows.length,
45
+ pass: rows.filter((r) => r.status === 'pass').length,
46
+ violation: rows.filter((r) => r.status === 'violation').length,
47
+ warn: rows.filter((r) => r.status === 'warn').length,
48
+ stat: rows.filter((r) => r.status === 'stat').length,
49
+ unknown: rows.filter((r) => r.status === 'unknown').length,
50
+ }
51
+
52
+ const payload = {
53
+ at: new Date().toISOString(),
54
+ windowHours,
55
+ source: { kind: source.kind, file: source.file, draft: source.kind === 'agents-draft' },
56
+ facts: {
57
+ sessions: facts.sessions,
58
+ turns: facts.turns.length,
59
+ commands: facts.commands.length,
60
+ writes: facts.fileWrites.length,
61
+ bytes: facts.bytes || 0,
62
+ unavailable: (facts.unavailable || []).length,
63
+ },
64
+ summary,
65
+ rows: rows.map((r) => {
66
+ const rule = (policy.rules || []).find((x) => x.id === r.id) || {}
67
+ const bindList = Array.isArray(rule.observe?.binds) ? rule.observe.binds : (rule.observe?.bind ? [rule.observe.bind] : [])
68
+ const bind = bindList[0] || null
69
+ return {
70
+ id: r.id, title: r.title, kind: r.kind, status: r.status,
71
+ tier: rule.tier || (rule.kind === 'constraint' ? 'redline' : 'hard'),
72
+ text: rule.text || '',
73
+ bindType: bind?.type || null,
74
+ bindTypes: bindList.map((b) => b.type),
75
+ binds: bindList,
76
+ explain: bindList.length ? bindList.map((b) => explainBind(b)).join(' | ') : explainBind(null),
77
+ hits: r.hits, base: r.base, rate: r.rate, detail: r.detail,
78
+ z: r.z, significance: r.significance,
79
+ samples: (r.samples || []).slice(0, 3),
80
+ }
81
+ }),
82
+ }
83
+
84
+ const findings = collectFindings(rows)
85
+ payload.findings = findings
86
+ payload.guardHits = guardHits(facts.windowStart || 0)
87
+ payload.injected = readInjected(5)
88
+ const bl = loadBaseline()
89
+ const ids = Object.keys(bl)
90
+ payload.baseline = ids.length ? { rules: ids.length, at: Object.values(bl)[0]?.at || '' } : null
91
+ payload.triaged = triaged
92
+ payload.findingSummary = findingSummary(findings)
93
+
94
+ try {
95
+ fs.mkdirSync(path.dirname(snapshotPath()), { recursive: true })
96
+ fs.writeFileSync(snapshotPath(), JSON.stringify(payload, null, 2))
97
+ } catch { /* 快照失败不影响返回 */ }
98
+
99
+ saveHistory(payload)
100
+ const rawSeries = readSeries(200)
101
+ payload.series = rawSeries.slice(-30)
102
+ payload.trend = seriesByTime(rawSeries, 60, 24)
103
+ payload.trendDay = seriesByTime(rawSeries, 1440, 30)
104
+ payload.trendWeek = seriesByTime(rawSeries, 10080, 12)
105
+ payload.trendBucketMinutes = 60
106
+ payload.history = readHistory(14)
107
+
108
+ return { payload, text: render(policy, facts, rows, source) }
109
+ }
package/lib/service.js ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * 唯一的操作实现:工具、HTTP 路由、未来的客户端命令都调这里。
3
+ * 任一处改动都在这个文件里,避免三个入口各写一遍。
4
+ */
5
+ import fs from 'node:fs'
6
+ import { runAudit, snapshotPath } from './run.js'
7
+ import { listRules, addRule, removeRule, dedupeRules, updateRule, setTier } from './rules-edit.js'
8
+ import { setFindingStatus } from './findings.js'
9
+ import { parseSentence } from './extract.js'
10
+ import { parseWithLlm } from './llm-parse.js'
11
+ import { judgeSemantic } from './judge.js'
12
+ import { introspectRule } from './introspect.js'
13
+ import { buildBaseline, saveBaseline, loadBaseline } from './stats.js'
14
+ import { resolveRuleSource } from './source.js'
15
+ import { initDraft } from './init.js'
16
+ import { PREDICATE_DOCS } from './predicates.js'
17
+ import { hygieneReport, guardHits } from './hygiene.js'
18
+ import { readInjected } from './injected-log.js'
19
+ import { listBackups, restoreBackup, exportForKeep, backupPolicy } from './backups.js'
20
+
21
+ const ok = (value) => ({ ok: true, value })
22
+ const fail = (code, message) => ({ ok: false, error: { code, message } })
23
+
24
+ export function createService(ctx) {
25
+ const report = (a = {}) => {
26
+ const hours = Number(a.window_hours) > 0 ? Number(a.window_hours) : 720
27
+ if (a.refresh) return ok(runAudit({ windowHours: hours }).payload)
28
+ try { return ok(JSON.parse(fs.readFileSync(snapshotPath(), 'utf8'))) } catch { return fail('dsh-ruleset/no-report', '还没有报告:先跑一次审计') }
29
+ }
30
+ const audit = (a = {}) => {
31
+ const hours = Number(a.window_hours) > 0 ? Number(a.window_hours) : 720
32
+ return ok(runAudit({ windowHours: hours }).payload)
33
+ }
34
+ return {
35
+ report,
36
+ audit,
37
+ rules: () => ok(listRules()),
38
+ addRule: (a) => { const r = addRule(a); return r.ok ? ok(r) : fail('dsh-ruleset/add-rule-failed', r.error) },
39
+ removeRule: (a) => { const r = removeRule(a); return r.ok ? ok(r) : fail('dsh-ruleset/remove-rule-failed', r.error) },
40
+ updateRule: (a) => { const r = updateRule(a); return r.ok ? ok(r) : fail('dsh-ruleset/update-rule-failed', r.error) },
41
+ setTier: (a) => { const r = setTier(a); return r.ok ? ok(r) : fail('dsh-ruleset/set-tier-failed', r.error) },
42
+ dedupe: () => { const r = dedupeRules(); return r.ok ? ok(r) : fail('dsh-ruleset/dedupe-failed', r.error) },
43
+ init: (a) => { try { return ok(initDraft(a)) } catch (e) { return fail('dsh-ruleset/init-failed', e?.message || String(e)) } },
44
+ predicates: () => ok(Object.entries(PREDICATE_DOCS).map(([type, d]) => ({ type, ...d }))),
45
+ parse: async (a) => {
46
+ const text = String(a?.text || '')
47
+ if (!text.trim()) return fail('dsh-ruleset/bad-request', 'text 为空')
48
+ const viaLlm = await parseWithLlm(ctx, text)
49
+ if (viaLlm && !viaLlm.error) return ok(viaLlm)
50
+ const h = parseSentence(text)
51
+ return ok({ classification: h.classification, bind: h.bind, by: 'heuristic', reason: viaLlm?.error || '' })
52
+ },
53
+ judge: async (a) => {
54
+ const src = resolveRuleSource('')
55
+ return ok(await judgeSemantic(ctx, src.policy || { rules: [] }, { windowHours: Number(a?.window_hours) || 168 }))
56
+ },
57
+ introspect: async (a) => {
58
+ const src = resolveRuleSource('')
59
+ const rules = src.policy?.rules || []
60
+ const targets = a?.id ? rules.filter((r) => r.id === a.id) : rules.slice(0, Number(a?.limit) || 3)
61
+ const items = []
62
+ for (const r of targets) items.push(await introspectRule(ctx, r))
63
+ return ok({ items })
64
+ },
65
+ suggest: () => {
66
+ const src = resolveRuleSource('')
67
+ const out = []
68
+ for (const r of (src.policy?.rules || [])) {
69
+ const binds = Array.isArray(r.observe?.binds) ? r.observe.binds : (r.observe?.bind ? [r.observe.bind] : [])
70
+ if (binds.length) continue
71
+ const parsed = parseSentence(`${r.title || ''}:${r.text || ''}`)
72
+ out.push({ id: r.id, title: r.title, suggestion: parsed.bind || null, classification: parsed.classification })
73
+ }
74
+ return ok({ items: out })
75
+ },
76
+ baseline: (a) => {
77
+ if (a?.action === 'get') return ok(loadBaseline())
78
+ const { payload } = runAudit({ windowHours: Number(a?.window_hours) || 168 })
79
+ const map = buildBaseline(payload.rows)
80
+ return saveBaseline(map) ? ok({ saved: Object.keys(map).length }) : fail('dsh-ruleset/baseline-failed', '写入失败')
81
+ },
82
+ hygiene: () => ok(hygieneReport()),
83
+ injected: (a) => ok({ entries: readInjected(Number(a?.limit) || 20) }),
84
+ backups: () => ok({ items: listBackups() }),
85
+ restore: (a) => { const r = restoreBackup(a?.file); return r.ok ? ok(r) : fail('dsh-ruleset/restore-failed', r.error) },
86
+ backup: (a) => { const r = backupPolicy(a?.action || 'manual'); return r.ok ? ok(r) : fail('dsh-ruleset/backup-failed', r.error) },
87
+ exportKeep: (a) => { const r = exportForKeep(a?.dir); return r.ok ? ok(r) : fail('dsh-ruleset/export-failed', r.error) },
88
+ guardLog: (a) => ok({ hits: guardHits(Date.now() - (Number(a?.window_hours) || 720) * 3600 * 1000) }),
89
+ findingStatus: (a) => { const r = setFindingStatus(a); return r.ok ? ok(r) : fail('dsh-ruleset/finding-status-failed', r.error) },
90
+ }
91
+ }
package/lib/source.js ADDED
@@ -0,0 +1,93 @@
1
+ /**
2
+ * 规则来源解析:policy.yaml → AGENTS.md(自动抽取为 draft)→ 无。
3
+ * draft 模式只注入、不判定:所有规则状态 unknown,并明确告诉用户怎么确认。
4
+ */
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { loadPolicy } from './policy.js'
8
+ import { extractFromAgents } from './extract.js'
9
+
10
+ const home = () => process.env.HOME || ''
11
+
12
+ function firstExisting(paths) {
13
+ return paths.find((p) => { try { return p && fs.existsSync(p) } catch { return false } }) || ''
14
+ }
15
+
16
+ export function resolveRuleSource(explicitPolicy = '') {
17
+ // 显式指定路径时不允许回落:读不到就是 none,避免拿别的 policy 冒充
18
+ if (explicitPolicy) {
19
+ if (!fs.existsSync(explicitPolicy)) return { kind: 'none', policy: null, file: explicitPolicy, warnings: [`指定的 policy 不存在:${explicitPolicy}`] }
20
+ const policy = loadPolicy(explicitPolicy)
21
+ if (policy) return { kind: 'policy', policy, file: explicitPolicy, warnings: [] }
22
+ return { kind: 'none', policy: null, file: explicitPolicy, warnings: [`policy 校验失败:${explicitPolicy}`] }
23
+ }
24
+ const policyFile = firstExisting([
25
+ explicitPolicy,
26
+ process.env.DSH_RULESET_POLICY || '',
27
+ path.join(home(), '.dsh', 'workspace', 'policy.yaml'),
28
+ ])
29
+ if (policyFile) {
30
+ const policy = loadPolicy(policyFile)
31
+ if (policy) {
32
+ // 即使规则来自 policy,也读一下 AGENTS.md,供注入去重用
33
+ const agentsFile = firstExisting([
34
+ process.env.DSH_RULESET_AGENTS || '',
35
+ path.join(home(), '.dsh', 'workspace', 'AGENTS.md'),
36
+ ])
37
+ let agentsText = ''
38
+ try { if (agentsFile) agentsText = fs.readFileSync(agentsFile, 'utf8') } catch { /* 读不到就当没有 */ }
39
+ return { kind: 'policy', policy, file: policyFile, agentsFile, agentsText, warnings: [] }
40
+ }
41
+ return { kind: 'none', policy: null, file: policyFile, warnings: [`policy 读取/校验失败:${policyFile}`] }
42
+ }
43
+
44
+ const agentsFile = firstExisting([
45
+ process.env.DSH_RULESET_AGENTS || '',
46
+ path.join(home(), '.dsh', 'workspace', 'AGENTS.md'),
47
+ path.join(process.cwd(), 'AGENTS.md'),
48
+ ])
49
+ if (agentsFile) {
50
+ try {
51
+ const text = fs.readFileSync(agentsFile, 'utf8')
52
+ const res = extractFromAgents(text, path.basename(agentsFile))
53
+ const policy = {
54
+ version: 1,
55
+ meta: { draft: true, source: agentsFile, extractedAt: new Date().toISOString() },
56
+ rules: res.rules,
57
+ }
58
+ return {
59
+ kind: 'agents-draft',
60
+ agentsFile,
61
+ agentsText: text,
62
+ policy,
63
+ file: agentsFile,
64
+ counts: res.byClass,
65
+ warnings: [`规则来自 ${path.basename(agentsFile)} 的自动抽取(${res.total} 条),尚未确认,只注入不判定`],
66
+ }
67
+ } catch (e) {
68
+ return { kind: 'none', policy: null, file: agentsFile, warnings: [`AGENTS.md 抽取失败:${e.message}`] }
69
+ }
70
+ }
71
+ return { kind: 'none', policy: null, file: '', warnings: ['未找到 policy.yaml 或 AGENTS.md'] }
72
+ }
73
+
74
+ /** 给普通用户的引导:三步走,可复制。 */
75
+ export function guidanceFor(source) {
76
+ if (source.kind === 'policy') return []
77
+ if (source.kind === 'agents-draft') {
78
+ return [
79
+ '## 需要你确认(当前为草稿)',
80
+ '',
81
+ `1. 你的规则目前从 \`${path.basename(source.file)}\` 自动抽取,共 ${source.policy.rules.length} 条;它们只被注入提示词,**不参与判定**`,
82
+ '2. 生成可编辑的草稿:`node scripts/extract.mjs AGENTS.md policy.draft.yaml`',
83
+ '3. 删掉不想要的、给关键几条补上 `observe.bind`,改名为 `policy.yaml` 放到 `~/.dsh/workspace/`;重启后规则即参与判定',
84
+ ]
85
+ }
86
+ return [
87
+ '## 还没有规则来源',
88
+ '',
89
+ '1. 立刻可用:把 `examples/policy.starter.yaml` 复制成 `~/.dsh/workspace/policy.yaml`',
90
+ '2. 或从自己的 AGENTS.md 抽取:`node scripts/extract.mjs AGENTS.md policy.draft.yaml`',
91
+ '3. 什么都不做也可以:插件不会误判,报告会一直显示「无规则来源」',
92
+ ]
93
+ }
package/lib/stats.js ADDED
@@ -0,0 +1,63 @@
1
+ /** 显著性判定(移植自 OpenClaw audit-verdict.py 的两比例 z 检验)。 */
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+
5
+ export const Z_CRIT = 1.96
6
+
7
+ export function twoPropZ(okCur, nCur, okBase, nBase) {
8
+ if (nCur <= 0 || nBase <= 0) return null
9
+ const p1 = okCur / nCur
10
+ const p2 = okBase / nBase
11
+ const p = (okCur + okBase) / (nCur + nBase)
12
+ const se = Math.sqrt(p * (1 - p) * (1 / nCur + 1 / nBase))
13
+ if (!Number.isFinite(se) || se <= 0) return null
14
+ return (p1 - p2) / se
15
+ }
16
+
17
+ const file = () => path.join(process.env.HOME || '', '.dsh', 'workspace', '.ruleset', 'baseline.json')
18
+
19
+ export function loadBaseline() {
20
+ try { return JSON.parse(fs.readFileSync(file(), 'utf8')) } catch { return {} }
21
+ }
22
+
23
+ export function saveBaseline(map) {
24
+ try {
25
+ fs.mkdirSync(path.dirname(file()), { recursive: true })
26
+ fs.writeFileSync(file(), JSON.stringify(map, null, 2))
27
+ return true
28
+ } catch { return false }
29
+ }
30
+
31
+ /** 用当前结果建基线(只存可判定的规则)。 */
32
+ export function buildBaseline(rows) {
33
+ const map = {}
34
+ for (const r of rows) {
35
+ if (!r.base) continue
36
+ map[r.id] = { n: r.base, ok: r.base - (r.hits || 0), at: new Date().toISOString() }
37
+ }
38
+ return map
39
+ }
40
+
41
+ /**
42
+ * 与基线比较:差异不显著 → inconclusive(灰),显著变差 → 保留 violation。
43
+ * 样本不足(<30)直接返回原状态,避免小样本误报。
44
+ */
45
+ export function applySignificance(rows, baseline) {
46
+ for (const r of rows) {
47
+ const b = baseline[r.id]
48
+ if (!b || !r.base || r.base < 30) continue
49
+ const okCur = r.base - (r.hits || 0)
50
+ const z = twoPropZ(okCur, r.base, b.ok, b.n)
51
+ if (z === null) continue
52
+ r.z = Number(z.toFixed(2))
53
+ if (Math.abs(z) < Z_CRIT) {
54
+ if (r.status === 'violation' || r.status === 'warn') {
55
+ r.significance = 'inconclusive'
56
+ r.detail = `${r.detail}(较基线差异不显著 z=${r.z})`
57
+ }
58
+ } else if (z < 0) {
59
+ r.detail = `${r.detail}(显著变差 z=${r.z})`
60
+ }
61
+ }
62
+ return rows
63
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * policy 校验:零依赖,按 schema/policy.schema.json 的核心约束逐条查。
3
+ * 目的:坏 policy 必须报错,而不是静默变成 unknown。
4
+ */
5
+ const KINDS = new Set(['constraint', 'protocol'])
6
+ const MECHANISMS = new Set(['instruction', 'hook', 'tool'])
7
+ import { PREDICATE_DOCS, PREDICATES } from './predicates.js'
8
+
9
+ // 允许的判据类型以 predicates.js 的实现为准,避免两处清单漂移
10
+ const PREDICATE_TYPES = new Set([...Object.keys(PREDICATE_DOCS), ...Object.keys(PREDICATES)])
11
+
12
+ /** 每类判据的必填参数:缺了就是“判据不成立”,必须报错而不是静默通过。 */
13
+ const REQUIRED_PARAMS = {
14
+ 'path-boundary': [['pattern']],
15
+ 'field-presence': [['fields']],
16
+ 'count-threshold': [['consecutiveFailures']],
17
+ 'turn-condition': [['ifTurnCallMin'], ['thenPattern']],
18
+ 'sequence-order': [['taskPattern'], ['first'], ['then']],
19
+ requires: [['ifPathPattern', 'ifContentPattern']],
20
+ duration: [['minMinutes']],
21
+ metric: [['key'], ['threshold']],
22
+ regex: [['pattern']],
23
+ 'explain-first': [],
24
+ }
25
+
26
+ function checkParams(bind, at, errors, warnings) {
27
+ const req = REQUIRED_PARAMS[bind.type]
28
+ if (!req) return
29
+ for (const group of req) {
30
+ const ok = group.some((k) => {
31
+ const v = bind[k]
32
+ if (Array.isArray(v)) return v.length > 0
33
+ return v !== undefined && v !== null && v !== ''
34
+ })
35
+ if (!ok) warnings.push(`${at}.observe.bind 缺少 ${group.join(' 或 ')}(${bind.type} 判据不成立,将被判为 unknown)`)
36
+ }
37
+ }
38
+
39
+ export function validatePolicy(policy) {
40
+ const errors = []
41
+ const warnings = []
42
+ if (!policy || typeof policy !== 'object') return { ok: false, errors: ['policy 不是对象'] }
43
+ if (typeof policy.version !== 'number') errors.push('version 必须是数字')
44
+ if (!Array.isArray(policy.rules)) return { ok: false, errors: [...errors, 'rules 必须是数组'] }
45
+ const ids = new Set()
46
+ policy.rules.forEach((r, i) => {
47
+ const at = `rules[${i}]`
48
+ if (!r || typeof r !== 'object') { errors.push(`${at} 不是对象`); return }
49
+ if (!r.id || !/^[a-z][a-z0-9-]*$/.test(r.id)) errors.push(`${at}.id 非法(要求 kebab-case)`)
50
+ else if (ids.has(r.id)) errors.push(`${at}.id 重复:${r.id}`)
51
+ else ids.add(r.id)
52
+ if (!KINDS.has(r.kind)) errors.push(`${at}.kind 必须是 constraint|protocol`)
53
+ if (!r.title) errors.push(`${at}.title 缺失`)
54
+ if (!r.text) errors.push(`${at}.text 缺失`)
55
+ if (r.mechanism && !MECHANISMS.has(r.mechanism)) errors.push(`${at}.mechanism 非法`)
56
+ const b = r.observe?.bind
57
+ if (b) {
58
+ if (!PREDICATE_TYPES.has(b.type)) errors.push(`${at}.observe.bind.type 未知:${b.type}`)
59
+ else checkParams(b, at, errors, warnings)
60
+ for (const [i, x] of (Array.isArray(r.observe?.binds) ? r.observe.binds.entries() : [])) {
61
+ if (!x || !PREDICATE_TYPES.has(x.type)) errors.push(`${at}.observe.binds[${i}].type 未知:${x?.type}`)
62
+ else checkParams(x, `${at}.observe.binds[${i}]`, errors, warnings)
63
+ }
64
+ for (const key of ['pattern', 'thenPattern', 'ifPattern', 'ifPathPattern', 'ifContentPattern', 'excludePath', 'requireUserPermit', 'pathPattern']) {
65
+ if (b[key]) {
66
+ try { new RegExp(b[key]) } catch (e) { errors.push(`${at}.observe.bind.${key} 不是合法正则:${e.message}`) }
67
+ }
68
+ }
69
+ if (b.minSamples !== undefined && !(Number(b.minSamples) > 0)) errors.push(`${at}.observe.bind.minSamples 必须 > 0`)
70
+ }
71
+ })
72
+ return { ok: errors.length === 0, errors, warnings }
73
+ }
package/locale/en.json ADDED
@@ -0,0 +1 @@
1
+ { "ruleset": { "title": "Ruleset", "refresh": "Refresh", "init": "Draft policy" } }
package/locale/zh.json ADDED
@@ -0,0 +1 @@
1
+ { "ruleset": { "title": "规则合规", "refresh": "刷新", "init": "生成草稿" } }
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "dsh-ruleset",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.1",
4
+ "type": "module",
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
+ "main": "./lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./client": "./client.js",
10
+ "./package.json": "./package.json",
11
+ "./cordis.patch.yml": "./cordis.patch.yml",
12
+ "./locale/*.json": "./locale/*.json"
13
+ },
14
+ "files": [
15
+ "CHANGELOG.md",
16
+ "DEVELOPMENT.md",
17
+ "LICENSE",
18
+ "README.md",
19
+ "client.js",
20
+ "cordis.patch.yml",
21
+ "docs",
22
+ "docs-schema.md",
23
+ "examples",
24
+ "lib",
25
+ "locale",
26
+ "schema",
27
+ "test"
28
+ ],
29
+ "dsh": {
30
+ "bundle": {
31
+ "patch": "./cordis.patch.yml"
32
+ },
33
+ "client": {
34
+ "platform": "web",
35
+ "immediately": true,
36
+ "inject": [
37
+ "@deepseek-ai/dsh-client-connection",
38
+ "@deepseek-ai/dsh-client-locale",
39
+ "@deepseek-ai/dsh-client-ui-conversation",
40
+ "@deepseek-ai/dsh-client-ui-sidebar-right"
41
+ ]
42
+ }
43
+ },
44
+ "dependencies": {
45
+ "js-yaml": "^4.1.0"
46
+ },
47
+ "license": "MIT",
48
+ "scripts": {
49
+ "test": "node --test test/*.test.mjs"
50
+ },
51
+ "engines": {
52
+ "node": ">=22"
53
+ },
54
+ "keywords": [
55
+ "dsh",
56
+ "dsh-plugin",
57
+ "agent-behavior",
58
+ "compliance",
59
+ "policy",
60
+ "audit"
61
+ ],
62
+ "author": "caifengmao",
63
+ "repository": {
64
+ "type": "git",
65
+ "url": "git+https://github.com/cengcengcai-creator/dsh-ruleset.git"
66
+ },
67
+ "homepage": "https://github.com/cengcengcai-creator/dsh-ruleset#readme",
68
+ "bugs": {
69
+ "url": "https://github.com/cengcengcai-creator/dsh-ruleset/issues"
70
+ }
6
71
  }