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
package/lib/init.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * ruleset_init:把 AGENTS.md 抽取成 draft policy,写到 <workspace>/.ruleset/policy.draft.yaml。
3
+ * 边界:只在用户显式要求时执行;永不写正式 policy.yaml;已存在则需 overwrite。
4
+ */
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { createRequire } from 'node:module'
8
+ import { extractFromAgents } from './extract.js'
9
+
10
+ const require = createRequire(import.meta.url)
11
+ let yaml = null
12
+ try { yaml = require('js-yaml') } catch { /* 退化 JSON */ }
13
+
14
+ export function initDraft({ workspace, agentsFile, out, overwrite = false } = {}) {
15
+ const ws = workspace || path.join(process.env.HOME || '', '.dsh', 'workspace')
16
+ const outDir = out ? path.dirname(out) : path.join(ws, '.ruleset')
17
+ const outFile = out || path.join(outDir, 'policy.draft.yaml')
18
+ if (fs.existsSync(outFile) && !overwrite) {
19
+ return { ok: false, reason: 'exists', file: outFile }
20
+ }
21
+ const agents = agentsFile || path.join(ws, 'AGENTS.md')
22
+ if (!fs.existsSync(agents)) return { ok: false, reason: 'no-agents', file: agents }
23
+ const text = fs.readFileSync(agents, 'utf8')
24
+ const res = extractFromAgents(text, path.basename(agents))
25
+ const policy = { version: 1, meta: { draft: true, source: agents, extractedAt: new Date().toISOString() }, rules: res.rules }
26
+ fs.mkdirSync(outDir, { recursive: true })
27
+ fs.writeFileSync(outFile, yaml?.dump ? yaml.dump(policy, { noRefs: true, lineWidth: 200 }) : JSON.stringify(policy, null, 2))
28
+ return { ok: true, file: outFile, total: res.total, byClass: res.byClass }
29
+ }
package/lib/inject.js ADDED
@@ -0,0 +1,64 @@
1
+ /** 注入层:把 policy 组装成 systemPrompt 段落(标准化格式,便于 agent 照着执行)。 */
2
+ import { explainBind } from './explain.js'
3
+
4
+ const SHORT_SAY = {
5
+ 'explain-first': '动手前须先解释',
6
+ 'path-boundary': '删除类命令需先确认',
7
+ 'field-presence': '文件须含指定字段',
8
+ 'count-threshold': '连续失败后仍重试算违规',
9
+ 'turn-condition': '长任务须出现指定动作',
10
+ 'sequence-order': '先检索再动手',
11
+ requires: '做了 X 须伴随 Y',
12
+ duration: '阻塞超时须后台化',
13
+ wal: '收到指令后须及时落盘',
14
+ never: '绝对禁止项',
15
+ bypass: '禁止绕过沙箱',
16
+ 'approval-gated': '敏感命令须经 DSH 审批',
17
+ 'permission-change': '权限变更须当轮解释',
18
+ 'job-dangling': '后台任务须结算',
19
+ 'command-audit': '斜杠命令须完成',
20
+ 'change-gate': '变更记录须含必需章节',
21
+ 'per-turn-cap': '单轮调用上限',
22
+ metric: '指标阈值',
23
+ regex: '内容/命令模式匹配',
24
+ }
25
+
26
+ const paramSummary = (bind) => {
27
+ if (!bind) return ''
28
+ const parts = []
29
+ for (const [k, v] of Object.entries(bind)) {
30
+ if (k === 'type' || v === undefined || v === null) continue
31
+ if (Array.isArray(v)) { if (v.length) parts.push(`${k}=${v.join('/')}`) ; continue }
32
+ parts.push(`${k}=${v}`)
33
+ }
34
+ return parts.join(' ')
35
+ }
36
+
37
+ export function composeSection(mode, policy) {
38
+ if (mode === 'off') return ''
39
+ const rules = Array.isArray(policy?.rules) ? policy.rules : []
40
+ const L = [
41
+ '# 工作标准(dsh-ruleset 注入,来自 policy)',
42
+ '格式:`- [类别] 规则名|要求:原文|判定:可检查方式(无判据则为“仅提示”)`。判定由插件机械执行,你只需按要求做。',
43
+ ]
44
+ if (rules.length === 0) {
45
+ L.push('- (未找到 policy:规则未加载,视为 unknown,不要假设没有规则)')
46
+ return L.join('\n')
47
+ }
48
+ const TIER_TITLE = { redline: '红线(不可越界)', hard: '硬约束(会被判定)', soft: '软规则(仅提示或统计)' }
49
+ const TIER_ORDER = ['redline', 'hard', 'soft']
50
+ for (const tier of TIER_ORDER) {
51
+ const group = rules.filter((r) => (r.tier || (r.kind === 'constraint' ? 'redline' : 'hard')) === tier)
52
+ if (!group.length) continue
53
+ L.push('', `## ${TIER_TITLE[tier]}`)
54
+ for (const r of group) {
55
+ const binds = Array.isArray(r.observe?.binds) ? r.observe.binds : (r.observe?.bind ? [r.observe.bind] : [])
56
+ const judge = binds.length
57
+ ? binds.map((b) => `${b.type}(${SHORT_SAY[b.type] || '可检查'})`).join(' + ')
58
+ : '仅提示(不判定)'
59
+ const tail = mode === 'full' && binds.length ? ` → ${binds.map((b) => explainBind(b)).join(';')}` : ''
60
+ L.push(`- [${r.kind || 'protocol'}] ${r.title || r.id}|要求:${r.text || ''}|判定:${judge}${tail}`)
61
+ }
62
+ }
63
+ return L.join('\n')
64
+ }
@@ -0,0 +1,30 @@
1
+ /** 注入可核:记录每次真正送进 system prompt 的规则内容指纹。 */
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import crypto from 'node:crypto'
5
+
6
+ const file = () => path.join(process.env.HOME || '', '.dsh', 'workspace', '.ruleset', 'injected.log')
7
+
8
+ export function recordInjected(text, meta = {}) {
9
+ try {
10
+ const body = String(text || '')
11
+ const hash = crypto.createHash('sha1').update(body).digest('hex').slice(0, 10)
12
+ const dir = path.dirname(file())
13
+ fs.mkdirSync(dir, { recursive: true })
14
+ let last = ''
15
+ try { const lines = fs.readFileSync(file(), 'utf8').trim().split('\n'); last = lines[lines.length - 1] || '' } catch { /* 首次 */ }
16
+ if (last.includes(`\t${hash}\t`)) return { hash, changed: false }
17
+ fs.appendFileSync(file(), `${new Date().toISOString()}\t${hash}\t${body.length}\t${meta.rules || 0}\t${meta.mode || ''}\n`)
18
+ return { hash, changed: true }
19
+ } catch { return { hash: '', changed: false } }
20
+ }
21
+
22
+ export function readInjected(limit = 20) {
23
+ try {
24
+ const lines = fs.readFileSync(file(), 'utf8').trim().split('\n').filter(Boolean)
25
+ return lines.slice(-limit).map((l) => {
26
+ const [at, hash, chars, rules, mode] = l.split('\t')
27
+ return { at, hash, chars: Number(chars), rules: Number(rules), mode }
28
+ })
29
+ } catch { return [] }
30
+ }
@@ -0,0 +1,55 @@
1
+ /** 规则理解:让模型说清「规定什么 / 审计什么 / 对象是什么 / 能否机械化」。 */
2
+ const SYSTEM = [
3
+ '你在做规则审计设计。给你一条工作纪律,输出 JSON:',
4
+ '{"object":"<审计对象,如 命令/文件写入/轮次>","trigger":"<什么条件下检查>","expectation":"<期望动作或字段>","exceptions":"<例外>","mechanical":true|false,"bind":{"type":"...","...":...}|null,"why":"<一句话>"}',
5
+ 'bind 只能用这些类型:path-boundary, field-presence, count-threshold, turn-condition, sequence-order, requires, duration, metric, regex, never, per-turn-cap, wal, change-gate, bypass, explain-first, doc-refs。',
6
+ '只有真能机械核对时才给 bind;对象不明确的,mechanical=false 且 bind=null。',
7
+ ].join('\n')
8
+
9
+ function collect(chunks) {
10
+ let out = ''
11
+ for (const c of chunks) {
12
+ if (!c) continue
13
+ if (typeof c.text === 'string') out += c.text
14
+ else if (typeof c.delta === 'string') out += c.delta
15
+ }
16
+ return out
17
+ }
18
+
19
+ export async function introspectRule(context, rule, { timeoutMs = 20000 } = {}) {
20
+ const llm = context?.get?.('llm')
21
+ if (!llm) return { error: 'llm 不可用' }
22
+ let provider, model
23
+ try {
24
+ const providers = llm.listProviders() || []
25
+ provider = providers[0]?.provider || providers[0]?.id || providers[0]?.name
26
+ const models = await llm.listModels(provider)
27
+ model = models?.[0]?.id || models?.[0]?.model
28
+ } catch (e) { return { error: 'discover: ' + (e?.message || e) } }
29
+ if (!provider || !model) return { error: 'no provider/model' }
30
+ const ac = new AbortController()
31
+ const timer = setTimeout(() => ac.abort(), timeoutMs)
32
+ try {
33
+ const prepared = await llm.prepareCall({ provider, model, maxTokens: 400, reasoningEffort: 'off' }, ac.signal)
34
+ let text = ''
35
+ for await (const c of prepared.stream({ ...prepared.config, system: SYSTEM, messages: [{ role: 'user', content: [{ type: 'text', text: `规则名:${rule.title || rule.id}\n正文:${String(rule.text || '').slice(0, 500)}` }] }], signal: ac.signal })) {
36
+ if (c?.type === 'finish') break
37
+ text += collect([c])
38
+ }
39
+ const m = text.match(/\{[\s\S]*\}/)
40
+ if (!m) return { error: 'no json', raw: text.slice(0, 120) }
41
+ const parsed = JSON.parse(m[0])
42
+ return {
43
+ id: rule.id,
44
+ object: String(parsed.object || '').slice(0, 60),
45
+ trigger: String(parsed.trigger || '').slice(0, 120),
46
+ expectation: String(parsed.expectation || '').slice(0, 120),
47
+ exceptions: String(parsed.exceptions || '').slice(0, 80),
48
+ mechanical: Boolean(parsed.mechanical),
49
+ bind: parsed.bind && parsed.bind.type ? parsed.bind : null,
50
+ why: String(parsed.why || '').slice(0, 160),
51
+ }
52
+ } catch (e) {
53
+ return { error: e?.message || String(e) }
54
+ } finally { clearTimeout(timer) }
55
+ }
package/lib/judge.js ADDED
@@ -0,0 +1,73 @@
1
+ /** 模型裁判:只覆盖没有机械判据的规则,不重复判机械判据已能证明的事。 */
2
+ import { buildFacts } from './facts.js'
3
+
4
+ const SYSTEM = [
5
+ '你是行为审计员。给你一条工作纪律和一段 agent 轨迹摘要,判断该轨迹是否遵守纪律。',
6
+ '只输出 JSON:{"verdict":"pass|violation|unknown","reason":"<=60字","evidence":"<=80字,指到具体轮次或命令"}',
7
+ '判断依据只能是轨迹里出现的证据;看不到证据就输出 unknown,不要猜测。',
8
+ '不要评价纪律本身是否合理。',
9
+ ].join('\n')
10
+
11
+ function trajectoryText(facts, limit = 12) {
12
+ const turns = facts.turns.filter((t) => !t.delegated).slice(-limit)
13
+ const lines = []
14
+ for (const t of turns) {
15
+ const user = String(t.user || '').replace(/\s+/g, ' ').slice(0, 120)
16
+ const calls = (t.calls || []).map((c) => c.name).join(',')
17
+ const writes = (t.writes || []).map((w) => w.path.split('/').pop()).join(',')
18
+ lines.push(`- 轮 ${t.seq}|用户:${user || '(无)'}|工具:${calls || '(无)'}${writes ? `|写入:${writes}` : ''}`)
19
+ }
20
+ return lines.join('\n')
21
+ }
22
+
23
+ async function callModel(context, prompt, timeoutMs = 20000) {
24
+ const llm = context?.get?.('llm')
25
+ if (!llm) return { error: 'llm 不可用' }
26
+ let provider, model
27
+ try {
28
+ const providers = llm.listProviders() || []
29
+ provider = providers[0]?.provider || providers[0]?.id || providers[0]?.name
30
+ const models = await llm.listModels(provider)
31
+ model = models?.[0]?.id || models?.[0]?.model
32
+ } catch (e) { return { error: 'discover: ' + (e?.message || e) } }
33
+ if (!provider || !model) return { error: 'no provider/model' }
34
+ const ac = new AbortController()
35
+ const timer = setTimeout(() => ac.abort(), timeoutMs)
36
+ try {
37
+ const prepared = await llm.prepareCall({ provider, model, maxTokens: 300, reasoningEffort: 'off' }, ac.signal)
38
+ let text = ''
39
+ for await (const c of prepared.stream({ ...prepared.config, system: SYSTEM, messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }], signal: ac.signal })) {
40
+ if (c?.type === 'finish') break
41
+ if (typeof c?.text === 'string') text += c.text
42
+ else if (typeof c?.delta === 'string') text += c.delta
43
+ }
44
+ const m = text.match(/\{[\s\S]*\}/)
45
+ if (!m) return { error: 'no json' }
46
+ return JSON.parse(m[0])
47
+ } catch (e) {
48
+ return { error: e?.message || String(e) }
49
+ } finally { clearTimeout(timer) }
50
+ }
51
+
52
+ export async function judgeSemantic(context, policy, { windowHours = 168 } = {}) {
53
+ const rules = (policy?.rules || []).filter((r) => {
54
+ const binds = Array.isArray(r.observe?.binds) ? r.observe.binds : (r.observe?.bind ? [r.observe.bind] : [])
55
+ return binds.length === 0
56
+ })
57
+ if (!rules.length) return { results: [], skipped: '没有需要模型审查的规则' }
58
+ const facts = buildFacts(windowHours)
59
+ const trail = trajectoryText(facts)
60
+ const results = []
61
+ for (const r of rules.slice(0, 5)) {
62
+ const prompt = `纪律:${r.title || r.id}\n要求:${String(r.text || '').slice(0, 400)}\n\n轨迹(最近 ${Math.min(12, facts.turns.length)} 轮):\n${trail}`
63
+ const out = await callModel(context, prompt)
64
+ results.push({
65
+ id: r.id, title: r.title,
66
+ verdict: ['pass', 'violation', 'unknown'].includes(out?.verdict) ? out.verdict : 'unknown',
67
+ reason: String(out?.reason || out?.error || '').slice(0, 200),
68
+ evidence: String(out?.evidence || '').slice(0, 200),
69
+ at: new Date().toISOString(),
70
+ })
71
+ }
72
+ return { results, windowHours }
73
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * 用宿主模型把「一句话规则」拆成可执行判据;失败时上层回落到启发式。
3
+ * 只读调用,不写文件。
4
+ */
5
+ const SYSTEM = [
6
+ '你把一句用户写的工作纪律,转成一条可机械检查的规则。只输出 JSON。',
7
+ '不要假设用户场景;所有参数都必须来自这句话本身。缺参数就放进 missing,不要瞎填。',
8
+ '输出:{"classification":"<短标签>","bind":{...}|null,"missing":["<参数名>"],"question":"<最多一句>","explain":"<给用户的一句白话解释>","alternatives":[{"type":"<判据类型>","bind":{...},"say":"<这条规则实际会检查什么>","why":"<为什么这样拆>"}]}',
9
+ '可用的判据机制(bind.type)与参数:',
10
+ '0) explain-first:动手(调用工具)之前必须先解释原因与计划,无参数。凡“先解释再操作”“说明计划后再执行”这类都归此类。',
11
+ '1) path-boundary:命令删除了某类路径且未被允许。参数 pattern(JS 正则,匹配命令)、requireApproval(bool)、exemptPaths(数组,可空)',
12
+ '2) field-presence:文件里缺少某些字段。参数 ext(如 .md)、fields(数组)、pathPattern(正则,可空)',
13
+ '3) count-threshold:同一命令连续失败后仍重试。参数 consecutiveFailures(数字)',
14
+ '4) turn-condition:某轮里必须出现某类动作。参数 ifTurnCallMin(数字)、thenPattern(正则)',
15
+ '5) sequence-order:某类任务应先做 A 再做 B。参数 taskPattern(正则)、first(动作名数组)、then(动作名数组)、minSamples(数字)',
16
+ '6) requires:做了 X 就必须伴随 Y。参数 ifPathPattern 或 ifContentPattern(正则)、minSamples(数字)',
17
+ '7) duration:单次调用阻塞超过阈值。参数 minMinutes(数字)',
18
+ '8) metric:某个平台指标超过阈值。参数 key(指标名)、op(<= 或 >=)、threshold(数字)',
19
+ '9) regex:命令或写入内容中出现某模式。参数 sources(["commands"] 或 ["fileWrites"])、pattern(正则)',
20
+ '10) never:绝对禁止某内容(不论是否审批)。参数 sources、pattern(正则)',
21
+ '11) per-turn-cap:单轮最多调用某工具几次。参数 toolPattern(正则)、maxPerTurn(数字)',
22
+ '12) bypass:命令试图绕过权限/沙箱(sudo、越界写入、伪装执行)。参数 patterns(正则数组,可空用默认)',
23
+ '13) change-gate:变更记录必须含指定章节。参数 pathPattern(正则)、sections(章节名数组)',
24
+ '如果整句无法直接机械检查,但可以拆成若干可检查的子规则,bind 设为 null、classification 设 semantic,并在 alternatives 里给出 1-3 个可检查的替代(每个 {type,bind,say,why})。',
25
+ '禁止把拆解工作推回给用户:只要能想到合理拆法,就必须写进 alternatives,question 留空。',
26
+ 'question 只用于“缺少必要参数且无法从原句推断”的情况,且最多一句。',
27
+ '例如“关键事实要有 ≥2 独立来源”可拆成 count-threshold 或 field-presence(要求记录里带 sources 字段与数量)。',
28
+ '只要 classification 是 semantic,alternatives 就必须非空(至少 1 条);只有连“拆成字段要求”都做不到时才可以空。',
29
+ '常见拆法:来源要求→field-presence(fields: sources,url,retrieved_at);数量下限→count-threshold 或 regex 匹配计数;禁止某动作→regex。',
30
+ '正则用 JS 语法,尽量短;不要把用户没写的内容编进去。',
31
+ ].join('\n')
32
+
33
+ function collectText(chunks) {
34
+ let out = ''
35
+ for (const c of chunks) {
36
+ if (!c) continue
37
+ if (typeof c.text === 'string') out += c.text
38
+ else if (typeof c.delta === 'string') out += c.delta
39
+ }
40
+ return out
41
+ }
42
+
43
+ /** 语义类兜底:从句子关键词推测可检查的子规则,至少给出可落地的字段要求。 */
44
+ function heuristicAlternatives(text) {
45
+ const t = String(text || '')
46
+ const out = []
47
+ if (/来源|URL|链接|检索时间|出处/.test(t)) {
48
+ out.push({
49
+ type: 'field-presence',
50
+ bind: { type: 'field-presence', ext: '.md', fields: ['sources', 'url', 'retrieved_at'] },
51
+ say: '要求调研记录里必须写清来源列表、来源 URL、检索时间三个字段',
52
+ why: '把“要可追溯”落成可检查的字段',
53
+ })
54
+ }
55
+ const m = t.match(/(\d+)\s*(?:个|条)?\s*(?:独立)?(?:来源|渠道)/)
56
+ if (m) {
57
+ out.push({
58
+ type: 'regex',
59
+ bind: { type: 'regex', sources: ['fileWrites'], pattern: '(?s)来源.{0,200}' },
60
+ say: `检查记录里是否列出来源条目(至少 ${m[1]} 条)`,
61
+ why: '数量下限需要记录格式配合,先检查结构存在',
62
+ })
63
+ }
64
+ if (!out.length) {
65
+ out.push({
66
+ type: 'field-presence',
67
+ bind: { type: 'field-presence', ext: '.md', fields: ['type', '判定依据'] },
68
+ say: '要求交付记录里必须出现判定依据字段',
69
+ why: '先保证记录自包含,再谈更细的检查',
70
+ })
71
+ }
72
+ return out.slice(0, 3)
73
+ }
74
+
75
+ export async function parseWithLlm(context, text, { timeoutMs = 12000 } = {}) {
76
+ const llm = context?.get?.('llm')
77
+ if (!llm || typeof llm.listProviders !== 'function') return { error: 'llm service not reachable' }
78
+ let provider
79
+ let model
80
+ try {
81
+ const providers = llm.listProviders() || []
82
+ provider = providers[0]?.provider || providers[0]?.id || providers[0]?.name
83
+ if (!provider) return { error: 'no provider' }
84
+ const models = await llm.listModels(provider)
85
+ model = models?.[0]?.id || models?.[0]?.model
86
+ if (!model) return { error: 'no model' }
87
+ } catch (e) { return { error: 'discover: ' + (e?.message || String(e)) } }
88
+
89
+ const ac = new AbortController()
90
+ const timer = setTimeout(() => ac.abort(), timeoutMs)
91
+ try {
92
+ const prepared = await llm.prepareCall({ provider, model, maxTokens: 500, reasoningEffort: 'off' }, ac.signal)
93
+ const opts = {
94
+ ...prepared.config,
95
+ system: SYSTEM,
96
+ messages: [{ role: 'user', content: [{ type: 'text', text }] }],
97
+ signal: ac.signal,
98
+ }
99
+ const chunks = []
100
+ for await (const c of prepared.stream(opts)) {
101
+ if (c?.type === 'finish') break
102
+ chunks.push(c)
103
+ }
104
+ const raw = collectText(chunks).trim()
105
+ const m = raw.match(/\{[\s\S]*\}/)
106
+ if (!m) return { error: 'no json in reply: ' + raw.slice(0, 80) }
107
+ const parsed = JSON.parse(m[0])
108
+ if (!parsed || typeof parsed !== 'object') return { error: 'bad json' }
109
+ const bind = parsed.bind && typeof parsed.bind === 'object' ? parsed.bind : null
110
+ let alternatives = Array.isArray(parsed.alternatives)
111
+ ? parsed.alternatives.filter((a) => a && a.bind && a.bind.type).slice(0, 3).map((a) => ({
112
+ type: String(a.type || a.bind.type), bind: a.bind,
113
+ say: String(a.say || '').slice(0, 120), why: String(a.why || '').slice(0, 120),
114
+ }))
115
+ : []
116
+ if (!alternatives.length && String(parsed.classification) === 'semantic') alternatives = heuristicAlternatives(text)
117
+ return {
118
+ classification: String(parsed.classification || 'process'),
119
+ bind,
120
+ missing: Array.isArray(parsed.missing) ? parsed.missing : [],
121
+ question: typeof parsed.question === 'string' ? parsed.question.slice(0, 120) : '',
122
+ explain: typeof parsed.explain === 'string' ? parsed.explain.slice(0, 200) : '',
123
+ alternatives,
124
+ by: 'llm',
125
+ }
126
+ } catch (e) {
127
+ return { error: 'call: ' + (e?.message || String(e)) }
128
+ } finally {
129
+ clearTimeout(timer)
130
+ }
131
+ }
package/lib/observe.js ADDED
@@ -0,0 +1,132 @@
1
+ /** 观测层:注册 observe_report 工具。判定只给三值,证据指回 seq / 文件。 */
2
+ import { runAudit } from './run.js'
3
+ import { createService } from './service.js'
4
+ import { parseSentence } from './extract.js'
5
+ import { parseWithLlm } from './llm-parse.js'
6
+ import { introspectRule } from './introspect.js'
7
+ import { resolveRuleSource } from './source.js'
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { initDraft } from './init.js'
12
+
13
+ export function registerReportTool(ctx, cfg, source) {
14
+ const initTool = ctx.tools.register({
15
+ name: 'ruleset_init',
16
+ description: '把一个 AGENTS.md 抽取成 draft policy,写到 <workspace>/.ruleset/policy.draft.yaml。只在用户明确要求初始化规则时调用;永不覆盖正式 policy.yaml。',
17
+ parameters: {
18
+ overwrite: { type: 'boolean', description: '已存在 draft 时是否覆盖' },
19
+ },
20
+ output: {
21
+ schema: {
22
+ type: 'object',
23
+ additionalProperties: false,
24
+ required: ['ok', 'detail'],
25
+ properties: {
26
+ ok: { type: 'boolean' },
27
+ file: { type: 'string' },
28
+ detail: { type: 'string' },
29
+ },
30
+ },
31
+ render: (_a, v) => [{ type: 'text', text: v.detail }],
32
+ },
33
+ async execute(args) {
34
+ const hours = Number(args?.window_hours) > 0 ? Number(args.window_hours) : cfg.windowHours
35
+ const { payload, text } = runAudit({ windowHours: hours, policyPath: cfg.policyPath })
36
+ return { report: text, evaluated: payload.rows.length - payload.summary.unknown, unknown: payload.summary.unknown }
37
+ },
38
+ })
39
+ const reportTool = ctx.tools.register({
40
+ name: 'ruleset_audit',
41
+ description: '按规则做验证与报告:读 policy 与会话轨迹,输出三值(pass/violation/unknown)。unknown 表示无数据源或样本不足,不得读作 pass。',
42
+ parameters: { window_hours: { type: 'integer', description: '观测窗口(小时),默认取配置' } },
43
+ output: {
44
+ schema: {
45
+ type: 'object',
46
+ additionalProperties: false,
47
+ required: ['report', 'evaluated', 'unknown'],
48
+ properties: { report: { type: 'string' }, evaluated: { type: 'integer' }, unknown: { type: 'integer' } },
49
+ },
50
+ render: (_a, v) => [{ type: 'text', text: String(v?.report ?? '') }],
51
+ },
52
+ async execute(args) {
53
+ const hours = Number(args?.window_hours) > 0 ? Number(args.window_hours) : cfg.windowHours
54
+ const { payload, text } = runAudit({ windowHours: hours, policyPath: cfg.policyPath })
55
+ return { report: text, evaluated: payload.rows.length - payload.summary.unknown, unknown: payload.summary.unknown }
56
+ },
57
+ })
58
+ const svc = createService(ctx)
59
+
60
+ const parseTool = ctx.tools.register({
61
+ name: 'ruleset_parse',
62
+ description: '把一句规则描述解析成可机械判定的判据(优先用宿主模型,失败回落规则匹配)。返回来源 by=llm|heuristic。',
63
+ parameters: { text: { type: 'string', description: '一句话规则描述' } },
64
+ output: {
65
+ schema: {
66
+ type: 'object',
67
+ additionalProperties: true,
68
+ required: ['by', 'classification'],
69
+ properties: {
70
+ by: { type: 'string' },
71
+ classification: { type: 'string' },
72
+ question: { type: 'string' },
73
+ explain: { type: 'string' },
74
+ },
75
+ },
76
+ render: (_a, v) => [{ type: 'text', text: `${v?.by} · ${v?.classification}\n${JSON.stringify(v?.bind ?? null)}\n${v?.reason || v?.explain || v?.question || ''}` }],
77
+ },
78
+ async execute(args) {
79
+ const res = await svc.parse({ text: String(args?.text || '') })
80
+ const v = res.value || {}
81
+ return { by: v.by || 'heuristic', classification: v.classification || 'process', bind: v.bind ?? {}, question: v.question || '', explain: v.reason || v.explain || '' }
82
+ },
83
+ })
84
+ const introspectTool = ctx.tools.register({
85
+ name: 'ruleset_introspect',
86
+ description: '让模型逐条说明规则审计的对象/触发/期望/例外,并给出可机械化的判据建议。',
87
+ parameters: {
88
+ id: { type: 'string', description: '只分析这条规则;省略则分析前 N 条' },
89
+ limit: { type: 'integer', description: '未给 id 时分析多少条,默认 3' },
90
+ },
91
+ output: {
92
+ schema: {
93
+ type: 'object',
94
+ additionalProperties: false,
95
+ required: ['summary'],
96
+ properties: { summary: { type: 'string' } },
97
+ },
98
+ render: (_a, v) => [{ type: 'text', text: String(v?.summary || '') }],
99
+ },
100
+ async execute(args) {
101
+ const res = await svc.introspect({ id: args?.id, limit: args?.limit })
102
+ const items = res.value?.items || []
103
+ const lines = []
104
+ for (const x of items) {
105
+ if (x.error) { lines.push(`${x.id}: 失败 ${x.error}`); continue }
106
+ lines.push(`${x.id}(${x.title || ''})`)
107
+ lines.push(` 对象=${x.object}|触发=${x.trigger}`)
108
+ lines.push(` 期望=${x.expectation}|例外=${x.exceptions || '无'}`)
109
+ lines.push(` 可机械化=${x.mechanical}${x.bind ? `|建议=${x.bind.type}` : ''}|${x.why}`)
110
+ }
111
+ return { summary: lines.join('\n') }
112
+ },
113
+ })
114
+ const playbookTool = ctx.tools.register({
115
+ name: 'ruleset_playbook',
116
+ description: '读取 dsh-ruleset 内置的「判据选用手册」:对象怎么定、正则怎么写、哪些规则不该硬编判据。',
117
+ parameters: {},
118
+ output: {
119
+ schema: { type: 'object', additionalProperties: false, required: ['text'], properties: { text: { type: 'string' } } },
120
+ render: (_a, v) => [{ type: 'text', text: String(v?.text || '') }],
121
+ },
122
+ async execute() {
123
+ try {
124
+ const here = path.dirname(fileURLToPath(import.meta.url))
125
+ return { text: fs.readFileSync(path.join(here, '..', 'docs', 'PREDICATE-PLAYBOOK.md'), 'utf8') }
126
+ } catch (e) {
127
+ return { text: '读取失败:' + (e?.message || String(e)) }
128
+ }
129
+ },
130
+ })
131
+ return () => { initTool?.(); reportTool?.(); parseTool?.(); introspectTool?.(); playbookTool?.() }
132
+ }
package/lib/policy.js ADDED
@@ -0,0 +1,57 @@
1
+ /** policy 读取(唯一真源)。解析失败返回 null → 调用方必须按 unknown 处理。 */
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
+
7
+ const require = createRequire(import.meta.url)
8
+ let yaml = null
9
+ try { yaml = require('js-yaml') } catch { yaml = null }
10
+
11
+ const candidates = (explicit) => [
12
+ explicit,
13
+ process.env.DSH_RULESET_POLICY || '',
14
+ path.join(process.env.HOME || '', '.dsh', 'workspace', 'policy.yaml'),
15
+ ].filter(Boolean)
16
+
17
+ export function loadPolicy(explicit) {
18
+ // 显式给了路径就不再回落:读不到/解析失败必须返回 null(unknown),
19
+ // 否则会静默用别人的 policy 顶上,判出完全不相干的结论。
20
+ if (explicit) {
21
+ try {
22
+ if (!fs.existsSync(explicit)) return null
23
+ const raw = fs.readFileSync(explicit, 'utf8')
24
+ const parsed = yaml?.load ? yaml.load(raw) : JSON.parse(raw)
25
+ const v = validatePolicy(parsed)
26
+ if (!v.ok) throw new Error(`policy 校验失败: ${v.errors.join('; ')}`)
27
+ return parsed
28
+ } catch { return null }
29
+ }
30
+ for (const p of candidates(explicit)) {
31
+ try {
32
+ if (!fs.existsSync(p)) continue
33
+ const raw = fs.readFileSync(p, 'utf8')
34
+ return yaml?.load ? yaml.load(raw) : JSON.parse(raw)
35
+ } catch { /* next */ }
36
+ }
37
+ return null
38
+ }
39
+
40
+ /** mtime 缓存:改 policy 不需要重启。读取失败回退到上次成功值。 */
41
+ export function watchPolicy(explicit) {
42
+ let cache = null
43
+ let stamp = -1
44
+ return {
45
+ get() {
46
+ const p = candidates(explicit).find((f) => { try { return fs.existsSync(f) } catch { return false } })
47
+ if (!p) return cache
48
+ let mt = 0
49
+ try { mt = fs.statSync(p).mtimeMs } catch { return cache }
50
+ if (mt !== stamp) {
51
+ const next = loadPolicy(p)
52
+ if (next) { cache = next; stamp = mt }
53
+ }
54
+ return cache
55
+ },
56
+ }
57
+ }