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.
- package/CHANGELOG.md +36 -0
- package/DEVELOPMENT.md +121 -0
- package/LICENSE +21 -0
- package/README.md +68 -2
- package/README.zh.md +131 -0
- package/client.js +822 -0
- package/cordis.patch.yml +10 -0
- package/docs/PREDICATE-PLAYBOOK.md +42 -0
- package/docs-schema.md +38 -0
- package/examples/policy.example.yaml +50 -0
- package/examples/policy.full.yaml +162 -0
- package/examples/policy.starter.yaml +65 -0
- package/lib/backups.js +77 -0
- package/lib/commands.js +38 -0
- package/lib/dedupe.js +22 -0
- package/lib/explain.js +28 -0
- package/lib/export.js +33 -0
- package/lib/extract.js +104 -0
- package/lib/facts.js +250 -0
- package/lib/findings.js +101 -0
- package/lib/guard.js +76 -0
- package/lib/history.js +71 -0
- package/lib/hygiene.js +86 -0
- package/lib/index.js +70 -0
- package/lib/init.js +29 -0
- package/lib/inject.js +64 -0
- package/lib/injected-log.js +30 -0
- package/lib/introspect.js +55 -0
- package/lib/judge.js +73 -0
- package/lib/llm-parse.js +131 -0
- package/lib/observe.js +132 -0
- package/lib/policy.js +57 -0
- package/lib/predicates.js +444 -0
- package/lib/report.js +66 -0
- package/lib/routes.js +62 -0
- package/lib/rules-edit.js +140 -0
- package/lib/run.js +109 -0
- package/lib/service.js +91 -0
- package/lib/source.js +93 -0
- package/lib/stats.js +63 -0
- package/lib/validate.js +73 -0
- package/locale/en.json +1 -0
- package/locale/zh.json +1 -0
- package/package.json +68 -3
- package/schema/policy.schema.json +41 -0
- package/test/dedupe.test.mjs +19 -0
- package/test/guard.test.mjs +30 -0
- package/test/load.test.mjs +21 -0
- package/test/predicates.test.mjs +49 -0
- package/test/source.test.mjs +32 -0
- package/test/validate.test.mjs +33 -0
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# dsh-ruleset bundle layer
|
|
2
|
+
# 单包两用:注入(systemPrompt 段)+ 观测(observe_report 工具),共用一份 policy。
|
|
3
|
+
- insert:
|
|
4
|
+
- id: dsh-ruleset
|
|
5
|
+
name: 'dsh-ruleset'
|
|
6
|
+
config:
|
|
7
|
+
policyPath: '' # 空 = 自动探测($DSH_RULESET_POLICY → ~/.dsh/workspace/policy.yaml)
|
|
8
|
+
guardEnabled: true
|
|
9
|
+
injectMode: off # compact | full | off(同时装 dsh-standards 时保持 off,避免重复注入)
|
|
10
|
+
windowHours: 720
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# 判据选用手册(开发经验沉淀)
|
|
2
|
+
|
|
3
|
+
> 这些是用真实误报换来的经验。写规则前先读一遍,能省掉大半返工。
|
|
4
|
+
|
|
5
|
+
## 一、先定对象,再选判据
|
|
6
|
+
|
|
7
|
+
1. 每条规则必须先回答:**审计对象是什么**——命令 / 文件写入 / 轮次 / 会话 / 记录文档
|
|
8
|
+
2. 对象要用 `pathPattern` + `excludePath` 收窄;不收窄就会命中 `AGENTS.md`、`README.md` 这类无关文件
|
|
9
|
+
3. 基数应当是「事件数」而非「全部文件数」:例如“记录五必录”的分母是**记录文件**,不是所有 .md
|
|
10
|
+
|
|
11
|
+
## 二、正则是最容易出事的一类
|
|
12
|
+
|
|
13
|
+
1. **不要用宽泛正则**:`来源|sources` 曾导致 195/195 全命中,全部误报
|
|
14
|
+
2. 匹配命令要**段首锚定**:`(?:^|[;&|]\s*)sudo\b`,不要裸写 `sudo`
|
|
15
|
+
3. 加上**引号感知**:`python3 -c "…sudo…"` 里的字样不算命令
|
|
16
|
+
4. JS 不支持 `(?s)`,需要跨行用 `[\s\S]`
|
|
17
|
+
|
|
18
|
+
## 三、能靠平台事实就别靠猜
|
|
19
|
+
|
|
20
|
+
1. "有没有审批"看 `approval/asked` + `approval/decided`,不要靠命令文本猜
|
|
21
|
+
2. "是不是子会话"看 `sandbox/mode.source === 'delegation'`
|
|
22
|
+
3. "后台跑了没"看 `job/registered` 与 `job/settled`
|
|
23
|
+
4. "长任务"用 `turn/start` 与 `turn/end` 的跨度,或调用次数
|
|
24
|
+
5. 红线类优先用 `approval-gated`,而不是 `regex`
|
|
25
|
+
|
|
26
|
+
## 四、语义规则不要硬编判据
|
|
27
|
+
|
|
28
|
+
1. “拿不准先问”“指不到证据不写结论”这类无法机械判定
|
|
29
|
+
2. 正确做法:保留为提示规则(状态永远 unknown),或让模型复核给出参考
|
|
30
|
+
3. 硬编判据只会产生假结论,比不判更糟
|
|
31
|
+
|
|
32
|
+
## 五、误报是长期成本
|
|
33
|
+
|
|
34
|
+
1. 发现要能标误报,且标记后从命中里扣减
|
|
35
|
+
2. 变化要与基线比较,`|z|<1.96` 说明无明显变化,不该飘红
|
|
36
|
+
3. 噪声大的规则降级为 `stat`,只统计不飘红
|
|
37
|
+
|
|
38
|
+
## 六、规则写了要有成本意识
|
|
39
|
+
|
|
40
|
+
1. 每条规则都会进提示词,长了就是成本,也会稀释注意力
|
|
41
|
+
2. 红线优先、硬约束次之、软规则最后;超过 20 条的规则集要开始考虑合并
|
|
42
|
+
3. 定期跑「规则体检」:重复、冲突、无判据、超长
|
package/docs-schema.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# policy schema
|
|
2
|
+
|
|
3
|
+
```yaml
|
|
4
|
+
version: 1
|
|
5
|
+
platform: { context_yellow_ratio: 0.4 }
|
|
6
|
+
rules:
|
|
7
|
+
- id: kebab-case-id # required, unique
|
|
8
|
+
kind: constraint|protocol # required
|
|
9
|
+
title: short label # required
|
|
10
|
+
text: one-line rule # required
|
|
11
|
+
mechanism: instruction|hook|tool
|
|
12
|
+
observe:
|
|
13
|
+
metric: name # required by convention
|
|
14
|
+
expect: 0
|
|
15
|
+
bind: # optional: makes the rule mechanically checkable
|
|
16
|
+
type: <predicate>
|
|
17
|
+
...predicate options
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Predicates
|
|
21
|
+
|
|
22
|
+
| type | options | verdict |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| `regex` | `sources` (`commands`/`fileWrites`), `pattern`, `target` (`cmd`/`content`/`path`), `skeleton`, `excludeLocalUrl`, `requireWrite`, `requireApproval`, `requireUserPermit` | 命中且无许可 → violation;扫描到样本 0 命中 → pass |
|
|
25
|
+
| `path-boundary` | `pattern`, `requireApproval`, `requireUserPermit` | 目标越出会话 cwd 且无审批 → violation |
|
|
26
|
+
| `field-presence` | `ext`, `fields`, `pathPattern`, `excludePath`, `legacyDays` | 文件缺字段 → violation;legacy 只统计不判定 |
|
|
27
|
+
| `sequence-order` | `taskPattern`, `first`, `then`, `minSamples` | 未先检索 → violation;样本不足 → unknown |
|
|
28
|
+
| `count-threshold` | `consecutiveFailures`, `minSamples` | 连续失败后仍重试 → violation |
|
|
29
|
+
| `requires` | `ifPathPattern`, `ifContentPattern` | 做了 X 无 Y → violation |
|
|
30
|
+
| `turn-condition` | `ifTurnCallMin`, `thenPattern` | 长任务无收尾动作 → violation |
|
|
31
|
+
| `duration` | `minMinutes` | 阻塞超阈值且未后台化 → violation |
|
|
32
|
+
| `metric` | `key`, `op`, `threshold` | 平台指标越界 → violation |
|
|
33
|
+
|
|
34
|
+
## Contract
|
|
35
|
+
|
|
36
|
+
- 没有 `bind` 的规则一律 `unknown`(语义规则就该承认判不了)
|
|
37
|
+
- `unknown` 不得读作 `pass`
|
|
38
|
+
- 每条 violation 必须能指回 `seq` 或文件路径
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
version: 1
|
|
2
|
+
rules:
|
|
3
|
+
- id: destructive-confirm
|
|
4
|
+
kind: constraint
|
|
5
|
+
title: 破坏性命令先确认
|
|
6
|
+
text: rm/diskutil/sudo 先说清并等确认;能用 trash 不用 rm
|
|
7
|
+
observe:
|
|
8
|
+
metric: destructive_blocked
|
|
9
|
+
expect: 0
|
|
10
|
+
bind:
|
|
11
|
+
type: path-boundary
|
|
12
|
+
pattern: '(?:^|[;&|(\n])\s*rm\s+-[rf]'
|
|
13
|
+
requireApproval: true
|
|
14
|
+
|
|
15
|
+
- id: credential-safety
|
|
16
|
+
kind: constraint
|
|
17
|
+
title: 凭据不落盘
|
|
18
|
+
text: 凭据不写入文件
|
|
19
|
+
observe:
|
|
20
|
+
metric: credential_leak
|
|
21
|
+
expect: 0
|
|
22
|
+
bind:
|
|
23
|
+
type: regex
|
|
24
|
+
source: fileWrites
|
|
25
|
+
target: content
|
|
26
|
+
pattern: 'sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}'
|
|
27
|
+
|
|
28
|
+
- id: stop-loss
|
|
29
|
+
kind: protocol
|
|
30
|
+
title: 同因失败即停
|
|
31
|
+
text: 同一命令连续两次同因失败即停
|
|
32
|
+
observe:
|
|
33
|
+
metric: repeat_failure
|
|
34
|
+
expect: 0
|
|
35
|
+
bind:
|
|
36
|
+
type: count-threshold
|
|
37
|
+
consecutiveFailures: 2
|
|
38
|
+
minSamples: 3
|
|
39
|
+
|
|
40
|
+
- id: deliverable-type
|
|
41
|
+
kind: protocol
|
|
42
|
+
title: 交付物首部声明 type
|
|
43
|
+
text: "交付物首部声明 type: 调研|排查|方案"
|
|
44
|
+
observe:
|
|
45
|
+
metric: deliverable_missing_field
|
|
46
|
+
expect: 0
|
|
47
|
+
bind:
|
|
48
|
+
type: field-presence
|
|
49
|
+
ext: .md
|
|
50
|
+
fields: [type]
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
version: 1
|
|
2
|
+
platform:
|
|
3
|
+
context_yellow_ratio: 0.4
|
|
4
|
+
rules:
|
|
5
|
+
- id: outbound-confirm
|
|
6
|
+
kind: constraint
|
|
7
|
+
title: 外发先问
|
|
8
|
+
text: 邮件/发帖/上传先确认
|
|
9
|
+
observe:
|
|
10
|
+
metric: outbound_blocked
|
|
11
|
+
bind:
|
|
12
|
+
type: regex
|
|
13
|
+
source: commands
|
|
14
|
+
skeleton: true
|
|
15
|
+
excludeLocalUrl: true
|
|
16
|
+
pattern: 'curl[^;|]*\s(?:-X\s*POST|--data|-d\s|--form|-F\s|--upload-file|-T\s)|git\s+push\b|(?:^|[;&|(\n]| )scp\s|\brsync\b[^;|]*@\S+:|(?:sendmail|mail\s+-s)\b'
|
|
17
|
+
requireApproval: true
|
|
18
|
+
requireUserPermit: '(?<!不)(?:可以|同意|发吧|发给我|发过来|发过去|上传|推送|好的|行|继续|装上|装吧)'
|
|
19
|
+
|
|
20
|
+
- id: destructive-confirm
|
|
21
|
+
kind: constraint
|
|
22
|
+
title: 破坏性命令先确认
|
|
23
|
+
text: rm/diskutil/sudo 先说清并等确认
|
|
24
|
+
observe:
|
|
25
|
+
metric: destructive_blocked
|
|
26
|
+
bind:
|
|
27
|
+
type: path-boundary
|
|
28
|
+
pattern: '(?:^|[;&|(\n])\s*rm\s+-[rf]'
|
|
29
|
+
requireApproval: true
|
|
30
|
+
requireUserPermit: '(?<!不)(?:可以|同意|都做|两件事|清理|清掉|删|归档)'
|
|
31
|
+
|
|
32
|
+
- id: credential-safety
|
|
33
|
+
kind: constraint
|
|
34
|
+
title: 凭据不落盘
|
|
35
|
+
text: 凭据不写入文件
|
|
36
|
+
observe:
|
|
37
|
+
metric: credential_leak
|
|
38
|
+
bind:
|
|
39
|
+
type: regex
|
|
40
|
+
sources: [fileWrites, commands]
|
|
41
|
+
pattern: 'sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|-----BEGIN (?:RSA |OPENSSH )?PRIVATE KEY-----'
|
|
42
|
+
requireWrite: true
|
|
43
|
+
|
|
44
|
+
- id: privacy-local
|
|
45
|
+
kind: constraint
|
|
46
|
+
title: 隐私不出机
|
|
47
|
+
text: 隐私数据绝不出本机
|
|
48
|
+
observe: { metric: privacy_egress }
|
|
49
|
+
|
|
50
|
+
- id: ask-when-unsure
|
|
51
|
+
kind: constraint
|
|
52
|
+
title: 拿不准先问
|
|
53
|
+
text: 拿不准时先问
|
|
54
|
+
observe: { metric: unasked_assumption }
|
|
55
|
+
|
|
56
|
+
- id: deliverable-type
|
|
57
|
+
kind: protocol
|
|
58
|
+
title: 交付物首部声明 type
|
|
59
|
+
text: "首部声明 type: 调研|排查|方案"
|
|
60
|
+
observe:
|
|
61
|
+
metric: deliverable_missing_field
|
|
62
|
+
bind:
|
|
63
|
+
type: field-presence
|
|
64
|
+
ext: .md
|
|
65
|
+
legacyDays: 7
|
|
66
|
+
excludePath: '(^|/)(\.archive|node_modules|scripts|notes|output)(/|$)|(^|/)(INDEX|README|AGENTS)\.md$'
|
|
67
|
+
fields: [type]
|
|
68
|
+
|
|
69
|
+
- id: search-first
|
|
70
|
+
kind: protocol
|
|
71
|
+
title: 排查先外部检索
|
|
72
|
+
text: 先查外部已知答案再碰本地
|
|
73
|
+
observe:
|
|
74
|
+
metric: audit_search_first_miss
|
|
75
|
+
bind:
|
|
76
|
+
type: sequence-order
|
|
77
|
+
taskPattern: '报错|错误|失败|为什么|排查|异常|崩|打不开|超时|error|fail|bug|timeout'
|
|
78
|
+
first: [web_search, web_fetch]
|
|
79
|
+
then: [read, grep, glob]
|
|
80
|
+
minSamples: 10
|
|
81
|
+
|
|
82
|
+
- id: evidence-before-conclusion
|
|
83
|
+
kind: protocol
|
|
84
|
+
title: 指不到证据不写结论
|
|
85
|
+
text: 结论必须能指回源码行号或原文
|
|
86
|
+
observe: { metric: conclusion_without_evidence }
|
|
87
|
+
|
|
88
|
+
- id: long-task-declaration
|
|
89
|
+
kind: protocol
|
|
90
|
+
title: 长任务先声明
|
|
91
|
+
text: 单轮≥12 次调用先发任务声明
|
|
92
|
+
observe: { metric: missing_declaration }
|
|
93
|
+
|
|
94
|
+
- id: task-close
|
|
95
|
+
kind: protocol
|
|
96
|
+
title: 收尾四步
|
|
97
|
+
text: 长任务结束前跑收尾命令/归档/查上下文/lint
|
|
98
|
+
observe:
|
|
99
|
+
metric: close_missed
|
|
100
|
+
bind:
|
|
101
|
+
type: turn-condition
|
|
102
|
+
ifTurnCallMin: 12
|
|
103
|
+
thenPattern: 'archive|归档|observe_report|session_projcache|context-watchdog|\blint\b'
|
|
104
|
+
|
|
105
|
+
- id: stop-loss
|
|
106
|
+
kind: protocol
|
|
107
|
+
title: 同因失败即停
|
|
108
|
+
text: 同一命令连续两次同因失败即停
|
|
109
|
+
observe:
|
|
110
|
+
metric: repeat_failure
|
|
111
|
+
bind:
|
|
112
|
+
type: count-threshold
|
|
113
|
+
consecutiveFailures: 2
|
|
114
|
+
minSamples: 3
|
|
115
|
+
|
|
116
|
+
- id: background-dispatch
|
|
117
|
+
kind: protocol
|
|
118
|
+
title: 长活后台化
|
|
119
|
+
text: 预计超 10-15 分钟后台化
|
|
120
|
+
observe:
|
|
121
|
+
metric: blocking_long_task
|
|
122
|
+
bind:
|
|
123
|
+
type: duration
|
|
124
|
+
minMinutes: 10
|
|
125
|
+
|
|
126
|
+
- id: review-grading
|
|
127
|
+
kind: protocol
|
|
128
|
+
title: 交付分级复核
|
|
129
|
+
text: 高风险交付加独立复核
|
|
130
|
+
observe:
|
|
131
|
+
metric: review_missing
|
|
132
|
+
bind:
|
|
133
|
+
type: requires
|
|
134
|
+
ifPathPattern: '评估|迁移|升级|报告|周报|PPT'
|
|
135
|
+
ifContentPattern: 'type\s*[::]\s*调研'
|
|
136
|
+
minSamples: 1
|
|
137
|
+
|
|
138
|
+
- id: context-rotation
|
|
139
|
+
kind: protocol
|
|
140
|
+
title: 上下文到线轮换
|
|
141
|
+
text: 占用≥40% 在任务边界轮换
|
|
142
|
+
observe:
|
|
143
|
+
metric: rotation_overdue
|
|
144
|
+
bind:
|
|
145
|
+
type: metric
|
|
146
|
+
key: context_ratio
|
|
147
|
+
op: '<='
|
|
148
|
+
threshold: 0.4
|
|
149
|
+
|
|
150
|
+
- id: record-completeness
|
|
151
|
+
kind: protocol
|
|
152
|
+
title: 记录五必录
|
|
153
|
+
text: 记录含测试前提/版本指纹/对象标识/判定依据/不确定项
|
|
154
|
+
observe:
|
|
155
|
+
metric: record_field_missing
|
|
156
|
+
bind:
|
|
157
|
+
type: field-presence
|
|
158
|
+
ext: .md
|
|
159
|
+
pathPattern: '/(notes|output)/'
|
|
160
|
+
legacyDays: 7
|
|
161
|
+
excludePath: '(^|/)(\.archive|node_modules|scripts)(/|$)|(^|/)(INDEX|README)\.md$'
|
|
162
|
+
fields: [测试前提, 版本指纹, 对象标识, 判定依据, 不确定项]
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# 起步包:只保留 5 条最常被违反、且能机械判定的规则。
|
|
2
|
+
# 复制到 ~/.dsh/workspace/policy.yaml 即可生效;不需要的先删。
|
|
3
|
+
version: 1
|
|
4
|
+
rules:
|
|
5
|
+
- id: destructive-confirm
|
|
6
|
+
kind: constraint
|
|
7
|
+
title: Confirm destructive commands outside the workspace
|
|
8
|
+
text: rm/diskutil/sudo outside the session workspace must be stated and approved first.
|
|
9
|
+
observe:
|
|
10
|
+
metric: destructive_blocked
|
|
11
|
+
bind:
|
|
12
|
+
type: path-boundary
|
|
13
|
+
pattern: '(?:^|[;&|(\n])\s*rm\s+-[rf]'
|
|
14
|
+
requireApproval: true
|
|
15
|
+
requireUserPermit: '(?<!不)(?:可以|同意|都做|清理|清掉|删|归档)'
|
|
16
|
+
|
|
17
|
+
- id: credential-safety
|
|
18
|
+
kind: constraint
|
|
19
|
+
title: Never persist credentials
|
|
20
|
+
text: API keys and tokens must not be written into files or commands.
|
|
21
|
+
observe:
|
|
22
|
+
metric: credential_leak
|
|
23
|
+
bind:
|
|
24
|
+
type: regex
|
|
25
|
+
sources: [fileWrites, commands]
|
|
26
|
+
pattern: 'sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|-----BEGIN (?:RSA |OPENSSH )?PRIVATE KEY-----'
|
|
27
|
+
requireWrite: true
|
|
28
|
+
|
|
29
|
+
- id: outbound-confirm
|
|
30
|
+
kind: constraint
|
|
31
|
+
title: Ask before anything leaves the machine
|
|
32
|
+
text: Uploads, pushes, emails and posts require explicit user approval.
|
|
33
|
+
observe:
|
|
34
|
+
metric: outbound_blocked
|
|
35
|
+
bind:
|
|
36
|
+
type: regex
|
|
37
|
+
source: commands
|
|
38
|
+
skeleton: true
|
|
39
|
+
excludeLocalUrl: true
|
|
40
|
+
pattern: 'curl[^;|]*\s(?:-X\s*POST|--data|-d\s|--form|-F\s|--upload-file|-T\s)|git\s+push\b|\bscp\s|\brsync\b[^;|]*@\S+:|(?:sendmail|mail\s+-s)\b'
|
|
41
|
+
requireApproval: true
|
|
42
|
+
requireUserPermit: '(?<!不)(?:可以|同意|发吧|发给我|上传|推送|好的|行|继续)'
|
|
43
|
+
|
|
44
|
+
- id: stop-loss
|
|
45
|
+
kind: protocol
|
|
46
|
+
title: Stop after two identical failures
|
|
47
|
+
text: Two consecutive failures of the same command means change the route.
|
|
48
|
+
observe:
|
|
49
|
+
metric: repeat_failure
|
|
50
|
+
bind:
|
|
51
|
+
type: count-threshold
|
|
52
|
+
consecutiveFailures: 2
|
|
53
|
+
minSamples: 3
|
|
54
|
+
|
|
55
|
+
- id: context-rotation
|
|
56
|
+
kind: protocol
|
|
57
|
+
title: Rotate before context pressure gets high
|
|
58
|
+
text: Above 40% context usage, rotate at a task boundary.
|
|
59
|
+
observe:
|
|
60
|
+
metric: rotation_overdue
|
|
61
|
+
bind:
|
|
62
|
+
type: metric
|
|
63
|
+
key: context_ratio
|
|
64
|
+
op: '<='
|
|
65
|
+
threshold: 0.4
|
package/lib/backups.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** 用户文件备份与回滚:policy.yaml 每次写入前留快照,可一键还原。 */
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
const root = () => path.join(process.env.HOME || '', '.dsh', 'workspace', '.ruleset', 'backups')
|
|
6
|
+
const indexFile = () => path.join(root(), 'index.json')
|
|
7
|
+
export const policyPath = () => path.join(process.env.HOME || '', '.dsh', 'workspace', 'policy.yaml')
|
|
8
|
+
|
|
9
|
+
function readIndex() {
|
|
10
|
+
try { return JSON.parse(fs.readFileSync(indexFile(), 'utf8')) } catch { return [] }
|
|
11
|
+
}
|
|
12
|
+
function writeIndex(list) {
|
|
13
|
+
try {
|
|
14
|
+
fs.mkdirSync(root(), { recursive: true })
|
|
15
|
+
fs.writeFileSync(indexFile(), JSON.stringify(list.slice(-50), null, 2))
|
|
16
|
+
} catch { /* ignore */ }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function listBackups() {
|
|
20
|
+
return readIndex().slice().reverse()
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 写入前调用:返回备份条目(失败不阻断写入,但要记录原因)。 */
|
|
24
|
+
export function backupPolicy(action = 'write') {
|
|
25
|
+
try {
|
|
26
|
+
const src = policyPath()
|
|
27
|
+
if (!fs.existsSync(src)) return { ok: true, skipped: 'no-policy' }
|
|
28
|
+
fs.mkdirSync(root(), { recursive: true })
|
|
29
|
+
const ts = new Date().toISOString().replace(/[:.]/g, '-')
|
|
30
|
+
const name = `policy-${ts}.yaml`
|
|
31
|
+
fs.copyFileSync(src, path.join(root(), name))
|
|
32
|
+
const item = { ts, file: name, action, bytes: fs.statSync(src).size }
|
|
33
|
+
const list = readIndex()
|
|
34
|
+
list.push(item)
|
|
35
|
+
writeIndex(list)
|
|
36
|
+
return { ok: true, item }
|
|
37
|
+
} catch (e) {
|
|
38
|
+
return { ok: false, error: e?.message || String(e) }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function restoreBackup(name) {
|
|
43
|
+
const list = readIndex()
|
|
44
|
+
const item = list.find((x) => x.file === name || x.ts === name)
|
|
45
|
+
if (!item) return { ok: false, error: '没有这个备份' }
|
|
46
|
+
const from = path.join(root(), item.file)
|
|
47
|
+
if (!fs.existsSync(from)) return { ok: false, error: '备份文件已不存在' }
|
|
48
|
+
try {
|
|
49
|
+
// 回滚前再留一份,避免回滚本身不可逆
|
|
50
|
+
backupPolicy('pre-restore')
|
|
51
|
+
fs.copyFileSync(from, policyPath())
|
|
52
|
+
return { ok: true, restored: item.file }
|
|
53
|
+
} catch (e) {
|
|
54
|
+
return { ok: false, error: e?.message || String(e) }
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 卸载前导出:把当前 policy 与 AGENTS.md 复制到用户可保留的位置。 */
|
|
59
|
+
export function exportForKeep(dir) {
|
|
60
|
+
try {
|
|
61
|
+
const out = dir || path.join(process.env.HOME || '', '.dsh', 'workspace', '.ruleset', 'export')
|
|
62
|
+
fs.mkdirSync(out, { recursive: true })
|
|
63
|
+
const copied = []
|
|
64
|
+
if (fs.existsSync(policyPath())) {
|
|
65
|
+
fs.copyFileSync(policyPath(), path.join(out, 'policy.yaml'))
|
|
66
|
+
copied.push('policy.yaml')
|
|
67
|
+
}
|
|
68
|
+
const agents = path.join(process.env.HOME || '', '.dsh', 'workspace', 'AGENTS.md')
|
|
69
|
+
if (fs.existsSync(agents)) {
|
|
70
|
+
fs.copyFileSync(agents, path.join(out, 'AGENTS.md'))
|
|
71
|
+
copied.push('AGENTS.md')
|
|
72
|
+
}
|
|
73
|
+
return { ok: true, dir: out, copied }
|
|
74
|
+
} catch (e) {
|
|
75
|
+
return { ok: false, error: e?.message || String(e) }
|
|
76
|
+
}
|
|
77
|
+
}
|
package/lib/commands.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 宿主命令通道:`/ruleset <json>` —— UI 在没有 HTTP 路由的环境(桌面端)下走这里。
|
|
3
|
+
* 只做分发,实现在 service.js。
|
|
4
|
+
*/
|
|
5
|
+
import { createService } from './service.js'
|
|
6
|
+
|
|
7
|
+
export function registerCommands(ctx) {
|
|
8
|
+
if (typeof ctx?.inject !== 'function') return () => {}
|
|
9
|
+
let dispose = () => {}
|
|
10
|
+
const sub = ctx.inject(['commands'], (scope) => {
|
|
11
|
+
const commands = scope.get?.('commands')
|
|
12
|
+
if (!commands?.register) return
|
|
13
|
+
const svc = createService(ctx)
|
|
14
|
+
const off = commands.register({
|
|
15
|
+
definitionId: 'dsh-ruleset:dispatch',
|
|
16
|
+
name: 'ruleset',
|
|
17
|
+
description: 'ruleset 内部通道:/ruleset {"op":"report","args":{...}}',
|
|
18
|
+
recordInput: false,
|
|
19
|
+
input: { hint: '{"op":"report","args":{}}' },
|
|
20
|
+
handler: async (invocation) => {
|
|
21
|
+
const raw = String(invocation?.rawInput || '').trim()
|
|
22
|
+
let req = null
|
|
23
|
+
try { req = JSON.parse(raw) } catch { return { kind: 'error', text: 'invalid JSON: ' + raw.slice(0, 80) } }
|
|
24
|
+
const op = String(req?.op || '')
|
|
25
|
+
const fn = svc[op]
|
|
26
|
+
if (typeof fn !== 'function') return { kind: 'error', text: 'unknown op: ' + op }
|
|
27
|
+
try {
|
|
28
|
+
const out = await fn(req.args || {})
|
|
29
|
+
return { kind: 'success', text: JSON.stringify(out) }
|
|
30
|
+
} catch (e) {
|
|
31
|
+
return { kind: 'error', text: 'op failed: ' + (e?.message || String(e)) }
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
})
|
|
35
|
+
dispose = typeof off === 'function' ? off : () => {}
|
|
36
|
+
})
|
|
37
|
+
return () => { dispose(); sub?.() }
|
|
38
|
+
}
|
package/lib/dedupe.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 注入去重:DSH 本身会注入工作区 AGENTS.md。
|
|
3
|
+
* 规则文本若已经出现在 AGENTS.md 里,就不再重复注入(但照常参与判定)。
|
|
4
|
+
* 只读,不写任何用户文件 —— 拔掉插件后 prompt 与 AGENTS.md 原样。
|
|
5
|
+
*/
|
|
6
|
+
const norm = (s) => String(s || '')
|
|
7
|
+
.replace(/[`*_#>]/g, '')
|
|
8
|
+
.replace(/\s+/g, '')
|
|
9
|
+
.toLowerCase()
|
|
10
|
+
|
|
11
|
+
export function dedupeRules(rules, agentsText) {
|
|
12
|
+
const hay = norm(agentsText)
|
|
13
|
+
if (!hay) return { kept: rules, skipped: [] }
|
|
14
|
+
const kept = []
|
|
15
|
+
const skipped = []
|
|
16
|
+
for (const r of rules) {
|
|
17
|
+
const probe = norm(r.text).slice(0, 40)
|
|
18
|
+
if (probe && hay.includes(probe)) skipped.push(r)
|
|
19
|
+
else kept.push(r)
|
|
20
|
+
}
|
|
21
|
+
return { kept, skipped }
|
|
22
|
+
}
|
package/lib/explain.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** 把判据参数翻译成一句人话,给非程序员看。 */
|
|
2
|
+
export function explainBind(bind) {
|
|
3
|
+
if (!bind || !bind.type) return '这条规则没有机械判据,只会作为提示注入,不参与判定。'
|
|
4
|
+
switch (bind.type) {
|
|
5
|
+
case 'explain-first':
|
|
6
|
+
return '检查每一轮里,第一次调用工具之前有没有先写解释/计划;没有就算违规。'
|
|
7
|
+
case 'path-boundary':
|
|
8
|
+
return `检查命令里是否出现「${bind.pattern || 'rm -rf'}」并且删的是工作区外的路径${bind.exemptPaths?.length ? `(已豁免:${bind.exemptPaths.join('、')})` : ''},且没有先征求同意。`
|
|
9
|
+
case 'field-presence':
|
|
10
|
+
return `检查${bind.ext || '.md'}文件里是否同时出现这些字段:${(bind.fields || []).join('、') || '(未填写)'};缺一即违规。`
|
|
11
|
+
case 'count-threshold':
|
|
12
|
+
return `同一条命令连续失败 ${bind.consecutiveFailures ?? 2} 次后仍在重试,就算违规。`
|
|
13
|
+
case 'turn-condition':
|
|
14
|
+
return `当一轮里调用工具超过 ${bind.ifTurnCallMin ?? 12} 次(算长任务)时,必须出现「${bind.thenPattern || '(未填写)'}」这个动作,否则违规。`
|
|
15
|
+
case 'sequence-order':
|
|
16
|
+
return `对匹配「${bind.taskPattern || '(未填写)'}」的任务,前面必须先有 ${(bind.first || []).join('/')},之后才允许 ${(bind.then || []).join('/')};样本少于 ${bind.minSamples ?? 10} 条时不判定。`
|
|
17
|
+
case 'requires':
|
|
18
|
+
return `当内容匹配「${bind.ifPathPattern || bind.ifContentPattern || '(未填写)'}」时,必须同时出现规定的伴随动作,否则违规。`
|
|
19
|
+
case 'duration':
|
|
20
|
+
return `单次调用阻塞超过 ${bind.minMinutes ?? 10} 分钟且没有转后台,就算违规。`
|
|
21
|
+
case 'metric':
|
|
22
|
+
return `平台指标 ${bind.key || 'context_ratio'} 必须 ${bind.op || '<='} ${bind.threshold ?? 0.4}${bind.key === 'context_ratio' ? `(即 ${Math.round((bind.threshold ?? 0.4) * 100)}%)` : ''},超过就违规。`
|
|
23
|
+
case 'regex':
|
|
24
|
+
return `在${(bind.sources || ['commands']).includes('fileWrites') ? '写入的内容' : '命令'}里匹配「${bind.pattern || '(未填写)'}」时算命中。`
|
|
25
|
+
default:
|
|
26
|
+
return `判据 ${bind.type}(暂无白话说明)。`
|
|
27
|
+
}
|
|
28
|
+
}
|
package/lib/export.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 互操作:把 DSH 事实流导出成通用事件日志(JSONL),
|
|
3
|
+
* 供 agent-rule-enforcement 的 audit_events.py 之类的离线审计器消费。
|
|
4
|
+
*
|
|
5
|
+
* 事件字段:ts(ISO) / session / tool / ok / duration_ms / checkpoint / outcome / user_visible / claims
|
|
6
|
+
* 我们只填有把握的:checkpoint 用「轮内是否出现过收尾动作」近似,claims 留空(不猜)。
|
|
7
|
+
*/
|
|
8
|
+
export function exportEvents(facts) {
|
|
9
|
+
const lines = []
|
|
10
|
+
const bySeq = new Map((facts.commands || []).map((c) => [c.seq, c]))
|
|
11
|
+
for (const t of facts.turns) {
|
|
12
|
+
const calls = t.calls || []
|
|
13
|
+
const tail = calls.slice(-3).map((c) => `${c.name} ${String(c.args?.command || c.args?.file_path || '')}`).join(' ')
|
|
14
|
+
const checkpoint = /archive|归档|observe_report|session_projcache|\blint\b/.test(tail)
|
|
15
|
+
if (calls.length === 0) continue
|
|
16
|
+
for (const c of calls) {
|
|
17
|
+
const cmd = bySeq.get(c.seq)
|
|
18
|
+
const started = cmd?.startedAt || t.startTime || Date.now()
|
|
19
|
+
const ended = cmd?.endAt && cmd.endAt > started ? cmd.endAt : started
|
|
20
|
+
lines.push(JSON.stringify({
|
|
21
|
+
ts: new Date(started).toISOString(),
|
|
22
|
+
session: t.session,
|
|
23
|
+
tool: c.name,
|
|
24
|
+
ok: !(cmd?.isError === true),
|
|
25
|
+
duration_ms: ended - started,
|
|
26
|
+
checkpoint,
|
|
27
|
+
outcome: 'ok',
|
|
28
|
+
user_visible: false,
|
|
29
|
+
}))
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return lines.join('\n')
|
|
33
|
+
}
|
package/lib/extract.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 从 AGENTS.md 抽取候选规则(draft),按「可执行性三档」分类:
|
|
3
|
+
* 产物要求 > 过程要求 > 态度要求
|
|
4
|
+
* 输出永远是 draft:每条带原文行号与分类,必须人工确认后才进 policy。
|
|
5
|
+
*/
|
|
6
|
+
const FORCE = /必须|不得|禁止|严禁|一律|不允许|只能/
|
|
7
|
+
const FIELDish = /必须包含|首部|字段|章节|模板/
|
|
8
|
+
const COUNTish = /\d+\s*(?:次|分钟|秒|行|字符|%|条|轮)/
|
|
9
|
+
const CMDish = /`[^`]*(?:scripts?\/|\.sh|\.py|\.mjs)[^`]*`|跑\s*`|执行\s*`/
|
|
10
|
+
const SEMANTICish = /拿不准|先问|判断|思考|觉得|态度|原则|尽量|优先/
|
|
11
|
+
|
|
12
|
+
const slug = (line, i) => `agents-l${line}-${i}`
|
|
13
|
+
|
|
14
|
+
/** 解析一句规则描述 → 分类 + 建议判据(抽取器与面板共用同一套口径)。 */
|
|
15
|
+
export function parseSentence(line) {
|
|
16
|
+
const t = String(line || '').trim()
|
|
17
|
+
if (!t) return { classification: 'empty', bind: null }
|
|
18
|
+
const fields = (t.match(/「([^」]{1,20})」/g) || []).map((s) => s.slice(1, -1))
|
|
19
|
+
let classification = 'process'
|
|
20
|
+
let bind = null
|
|
21
|
+
if (FIELDish.test(t)) {
|
|
22
|
+
classification = 'field'
|
|
23
|
+
bind = fields.length
|
|
24
|
+
? { type: 'field-presence', ext: '.md', fields }
|
|
25
|
+
: { type: 'field-presence', ext: '.md', fields: ['type'] }
|
|
26
|
+
} else if (/删除|rm\b|清空/.test(t)) {
|
|
27
|
+
classification = 'path'
|
|
28
|
+
bind = { type: 'path-boundary', pattern: 'rm\\s+-rf', requireApproval: true }
|
|
29
|
+
} else if (COUNTish.test(t)) {
|
|
30
|
+
classification = 'count'
|
|
31
|
+
const times = t.match(/(\d+)\s*次/)
|
|
32
|
+
const mins = t.match(/(\d+)\s*分钟/)
|
|
33
|
+
const pct = t.match(/(\d+(?:\.\d+)?)\s*%/)
|
|
34
|
+
const perTurn = /单轮|每轮|一轮|轮内/.test(t)
|
|
35
|
+
if (times && perTurn) bind = { type: 'turn-condition', ifTurnCallMin: Number(times[1]), thenPattern: 'observe_report|archive|归档|lint' }
|
|
36
|
+
else if (times) bind = { type: 'count-threshold', consecutiveFailures: Number(times[1]) }
|
|
37
|
+
else if (mins) bind = { type: 'duration', minMinutes: Number(mins[1]) }
|
|
38
|
+
else if (pct) bind = { type: 'metric', key: 'context_ratio', op: '<=', threshold: Number(pct[1]) / 100 }
|
|
39
|
+
} else if (/先查|先搜|先看外部|外部检索|检索|类似实例|类似案例|借鉴|闭门造车/.test(t)) {
|
|
40
|
+
classification = 'search-first'
|
|
41
|
+
bind = {
|
|
42
|
+
type: 'sequence-order',
|
|
43
|
+
taskPattern: '报错|错误|失败|为什么|排查|异常|崩|打不开|超时|error|fail|bug|debug|开发|实现',
|
|
44
|
+
first: ['web_search', 'web_fetch'],
|
|
45
|
+
then: ['read', 'grep', 'glob'],
|
|
46
|
+
minSamples: 10,
|
|
47
|
+
}
|
|
48
|
+
} else if (/先[^。;]{0,12}(解释|说明|讲清|告知)/.test(t) || /(解释|说明)[^。;]{0,12}(原因|计划|方案|思路)/.test(t)) {
|
|
49
|
+
classification = 'explain-first'
|
|
50
|
+
bind = { type: 'explain-first' }
|
|
51
|
+
} else if (/外发|上传|推送|发帖|邮件/.test(t)) {
|
|
52
|
+
classification = 'outbound'
|
|
53
|
+
bind = { type: 'regex', sources: ['commands'], pattern: 'git\\s+push|curl[^;|]*(-X\\s+POST|--data)|(?:sendmail|mail\\s+-s)', requireApproval: true }
|
|
54
|
+
} else if (CMDish.test(t)) {
|
|
55
|
+
classification = 'artifact'
|
|
56
|
+
} else if (SEMANTICish.test(t)) {
|
|
57
|
+
classification = 'semantic'
|
|
58
|
+
}
|
|
59
|
+
return { classification, bind, text: t }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function extractFromAgents(text, file = 'AGENTS.md') {
|
|
63
|
+
const lines = String(text).split('\n')
|
|
64
|
+
const cands = []
|
|
65
|
+
lines.forEach((raw, idx) => {
|
|
66
|
+
const line = raw.trim()
|
|
67
|
+
if (!line || !FORCE.test(line)) return
|
|
68
|
+
if (/^[-*]\s*\[[ x]\]/.test(line)) return // 复选框不算规则正文
|
|
69
|
+
const n = idx + 1
|
|
70
|
+
let cls = 'process' // 过程要求:可检测但需人工确认怎么测
|
|
71
|
+
let bind = null
|
|
72
|
+
const fields = (line.match(/「([^」]{1,20})」/g) || []).map((s) => s.slice(1, -1))
|
|
73
|
+
if (FIELDish.test(line)) {
|
|
74
|
+
cls = 'field'
|
|
75
|
+
bind = fields.length
|
|
76
|
+
? { type: 'field-presence', ext: '.md', fields }
|
|
77
|
+
: { type: 'field-presence', ext: '.md', fields: ['type'] }
|
|
78
|
+
} else if (COUNTish.test(line)) {
|
|
79
|
+
cls = 'count'
|
|
80
|
+
const times = line.match(/(\d+)\s*次/)
|
|
81
|
+
const mins = line.match(/(\d+)\s*分钟/)
|
|
82
|
+
if (times) bind = { type: 'turn-condition', ifTurnCallMin: Number(times[1]), thenPattern: 'observe_report|archive|归档|lint' }
|
|
83
|
+
else if (mins) bind = { type: 'duration', minMinutes: Number(mins[1]) }
|
|
84
|
+
} else if (CMDish.test(line)) {
|
|
85
|
+
cls = 'artifact'
|
|
86
|
+
} else if (SEMANTICish.test(line)) {
|
|
87
|
+
cls = 'semantic'
|
|
88
|
+
}
|
|
89
|
+
cands.push({
|
|
90
|
+
id: slug(n, cands.length),
|
|
91
|
+
kind: 'protocol',
|
|
92
|
+
title: line.replace(/^#+\s*/, '').slice(0, 40),
|
|
93
|
+
text: line.replace(/\s+/g, ' ').slice(0, 200),
|
|
94
|
+
observe: { metric: `agents_l${n}`, proposed: true },
|
|
95
|
+
draft: { classification: cls, suggestedBind: bind, source: `${file}:${n}` },
|
|
96
|
+
})
|
|
97
|
+
})
|
|
98
|
+
return {
|
|
99
|
+
file,
|
|
100
|
+
total: cands.length,
|
|
101
|
+
byClass: cands.reduce((acc, c) => { acc[c.draft.classification] = (acc[c.draft.classification] || 0) + 1; return acc }, {}),
|
|
102
|
+
rules: cands,
|
|
103
|
+
}
|
|
104
|
+
}
|