@twinsearth/dsh-fang 3.1.21 → 3.1.22

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 (113) hide show
  1. package/LICENSES/LICENSES/cordis-MIT.txt +39 -0
  2. package/client.js +197 -3
  3. package/defaults/defaults/umbrella-rules.yaml +113 -0
  4. package/package.json +2 -2
  5. package/sdk/sdk/README.md +65 -0
  6. package/sdk/sdk/examples/status-badge/README.md +16 -0
  7. package/sdk/sdk/examples/status-badge/client.js +60 -0
  8. package/sdk/sdk/examples/status-badge/cordis.patch.yml +7 -0
  9. package/sdk/sdk/examples/status-badge/index.js +12 -0
  10. package/sdk/sdk/examples/status-badge/package.json +24 -0
  11. package/sdk/sdk/templates/plugin/README.md +36 -0
  12. package/sdk/sdk/templates/plugin/client.js +35 -0
  13. package/sdk/sdk/templates/plugin/cordis.patch.yml +8 -0
  14. package/sdk/sdk/templates/plugin/icon.svg +5 -0
  15. package/sdk/sdk/templates/plugin/index.js +23 -0
  16. package/sdk/sdk/templates/plugin/locale/en.json +6 -0
  17. package/sdk/sdk/templates/plugin/package.json +36 -0
  18. package/src/kernel/types.mjs +1 -1
  19. package/src/src/compose.mjs +67 -0
  20. package/src/src/contract/client.js +86 -0
  21. package/src/src/contract/constants.js +79 -0
  22. package/src/src/contract/envelope.js +83 -0
  23. package/src/src/contract/index.js +19 -0
  24. package/src/src/contract/negotiate.js +106 -0
  25. package/src/src/contract/server.js +77 -0
  26. package/src/src/contract/transports.js +301 -0
  27. package/src/src/index.mjs +11 -0
  28. package/src/src/kernel/core.mjs +100 -0
  29. package/src/src/kernel/extensions.mjs +61 -0
  30. package/src/src/kernel/fsx.mjs +349 -0
  31. package/src/src/kernel/index.mjs +21 -0
  32. package/src/src/kernel/ledger.mjs +94 -0
  33. package/src/src/kernel/paths.mjs +182 -0
  34. package/src/src/kernel/role.mjs +68 -0
  35. package/src/src/kernel/rounds.mjs +172 -0
  36. package/src/src/kernel/schema.mjs +5 -0
  37. package/src/src/kernel/types.mjs +264 -0
  38. package/src/src/kernel/vendor/cosmokit.mjs +421 -0
  39. package/src/src/kernel/vendor/schemastery.mjs +638 -0
  40. package/src/src/lib/adapter-client.mjs +383 -0
  41. package/src/src/lib/adapter-protocol.mjs +243 -0
  42. package/src/src/lib/ai-secret-store.mjs +202 -0
  43. package/src/src/lib/boot-guard.mjs +182 -0
  44. package/src/src/lib/branch-store.mjs +84 -0
  45. package/src/src/lib/branch.mjs +74 -0
  46. package/src/src/lib/bridge-client.mjs +133 -0
  47. package/src/src/lib/broker-adapter.mjs +67 -0
  48. package/src/src/lib/broker.mjs +45 -0
  49. package/src/src/lib/business-producers.mjs +109 -0
  50. package/src/src/lib/command-cache.mjs +209 -0
  51. package/src/src/lib/compat.mjs +170 -0
  52. package/src/src/lib/composer-journal.mjs +128 -0
  53. package/src/src/lib/container/index.mjs +806 -0
  54. package/src/src/lib/decision-events.mjs +129 -0
  55. package/src/src/lib/decision-ingest-client.mjs +41 -0
  56. package/src/src/lib/decision-outbox.mjs +129 -0
  57. package/src/src/lib/default-essence.mjs +61 -0
  58. package/src/src/lib/desktop-launch.mjs +138 -0
  59. package/src/src/lib/essence.mjs +1211 -0
  60. package/src/src/lib/fork-client.mjs +410 -0
  61. package/src/src/lib/fork-config-lock.mjs +153 -0
  62. package/src/src/lib/fork-seed.mjs +304 -0
  63. package/src/src/lib/fork-supervision-settings.mjs +58 -0
  64. package/src/src/lib/fork-supervisor.mjs +122 -0
  65. package/src/src/lib/fs-guard.mjs +28 -0
  66. package/src/src/lib/http-auth.mjs +162 -0
  67. package/src/src/lib/idle-audit.mjs +178 -0
  68. package/src/src/lib/interaction-poke.mjs +61 -0
  69. package/src/src/lib/mirror-etag.mjs +92 -0
  70. package/src/src/lib/mirror-official-source.mjs +93 -0
  71. package/src/src/lib/mirror.mjs +478 -0
  72. package/src/src/lib/mother-link.mjs +156 -0
  73. package/src/src/lib/mutex.mjs +31 -0
  74. package/src/src/lib/permissions.mjs +115 -0
  75. package/src/src/lib/pnpm-store.mjs +189 -0
  76. package/src/src/lib/preferences.mjs +212 -0
  77. package/src/src/lib/producer-contract.mjs +162 -0
  78. package/src/src/lib/reflow.mjs +41 -0
  79. package/src/src/lib/remote.mjs +408 -0
  80. package/src/src/lib/restart-contract.mjs +650 -0
  81. package/src/src/lib/roots.mjs +30 -0
  82. package/src/src/lib/rule-registry.mjs +1101 -0
  83. package/src/src/lib/runtime-capture.mjs +307 -0
  84. package/src/src/lib/semaphore.mjs +34 -0
  85. package/src/src/lib/session-bundle.mjs +138 -0
  86. package/src/src/lib/session-format.mjs +658 -0
  87. package/src/src/lib/sse-parser.mjs +102 -0
  88. package/src/src/lib/ssrf-guard.mjs +170 -0
  89. package/src/src/lib/status-store.mjs +257 -0
  90. package/src/src/lib/task-handle.mjs +622 -0
  91. package/src/src/lib/ui-actions.mjs +55 -0
  92. package/src/src/lib/umbrella.mjs +1661 -0
  93. package/src/src/lib/upgrade-coordinator.mjs +107 -0
  94. package/src/src/lib/upgrade-status.mjs +43 -0
  95. package/src/src/plugins/adapter.mjs +1468 -0
  96. package/src/src/plugins/approver.mjs +1210 -0
  97. package/src/src/plugins/auditor.mjs +330 -0
  98. package/src/src/plugins/buffer-keeper.mjs +522 -0
  99. package/src/src/plugins/decision-center.mjs +2265 -0
  100. package/src/src/plugins/forker.mjs +1594 -0
  101. package/src/src/plugins/healer.mjs +664 -0
  102. package/src/src/plugins/hot-reloader.mjs +274 -0
  103. package/src/src/plugins/imports.mjs +247 -0
  104. package/src/src/plugins/orchestrator.mjs +3806 -0
  105. package/src/src/plugins/restart-guard.mjs +948 -0
  106. package/src/src/plugins/router.mjs +714 -0
  107. package/src/src/plugins/scorer.mjs +624 -0
  108. package/src/src/plugins/session-bridge.mjs +166 -0
  109. package/src/src/plugins/session-catalog.mjs +771 -0
  110. package/src/src/plugins/session-router.mjs +125 -0
  111. package/src/src/plugins/session-sync.mjs +171 -0
  112. package/src/src/plugins/umbrella.mjs +419 -0
  113. package/tools/recover-queue.mjs +133 -0
@@ -0,0 +1,1101 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // dsh-Fang v2.8.0 — 可配置的动作规则表(YAML 叠加层)。
5
+ //
6
+ // 约束:本仓库零第三方运行时依赖(CI 与 profile 安装都依赖这一点),所以这里手写
7
+ // * YAML **子集**解析器(块映射 / 序列 / 引号标量 / 简单 flow 列表 / 注释;不做锚点、多文档、块标量)
8
+ // * 配置 schema 校验(手写,错误逐条给出)
9
+ // * 声明式 matcher/evidence 编译器(只允许内置 kind,不能写任意 JS)
10
+ // * RuleRegistry(内置规则 + YAML 叠加,事务化应用)
11
+ // * 文件加载 + fs.watch 热加载(失败保留旧规则)
12
+ //
13
+ // 设计边界(刻意的):
14
+ // YAML 是「配置」不是「脚本」。match 是任意 JS 谓词,不可能安全地塞进 YAML;
15
+ // 因此 YAML 只能 (a) 开关内置规则、(b) 覆盖 light/priority/reason/tags/category、
16
+ // (c) 给内置规则追加正则、(d) 用内置声明式 matcher 新增简单规则。
17
+ // 复杂谓词仍然写在代码里,用 id 引用。
18
+
19
+ import fs from 'node:fs'
20
+ import path from 'node:path'
21
+ import { ACTION_CATEGORIES, assertActionRule, DEFAULT_ACTION_RULES } from './umbrella.mjs'
22
+ import { LIGHT_RANK } from '../kernel/index.mjs'
23
+
24
+ /** 内置规则的默认优先级(越小越先匹配;同优先级按内置顺序)。 */
25
+ export const DEFAULT_RULE_PRIORITIES = Object.freeze({
26
+ 'dsh-lifecycle': 10,
27
+ 'destructive-command': 20,
28
+ 'credential-access': 30,
29
+ 'network-allowlisted': 40,
30
+ 'network-egress': 50,
31
+ 'dynamic-import': 60,
32
+ 'write-in-buffer': 70,
33
+ 'write-in-allowlist': 80,
34
+ 'write-production': 90,
35
+ 'write-outside-buffer': 100,
36
+ 'exec-read-only': 110,
37
+ 'exec-side-effect': 120,
38
+ 'read-in-buffer': 130,
39
+ 'read-outside-buffer': 140,
40
+ 'unknown-tool': 9999,
41
+ })
42
+
43
+ export const RULE_CONFIG_VERSION = 1
44
+ export const MATCHER_KINDS = [
45
+ 'command-pattern', 'path-pattern', 'path-outside',
46
+ 'url-host-in', 'url-host-not-in', 'tool-in', 'pid-equal', 'always', 'never',
47
+ ]
48
+ export const EVIDENCE_KINDS = ['pattern-match', 'list-match', 'static']
49
+ const MAX_PATTERN_LENGTH = 500
50
+ const MAX_PATTERNS = 50
51
+
52
+ // ─────────────────────────────────────────────────────────────────────────────
53
+ // 1. YAML 子集解析
54
+ // ─────────────────────────────────────────────────────────────────────────────
55
+
56
+ function stripComment(line) {
57
+ let inSingle = false
58
+ let inDouble = false
59
+ for (let i = 0; i < line.length; i += 1) {
60
+ const ch = line[i]
61
+ if (ch === "'" && !inDouble) inSingle = !inSingle
62
+ else if (ch === '"' && !inSingle) inDouble = !inDouble
63
+ else if (ch === '#' && !inSingle && !inDouble) return line.slice(0, i)
64
+ }
65
+ return line
66
+ }
67
+
68
+ function unescapeDouble(text) {
69
+ return text.replace(/\\(["\\/nrt])/g, (_m, c) => (c === 'n' ? '\n' : c === 'r' ? '\r' : c === 't' ? '\t' : c))
70
+ }
71
+
72
+ /** 按顶层逗号切分 flow 内容(尊重引号与嵌套 [] {})。 */
73
+ function splitFlowParts(inner) {
74
+ const parts = []
75
+ let current = ''
76
+ let inSingle = false
77
+ let inDouble = false
78
+ let depth = 0
79
+ for (const ch of inner) {
80
+ if (ch === "'" && !inDouble) inSingle = !inSingle
81
+ else if (ch === '"' && !inSingle) inDouble = !inDouble
82
+ else if (!inSingle && !inDouble) {
83
+ if (ch === '[' || ch === '{') depth += 1
84
+ else if (ch === ']' || ch === '}') depth -= 1
85
+ else if (ch === ',' && depth === 0) {
86
+ parts.push(current)
87
+ current = ''
88
+ continue
89
+ }
90
+ }
91
+ current += ch
92
+ }
93
+ if (current.trim().length > 0) parts.push(current)
94
+ return parts
95
+ }
96
+
97
+ /** flow 映射里第一个顶层冒号位置(引号/嵌套外);没有则 -1。 */
98
+ function findFlowColon(part) {
99
+ let inSingle = false
100
+ let inDouble = false
101
+ let depth = 0
102
+ for (let index = 0; index < part.length; index += 1) {
103
+ const ch = part[index]
104
+ if (ch === "'" && !inDouble) inSingle = !inSingle
105
+ else if (ch === '"' && !inSingle) inDouble = !inDouble
106
+ else if (!inSingle && !inDouble) {
107
+ if (ch === '[' || ch === '{') depth += 1
108
+ else if (ch === ']' || ch === '}') depth -= 1
109
+ else if (ch === ':' && depth === 0) return index
110
+ }
111
+ }
112
+ return -1
113
+ }
114
+
115
+ function unquoteFlowKey(raw) {
116
+ const text = String(raw ?? '').trim()
117
+ if (text.length >= 2 && ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'")))) {
118
+ return text.startsWith('"') ? unescapeDouble(text.slice(1, -1)) : text.slice(1, -1)
119
+ }
120
+ return text
121
+ }
122
+
123
+ function parseScalar(raw) {
124
+ const text = String(raw ?? '').trim()
125
+ if (text.length === 0) return null
126
+ if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) return unescapeDouble(text.slice(1, -1))
127
+ if (text.length >= 2 && text.startsWith("'") && text.endsWith("'")) return text.slice(1, -1).replace(/''/g, "'")
128
+ if ((text.startsWith('[') && text.endsWith(']')) || (text.startsWith('{') && text.endsWith('}'))) {
129
+ const isList = text.startsWith('[')
130
+ const inner = text.slice(1, -1).trim()
131
+ if (inner.length === 0) return isList ? [] : {}
132
+ const parts = splitFlowParts(inner)
133
+ if (isList) return parts.map((part) => parseScalar(part))
134
+ const mapping = {}
135
+ for (const part of parts) {
136
+ const colon = findFlowColon(part)
137
+ if (colon < 0) {
138
+ mapping[unquoteFlowKey(part)] = null
139
+ continue
140
+ }
141
+ mapping[unquoteFlowKey(part.slice(0, colon))] = parseScalar(part.slice(colon + 1))
142
+ }
143
+ return mapping
144
+ }
145
+ if (text === 'true') return true
146
+ if (text === 'false') return false
147
+ if (text === 'null' || text === '~') return null
148
+ if (/^-?\d+$/.test(text)) return Number(text)
149
+ if (/^-?\d+\.\d+$/.test(text)) return Number(text)
150
+ return text
151
+ }
152
+
153
+ /**
154
+ * 解析 YAML 子集。返回 { value, errors }。
155
+ * 不支持的语法(锚点/别名/多文档/块标量/tab 缩进)会给出明确错误,由调用方 fail-safe 处理。
156
+ */
157
+ export function parseYamlSubset(text) {
158
+ const errors = []
159
+ const tokens = []
160
+ const lines = String(text ?? '').split(/\r?\n/)
161
+ for (let index = 0; index < lines.length; index += 1) {
162
+ const noComment = stripComment(lines[index])
163
+ if (noComment.trim().length === 0) continue
164
+ if (noComment.startsWith('---') || noComment.startsWith('...')) {
165
+ errors.push(`line ${index + 1}: multi-document YAML is not supported`)
166
+ continue
167
+ }
168
+ const indentMatch = /^[ \t]*/.exec(noComment)[0]
169
+ if (indentMatch.includes('\t')) {
170
+ errors.push(`line ${index + 1}: tab indentation is not supported`)
171
+ continue
172
+ }
173
+ tokens.push({ indent: indentMatch.length, content: noComment.trim(), line: index + 1 })
174
+ }
175
+ if (errors.length > 0) return { value: null, errors }
176
+
177
+ const isSequenceLine = (token) => token.content === '-' || token.content.startsWith('- ')
178
+
179
+ const parseBlock = (startIndex, indent) => {
180
+ const first = tokens[startIndex]
181
+ if (first === undefined) return [null, startIndex]
182
+ if (isSequenceLine(first)) return parseSequence(startIndex, indent)
183
+ return parseMapping(startIndex, indent)
184
+ }
185
+
186
+ const parseSequence = (startIndex, indent) => {
187
+ const items = []
188
+ let index = startIndex
189
+ while (index < tokens.length) {
190
+ const token = tokens[index]
191
+ if (token.indent !== indent || !isSequenceLine(token)) break
192
+ const rest = token.content === '-' ? '' : token.content.slice(2).trim()
193
+ if (rest.length === 0) {
194
+ const next = tokens[index + 1]
195
+ if (next !== undefined && next.indent > indent) {
196
+ const [child, nextIndex] = parseBlock(index + 1, next.indent)
197
+ items.push(child)
198
+ index = nextIndex
199
+ } else {
200
+ items.push(null)
201
+ index += 1
202
+ }
203
+ continue
204
+ }
205
+ const inlineKey = /^([A-Za-z0-9_$.-]+):(?:\s|$)/.exec(rest)
206
+ if (inlineKey !== null) {
207
+ const virtualIndent = indent + 2
208
+ const key = inlineKey[1]
209
+ const restValue = rest.slice(inlineKey[0].length).trim()
210
+ const mapped = {}
211
+ if (restValue.length > 0) mapped[key] = parseScalar(restValue)
212
+ else {
213
+ const next = tokens[index + 1]
214
+ if (next !== undefined && next.indent > virtualIndent) {
215
+ const [child, nextIndex] = parseBlock(index + 1, next.indent)
216
+ mapped[key] = child
217
+ index = nextIndex - 1
218
+ } else {
219
+ mapped[key] = null
220
+ }
221
+ }
222
+ // 同时解析续行的同级键(`- key: v` 后面按 indent+2 继续)
223
+ index += 1
224
+ while (index < tokens.length && tokens[index].indent === virtualIndent && !isSequenceLine(tokens[index])) {
225
+ const line = tokens[index]
226
+ const match = /^([A-Za-z0-9_$.-]+):(?:\s*(.*))?$/.exec(line.content)
227
+ if (match === null) {
228
+ errors.push(`line ${line.line}: expected "key: value" inside sequence item`)
229
+ index += 1
230
+ continue
231
+ }
232
+ const childKey = match[1]
233
+ const childRest = String(match[2] ?? '').trim()
234
+ if (childRest.length > 0) {
235
+ mapped[childKey] = parseScalar(childRest)
236
+ index += 1
237
+ continue
238
+ }
239
+ const nextToken = tokens[index + 1]
240
+ if (nextToken !== undefined && nextToken.indent > virtualIndent) {
241
+ const [child, nextIndex] = parseBlock(index + 1, nextToken.indent)
242
+ mapped[childKey] = child
243
+ index = nextIndex
244
+ } else {
245
+ mapped[childKey] = null
246
+ index += 1
247
+ }
248
+ }
249
+ items.push(mapped)
250
+ continue
251
+ }
252
+ items.push(parseScalar(rest))
253
+ index += 1
254
+ }
255
+ return [items, index]
256
+ }
257
+
258
+ const parseMapping = (startIndex, indent) => {
259
+ const mapping = {}
260
+ let index = startIndex
261
+ while (index < tokens.length) {
262
+ const token = tokens[index]
263
+ if (token.indent !== indent || isSequenceLine(token)) break
264
+ const match = /^([A-Za-z0-9_$.-]+):(?:\s*(.*))?$/.exec(token.content)
265
+ if (match === null) {
266
+ errors.push(`line ${token.line}: expected "key: value" or "- item"`)
267
+ index += 1
268
+ continue
269
+ }
270
+ const key = match[1]
271
+ const rest = String(match[2] ?? '').trim()
272
+ if (rest.length > 0) {
273
+ mapping[key] = parseScalar(rest)
274
+ index += 1
275
+ continue
276
+ }
277
+ const next = tokens[index + 1]
278
+ if (next !== undefined && next.indent > indent) {
279
+ const [child, nextIndex] = parseBlock(index + 1, next.indent)
280
+ mapping[key] = child
281
+ index = nextIndex
282
+ } else {
283
+ mapping[key] = null
284
+ index += 1
285
+ }
286
+ }
287
+ return [mapping, index]
288
+ }
289
+
290
+ const [value, endIndex] = parseBlock(0, tokens[0].indent)
291
+ if (endIndex < tokens.length) {
292
+ const leftover = tokens[endIndex]
293
+ errors.push(`line ${leftover.line}: unexpected indentation / content`)
294
+ }
295
+ return { value, errors }
296
+ }
297
+
298
+ // ─────────────────────────────────────────────────────────────────────────────
299
+ // 2. schema 校验(手写;错误逐条给出,不做部分接受)
300
+ // ─────────────────────────────────────────────────────────────────────────────
301
+
302
+ const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value)
303
+
304
+ function checkPatternList(list, field, errors) {
305
+ if (!Array.isArray(list)) {
306
+ errors.push(`${field}: must be a list`)
307
+ return
308
+ }
309
+ if (list.length === 0 || list.length > MAX_PATTERNS) {
310
+ errors.push(`${field}: must contain 1..${MAX_PATTERNS} patterns`)
311
+ return
312
+ }
313
+ for (const [index, pattern] of list.entries()) {
314
+ if (!isPlainObject(pattern)) {
315
+ errors.push(`${field}[${index}]: must be an object { re, label? }`)
316
+ continue
317
+ }
318
+ if (typeof pattern.re !== 'string' || pattern.re.length === 0) {
319
+ errors.push(`${field}[${index}].re: required non-empty string`)
320
+ continue
321
+ }
322
+ if (pattern.re.length > MAX_PATTERN_LENGTH) {
323
+ errors.push(`${field}[${index}].re: longer than ${MAX_PATTERN_LENGTH} chars`)
324
+ }
325
+ if (pattern.label !== undefined && (typeof pattern.label !== 'string' || pattern.label.length > 200)) {
326
+ errors.push(`${field}[${index}].label: string ≤200 chars`)
327
+ }
328
+ }
329
+ }
330
+
331
+ function validateMatcher(match, field, errors) {
332
+ if (!isPlainObject(match)) {
333
+ errors.push(`${field}: must be an object with a "kind"`)
334
+ return
335
+ }
336
+ const kind = match.kind
337
+ if (!MATCHER_KINDS.includes(kind)) {
338
+ errors.push(`${field}.kind: unknown matcher "${String(kind)}" (allowed: ${MATCHER_KINDS.join(', ')})`)
339
+ return
340
+ }
341
+ if (kind === 'command-pattern') checkPatternList(match.patterns, `${field}.patterns`, errors)
342
+ if (kind === 'path-pattern') {
343
+ checkPatternList(match.patterns, `${field}.patterns`, errors)
344
+ if (match.scope !== undefined && !['target', 'read', 'write', 'all'].includes(match.scope)) {
345
+ errors.push(`${field}.scope: must be target|read|write|all`)
346
+ }
347
+ }
348
+ if (kind === 'path-outside') {
349
+ if (!['$bufferRoot', '$productionRoot', 'literal'].includes(match.root)) {
350
+ errors.push(`${field}.root: must be $bufferRoot|$productionRoot|literal`)
351
+ }
352
+ if (match.root === 'literal' && typeof match.literal !== 'string') {
353
+ errors.push(`${field}.literal: required when root=literal`)
354
+ }
355
+ }
356
+ if (kind === 'url-host-in' || kind === 'url-host-not-in') {
357
+ if (!Array.isArray(match.hosts) || match.hosts.length === 0 || match.hosts.length > 100) {
358
+ errors.push(`${field}.hosts: list with 1..100 entries`)
359
+ }
360
+ }
361
+ if (kind === 'tool-in') {
362
+ if (!Array.isArray(match.tools) || match.tools.length === 0 || match.tools.length > 50) {
363
+ errors.push(`${field}.tools: list with 1..50 entries`)
364
+ }
365
+ }
366
+ if (kind === 'pid-equal') {
367
+ const ok = match.pid === '$currentPid' || (typeof match.pid === 'number' && Number.isInteger(match.pid))
368
+ if (!ok) errors.push(`${field}.pid: must be $currentPid or an integer`)
369
+ }
370
+ }
371
+
372
+ function validateEvidence(evidence, field, errors) {
373
+ if (evidence === undefined) return
374
+ if (!isPlainObject(evidence)) {
375
+ errors.push(`${field}: must be an object`)
376
+ return
377
+ }
378
+ if (!EVIDENCE_KINDS.includes(evidence.kind)) {
379
+ errors.push(`${field}.kind: unknown evidence "${String(evidence.kind)}" (allowed: ${EVIDENCE_KINDS.join(', ')})`)
380
+ return
381
+ }
382
+ if (evidence.kind === 'static' && !isPlainObject(evidence.payload)) {
383
+ errors.push(`${field}.payload: object required for kind=static`)
384
+ }
385
+ }
386
+
387
+ /** 校验单个规则条目(overlay 或 declarative)。 */
388
+ export function validateRuleEntry(entry, index, errors) {
389
+ const field = `rules[${index}]`
390
+ if (!isPlainObject(entry)) {
391
+ errors.push(`${field}: must be an object`)
392
+ return
393
+ }
394
+ if (typeof entry.id !== 'string' || entry.id.length === 0 || entry.id.length > 100) {
395
+ errors.push(`${field}.id: required string (1..100 chars)`)
396
+ } else if (!/^[a-z0-9][a-z0-9-]*$/.test(entry.id)) {
397
+ errors.push(`${field}.id: must match ^[a-z0-9][a-z0-9-]*$`)
398
+ }
399
+ if (entry.enabled !== undefined && typeof entry.enabled !== 'boolean') errors.push(`${field}.enabled: boolean`)
400
+ if (entry.light !== undefined && !Object.prototype.hasOwnProperty.call(LIGHT_RANK, entry.light)) {
401
+ errors.push(`${field}.light: must be green|blue|yellow|red`)
402
+ }
403
+ if (entry.priority !== undefined && (!Number.isInteger(entry.priority) || entry.priority < 0 || entry.priority > 10000)) {
404
+ errors.push(`${field}.priority: integer 0..10000`)
405
+ }
406
+ if (entry.reason !== undefined && (typeof entry.reason !== 'string' || entry.reason.length > 500)) {
407
+ errors.push(`${field}.reason: string ≤500 chars`)
408
+ }
409
+ if (entry.tags !== undefined) {
410
+ if (!Array.isArray(entry.tags) || entry.tags.length > 20 || entry.tags.some((t) => typeof t !== 'string')) {
411
+ errors.push(`${field}.tags: list of ≤20 strings`)
412
+ }
413
+ }
414
+ if (entry.category !== undefined && !ACTION_CATEGORIES.includes(entry.category)) {
415
+ errors.push(`${field}.category: must be one of ${ACTION_CATEGORIES.join(', ')}`)
416
+ }
417
+ if (entry.match !== undefined) validateMatcher(entry.match, `${field}.match`, errors)
418
+ if (entry.evidence !== undefined) validateEvidence(entry.evidence, `${field}.evidence`, errors)
419
+ if (entry.pathPatterns !== undefined) checkPatternList(entry.pathPatterns, `${field}.pathPatterns`, errors)
420
+ if (entry.commandPatterns !== undefined) checkPatternList(entry.commandPatterns, `${field}.commandPatterns`, errors)
421
+ }
422
+
423
+ /**
424
+ * 校验整个配置。返回 { config, errors };errors 非空时调用方必须回退(fail-safe)。
425
+ */
426
+ export function validateRuleConfig(raw) {
427
+ const errors = []
428
+ if (!isPlainObject(raw)) return { config: null, errors: ['config: top level must be a mapping'] }
429
+ if (raw.version !== RULE_CONFIG_VERSION) {
430
+ errors.push(`version: must be ${RULE_CONFIG_VERSION}`)
431
+ }
432
+ if (raw.inherit !== undefined && typeof raw.inherit !== 'boolean') errors.push('inherit: boolean')
433
+ const settings = isPlainObject(raw.settings) ? raw.settings : {}
434
+ for (const key of ['failOnUnknownRule', 'failOnInvalidPattern', 'rejectUnsafeRegex']) {
435
+ if (settings[key] !== undefined && typeof settings[key] !== 'boolean') errors.push(`settings.${key}: boolean`)
436
+ }
437
+ const rules = raw.rules ?? []
438
+ if (!Array.isArray(rules)) {
439
+ errors.push('rules: must be a list')
440
+ } else {
441
+ for (const [index, entry] of rules.entries()) validateRuleEntry(entry, index, errors)
442
+ }
443
+ if (errors.length > 0) return { config: null, errors }
444
+ return {
445
+ config: {
446
+ version: RULE_CONFIG_VERSION,
447
+ inherit: raw.inherit !== false,
448
+ settings: {
449
+ failOnUnknownRule: settings.failOnUnknownRule === true,
450
+ failOnInvalidPattern: settings.failOnInvalidPattern === true,
451
+ rejectUnsafeRegex: settings.rejectUnsafeRegex !== false,
452
+ },
453
+ rules,
454
+ },
455
+ errors: [],
456
+ }
457
+ }
458
+
459
+ // ─────────────────────────────────────────────────────────────────────────────
460
+ // 3. 正则安全启发式(不是完整 ReDoS 检测,够挡住明显灾难回溯)
461
+ // ─────────────────────────────────────────────────────────────────────────────
462
+
463
+ export function isSafePatternSource(source) {
464
+ const text = String(source ?? '')
465
+ if (text.length === 0 || text.length > MAX_PATTERN_LENGTH) return false
466
+ // 禁止嵌套量词:(a+)+ / (.*)* / (\w+)* 这类灾难回溯形状
467
+ if (/\([^()]*[+*]\)[+*]/.test(text)) return false
468
+ if (/\([^()]*\{\d+,\}\)[+*]/.test(text)) return false
469
+ // 超过 200 的定长重复基本没有正当用途
470
+ if (/\{\s*\d{3,}/.test(text)) return false
471
+ return true
472
+ }
473
+
474
+ function compilePatterns(list, errors, labelPrefix) {
475
+ const out = []
476
+ for (const [index, pattern] of list.entries()) {
477
+ if (!isSafePatternSource(pattern.re)) {
478
+ errors.push(`${labelPrefix}[${index}]: unsafe or too long regex rejected`)
479
+ continue
480
+ }
481
+ try {
482
+ out.push({
483
+ re: new RegExp(pattern.re, 'i'),
484
+ id: pattern.id ?? pattern.label ?? String(pattern.re).slice(0, 40),
485
+ label: pattern.label ?? String(pattern.re).slice(0, 40),
486
+ })
487
+ } catch (e) {
488
+ errors.push(`${labelPrefix}[${index}]: invalid regex (${e?.message ?? e})`)
489
+ }
490
+ }
491
+ return out
492
+ }
493
+
494
+ // ─────────────────────────────────────────────────────────────────────────────
495
+ // 4. 声明式 matcher / evidence 编译
496
+ // ─────────────────────────────────────────────────────────────────────────────
497
+
498
+ function hostMatches(host, pattern) {
499
+ const p = String(pattern).toLowerCase()
500
+ const h = String(host).toLowerCase()
501
+ if (p.startsWith('*.')) return h.endsWith(p.slice(1))
502
+ return h === p
503
+ }
504
+
505
+ function pathInside(child, parent) {
506
+ if (typeof child !== 'string' || typeof parent !== 'string' || parent.length === 0) return false
507
+ const rel = path.relative(path.resolve(parent), path.resolve(child))
508
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
509
+ }
510
+
511
+ /** 编译声明式规则;返回 { rule, errors }(errors 非空时 rule 可能仍可用,调用方决定)。 */
512
+ export function compileDeclarativeRule(entry, { rejectUnsafeRegex = true } = {}) {
513
+ const errors = []
514
+ const patterns = {}
515
+ const compile = (list, key) => {
516
+ if (list === undefined) return []
517
+ const compiled = compilePatterns(list, errors, `rules.${entry.id}.${key}`)
518
+ if (rejectUnsafeRegex === false) {
519
+ // 调用方显式关闭安全检查时,把因安全被拒的模式按原样重编译(仍要求语法合法)
520
+ for (const [index, pattern] of list.entries()) {
521
+ if (compiled.some((c) => c.source === pattern.re)) continue
522
+ try {
523
+ compiled.push({ re: new RegExp(pattern.re, 'i'), id: pattern.id ?? `p${index}`, label: pattern.label ?? pattern.re })
524
+ } catch { /* 已记录为错误 */ }
525
+ }
526
+ }
527
+ patterns[key] = compiled
528
+ return compiled
529
+ }
530
+
531
+ const match = entry.match
532
+ let matchFn = null
533
+ const evidenceKind = entry.evidence?.kind ?? 'pattern-match'
534
+
535
+ if (match !== undefined) {
536
+ switch (match.kind) {
537
+ case 'command-pattern': {
538
+ const compiled = compile(match.patterns, 'commandPatterns')
539
+ matchFn = (_ev, ctx) => compiled.some(({ re }) => re.test(ctx.commandText))
540
+ break
541
+ }
542
+ case 'path-pattern': {
543
+ const compiled = compile(match.patterns, 'pathPatterns')
544
+ const scope = match.scope ?? 'all'
545
+ matchFn = (_ev, ctx) => {
546
+ const candidates = []
547
+ if (scope === 'target' || scope === 'all') if (ctx.targetPath !== null) candidates.push(ctx.targetPath)
548
+ if (scope === 'write' || scope === 'all') candidates.push(...ctx.writeTargets)
549
+ if (scope === 'read' || scope === 'all') candidates.push(...ctx.readTargets)
550
+ return candidates.some((p) => compiled.some(({ re }) => re.test(p)))
551
+ }
552
+ break
553
+ }
554
+ case 'path-outside': {
555
+ const rootOf = (ev) => {
556
+ if (match.root === '$bufferRoot') return ev?.context?.bufferRoot ?? null
557
+ if (match.root === '$productionRoot') return ev?.context?.productionRoot ?? null
558
+ return match.literal ?? null
559
+ }
560
+ const checkAllowPaths = match.checkAllowPaths !== false
561
+ matchFn = (ev, ctx) => {
562
+ if (ctx.targetPath === null) return false
563
+ const root = rootOf({ context: { ...ev?.context, bufferRoot: ctx.policy.bufferRoot, productionRoot: ctx.policy.productionRoot } })
564
+ if (root === null) return false
565
+ if (pathInside(ctx.targetPath, root)) return false
566
+ if (checkAllowPaths && ctx.policy.allowPaths.some((a) => pathInside(ctx.targetPath, a))) return false
567
+ return true
568
+ }
569
+ break
570
+ }
571
+ case 'url-host-in': {
572
+ matchFn = (_ev, ctx) => ctx.url !== null && match.hosts.some((h) => hostMatches(ctx.url.host, h))
573
+ break
574
+ }
575
+ case 'url-host-not-in': {
576
+ matchFn = (_ev, ctx) => ctx.url !== null && !match.hosts.some((h) => hostMatches(ctx.url.host, h))
577
+ break
578
+ }
579
+ case 'tool-in': {
580
+ const set = new Set(match.tools.map(String))
581
+ matchFn = (ev) => set.has(String(ev?.tool ?? ''))
582
+ break
583
+ }
584
+ case 'pid-equal': {
585
+ matchFn = (_ev, ctx) => (match.pid === '$currentPid' ? ctx.targetPid === process.pid : ctx.targetPid === match.pid)
586
+ break
587
+ }
588
+ case 'always': matchFn = () => true; break
589
+ case 'never': matchFn = () => false; break
590
+ default: errors.push(`rules.${entry.id}.match.kind: unsupported "${String(match.kind)}"`)
591
+ }
592
+ }
593
+
594
+ let evidenceFn = null
595
+ switch (evidenceKind) {
596
+ case 'pattern-match': {
597
+ evidenceFn = (_ev, ctx) => {
598
+ const hits = [...(patterns.commandPatterns ?? []), ...(patterns.pathPatterns ?? [])]
599
+ .filter(({ re }) => re.test(ctx.commandText) || (ctx.targetPath !== null && re.test(ctx.targetPath)) || ctx.writeTargets.some((t) => re.test(t)))
600
+ .map((p) => p.id)
601
+ return { matchedPattern: hits.length > 0 ? hits[0] : 'declarative-pattern', patternIds: hits }
602
+ }
603
+ break
604
+ }
605
+ case 'list-match': {
606
+ evidenceFn = (_ev, ctx) => ({
607
+ matchedPattern: 'declarative-list',
608
+ writeTargets: ctx.writeTargets,
609
+ readTargets: ctx.readTargets,
610
+ })
611
+ break
612
+ }
613
+ case 'static': {
614
+ const payload = entry.evidence?.payload ?? {}
615
+ evidenceFn = () => ({ ...payload })
616
+ break
617
+ }
618
+ default:
619
+ errors.push(`rules.${entry.id}.evidence.kind: unsupported "${String(evidenceKind)}"`)
620
+ }
621
+
622
+ if (matchFn === null || evidenceFn === null) return { rule: null, errors }
623
+
624
+ const light = entry.light
625
+ const category = entry.category
626
+ const reason = entry.reason
627
+ return {
628
+ rule: {
629
+ id: entry.id,
630
+ category,
631
+ light,
632
+ reason,
633
+ tags: entry.tags ?? [],
634
+ match: matchFn,
635
+ evidence: evidenceFn,
636
+ source: 'yaml',
637
+ priority: entry.priority,
638
+ },
639
+ errors,
640
+ }
641
+ }
642
+
643
+ // ─────────────────────────────────────────────────────────────────────────────
644
+ // 5. RuleRegistry:内置 + YAML 叠加(事务化)
645
+ // ─────────────────────────────────────────────────────────────────────────────
646
+
647
+ /**
648
+ * @param {object[]} builtinRules 默认 DEFAULT_ACTION_RULES
649
+ * @param {{priorities?: Record<string, number>}} [options]
650
+ */
651
+ /** 不可协商标签:带这些标签的规则不可被关闭、不可被降低灯色。 */
652
+ export const NON_NEGOTIABLE_TAGS = Object.freeze(['hard-deny', 'non-negotiable'])
653
+
654
+ export function isLockedRule(rule) {
655
+ return Array.isArray(rule?.tags) && rule.tags.some((tag) => NON_NEGOTIABLE_TAGS.includes(tag))
656
+ }
657
+
658
+ /**
659
+ * 分层规则注册表:内置规则 → YAML 层(基线 → 项目 → 环境,后层按 id 覆盖前层)。
660
+ * 事务化:任何一层被判定 fatal 时整次 rebuild 被拒绝,effective 保持上一次有效值。
661
+ *
662
+ * @param {object[]} builtinRules
663
+ * @param {{priorities?: Record<string, number>}} [options]
664
+ */
665
+ export function createRuleRegistry(builtinRules = DEFAULT_ACTION_RULES, options = {}) {
666
+ const builtin = [...builtinRules]
667
+ const defaultPriorities = { ...DEFAULT_RULE_PRIORITIES, ...(options.priorities ?? {}) }
668
+ let effective = []
669
+ let layers = []
670
+ let status = { source: 'builtin', appliedAt: null, warnings: [], errors: [], configVersion: null, layers: 0, strictMode: null }
671
+
672
+ const priorityBase = (rule, priorities) => {
673
+ const explicit = priorities[rule.id]
674
+ if (Number.isFinite(explicit)) return explicit
675
+ const index = builtin.findIndex((r) => r.id === rule.id)
676
+ return index >= 0 ? index * 10 : 5000
677
+ }
678
+
679
+ const sortRules = (rules, priorities) => rules
680
+ .map((rule, index) => ({ rule, index }))
681
+ .sort((a, b) => {
682
+ const pa = priorityBase(a.rule, priorities)
683
+ const pb = priorityBase(b.rule, priorities)
684
+ if (pa !== pb) return pa - pb
685
+ return a.index - b.index
686
+ })
687
+ .map(({ rule }) => rule)
688
+
689
+ const resetToBuiltin = () => {
690
+ layers = []
691
+ effective = sortRules(builtin, defaultPriorities)
692
+ status = { source: 'builtin', appliedAt: Date.now(), warnings: [], errors: [], configVersion: null, layers: 0, strictMode: null }
693
+ return effective
694
+ }
695
+ resetToBuiltin()
696
+
697
+ /**
698
+ * 纯计算:从内置 + 给定层序列构建候选规则表。**不修改** effective/status,
699
+ * 由调用方在 applied 时提交——失败时三者全部保持上一次成功值。
700
+ */
701
+ const computeRebuild = (layerList) => {
702
+ const warnings = []
703
+ const errors = []
704
+ const layerRecords = []
705
+ const priorities = { ...defaultPriorities }
706
+ let byId = new Map(builtin.map((rule) => [rule.id, rule]))
707
+ let order = builtin.map((rule) => rule.id)
708
+ const locked = new Set()
709
+ const builtinById = new Map(builtin.map((rule) => [rule.id, rule]))
710
+
711
+ // inherit:false = 严格模式:丢弃此前所有可调规则,只保留硬规则 + fallback,
712
+ // 然后从该层开始叠加。硬规则与 fallback 不能被任何配置拆掉。
713
+ let startIndex = 0
714
+ for (let index = layerList.length - 1; index >= 0; index -= 1) {
715
+ if (layerList[index].inherit === false) { startIndex = index; break }
716
+ }
717
+ const strictMode = startIndex > 0 || (layerList.length > 0 && layerList[0].inherit === false)
718
+ let strictModeInfo = null
719
+ if (strictMode) {
720
+ const preserved = builtin.filter((rule) => isLockedRule(rule) || rule.category === 'fallback')
721
+ byId = new Map(preserved.map((rule) => [rule.id, rule]))
722
+ order = preserved.map((rule) => rule.id)
723
+ for (const id of Object.keys(priorities)) if (!byId.has(id)) delete priorities[id]
724
+ strictModeInfo = {
725
+ activatedAt: Date.now(),
726
+ layerIndex: startIndex,
727
+ preservedHardRules: preserved.filter((rule) => isLockedRule(rule)).map((rule) => rule.id),
728
+ preservedFallback: preserved.filter((rule) => rule.category === 'fallback').map((rule) => rule.id),
729
+ discardedRuleCount: builtin.length - preserved.length,
730
+ }
731
+ }
732
+ let fatal = false
733
+ let lockViolation = false
734
+
735
+ for (let layerIndex = startIndex; layerIndex < layerList.length; layerIndex += 1) {
736
+ const layer = layerList[layerIndex]
737
+ const layerErrors = []
738
+ for (const entry of layer.rules) {
739
+ const isDeclarative = entry.match !== undefined
740
+ if (isDeclarative) {
741
+ if (byId.has(entry.id)) warnings.push(`declarative rule "${entry.id}" shadows an existing rule`)
742
+ const compiled = compileDeclarativeRule(entry, { rejectUnsafeRegex: layer.settings.rejectUnsafeRegex })
743
+ layerErrors.push(...compiled.errors)
744
+ if (compiled.rule !== null) {
745
+ try {
746
+ assertActionRule(compiled.rule)
747
+ byId.set(compiled.rule.id, compiled.rule)
748
+ if (!order.includes(compiled.rule.id)) order.push(compiled.rule.id)
749
+ if (entry.priority !== undefined) priorities[compiled.rule.id] = entry.priority
750
+ if (isLockedRule(compiled.rule)) locked.add(compiled.rule.id)
751
+ } catch (e) {
752
+ layerErrors.push(`rules.${entry.id}: ${e.message}`)
753
+ }
754
+ }
755
+ continue
756
+ }
757
+
758
+ // 严格模式丢弃过内置规则后,后续层仍可按 id 引用它(重新引入内置定义再覆盖),
759
+ // 这样 inherit:false 之后的 inherit:true 层是"叠加"而不是"必须重写谓词"。
760
+ const base = byId.get(entry.id) ?? builtinById.get(entry.id)
761
+ if (base === undefined) {
762
+ const message = `unknown rule id "${entry.id}"`
763
+ if (layer.settings.failOnUnknownRule) layerErrors.push(message)
764
+ else warnings.push(message)
765
+ continue
766
+ }
767
+
768
+ // 硬规则锁定:不可关闭、不可降低灯色(允许提升灯色 / 追加 pattern / 改 reason)
769
+ if (isLockedRule(base) || locked.has(base.id)) {
770
+ if (entry.enabled === false) {
771
+ layerErrors.push(`rule "${entry.id}" is non-negotiable and cannot be disabled`)
772
+ lockViolation = true
773
+ continue
774
+ }
775
+ if (entry.light !== undefined && !(LIGHT_RANK[entry.light] >= LIGHT_RANK[base.light])) {
776
+ layerErrors.push(`rule "${entry.id}" is non-negotiable; light cannot be lowered from ${base.light} to ${entry.light}`)
777
+ lockViolation = true
778
+ continue
779
+ }
780
+ if (entry.tags !== undefined) {
781
+ const requiredTags = (base.tags ?? []).filter((tag) => NON_NEGOTIABLE_TAGS.includes(tag))
782
+ const missingTags = requiredTags.filter((tag) => !Array.isArray(entry.tags) || !entry.tags.includes(tag))
783
+ if (missingTags.length > 0) {
784
+ layerErrors.push(`rule "${entry.id}" is non-negotiable; locked tags cannot be removed: ${missingTags.join(',')}`)
785
+ lockViolation = true
786
+ continue
787
+ }
788
+ }
789
+ if (entry.priority !== undefined) {
790
+ const currentPriority = priorities[base.id] ?? defaultPriorities[base.id] ?? 500
791
+ if (entry.priority > currentPriority) {
792
+ layerErrors.push(`rule "${entry.id}" is non-negotiable; priority cannot move later than ${currentPriority}`)
793
+ lockViolation = true
794
+ continue
795
+ }
796
+ }
797
+ }
798
+
799
+ if (entry.enabled === false) {
800
+ byId.delete(entry.id)
801
+ locked.delete(entry.id)
802
+ continue
803
+ }
804
+
805
+ if (!byId.has(entry.id)) {
806
+ if (!order.includes(entry.id)) order.push(entry.id)
807
+ if (priorities[entry.id] === undefined) priorities[entry.id] = defaultPriorities[entry.id] ?? 500
808
+ }
809
+ let patched = {
810
+ ...base,
811
+ light: entry.light ?? base.light,
812
+ reason: entry.reason ?? base.reason,
813
+ tags: entry.tags ?? base.tags,
814
+ category: entry.category ?? base.category,
815
+ }
816
+ if (entry.pathPatterns !== undefined || entry.commandPatterns !== undefined) {
817
+ const patternErrors = []
818
+ const pathPatterns = entry.pathPatterns === undefined
819
+ ? []
820
+ : compilePatterns(entry.pathPatterns, patternErrors, `rules.${entry.id}.pathPatterns`)
821
+ const commandPatterns = entry.commandPatterns === undefined
822
+ ? []
823
+ : compilePatterns(entry.commandPatterns, patternErrors, `rules.${entry.id}.commandPatterns`)
824
+ layerErrors.push(...patternErrors)
825
+ const originalMatch = base.match
826
+ patched = {
827
+ ...patched,
828
+ match: (ev, ctx) => {
829
+ if (originalMatch(ev, ctx)) return true
830
+ if (commandPatterns.some(({ re }) => re.test(ctx.commandText))) return true
831
+ const candidates = [ctx.targetPath, ...ctx.writeTargets, ...ctx.readTargets].filter((x) => typeof x === 'string')
832
+ return candidates.some((p) => pathPatterns.some(({ re }) => re.test(p)))
833
+ },
834
+ }
835
+ }
836
+ if (entry.priority !== undefined) priorities[entry.id] = entry.priority
837
+ const merged = { ...patched, source: 'yaml' }
838
+ byId.set(entry.id, merged)
839
+ if (isLockedRule(merged)) locked.add(entry.id)
840
+ }
841
+ errors.push(...layerErrors)
842
+ if (layer.settings.failOnInvalidPattern && layerErrors.length > 0) fatal = true
843
+ if (layer.settings.failOnUnknownRule && layerErrors.some((e) => e.startsWith('unknown rule id'))) fatal = true
844
+ layerRecords.push({ index: layerIndex, inherit: layer.inherit !== false, version: layer.version, rules: layer.rules.length, errors: layerErrors.length })
845
+ }
846
+
847
+ if (lockViolation) fatal = true
848
+ const merged = order.map((id) => byId.get(id)).filter((rule) => rule !== undefined)
849
+ const sorted = sortRules(merged, priorities)
850
+ // 安全网:任何 rebuild 结果都必须有 fallback(未知动作的兜底)
851
+ if (!sorted.some((rule) => rule.category === 'fallback')) {
852
+ warnings.push('fallback rule missing after rebuild')
853
+ fatal = true
854
+ }
855
+ const source = strictMode ? 'strict-replaced' : (layerList.length > 0 ? 'layered' : 'builtin')
856
+ if (fatal) {
857
+ // 失败:不提交任何状态(effective / status / strictMode 保持上一次成功值)
858
+ return {
859
+ applied: false,
860
+ ruleCount: effective.length,
861
+ warnings,
862
+ errors,
863
+ source,
864
+ layers: layerRecords,
865
+ strictMode: null,
866
+ effective,
867
+ status,
868
+ }
869
+ }
870
+ const nextStatus = {
871
+ source,
872
+ appliedAt: Date.now(),
873
+ warnings,
874
+ errors,
875
+ configVersion: layerList.at(-1)?.version ?? null,
876
+ layers: layerList.length,
877
+ strictMode: strictModeInfo,
878
+ }
879
+ return {
880
+ applied: true,
881
+ ruleCount: sorted.length,
882
+ warnings,
883
+ errors,
884
+ source,
885
+ layers: layerRecords,
886
+ strictMode: strictModeInfo,
887
+ effective: sorted,
888
+ status: nextStatus,
889
+ }
890
+ }
891
+
892
+ const find = (evidence, ctx) => effective.find((rule) => rule.match(evidence, ctx)) ?? effective[effective.length - 1] ?? null
893
+
894
+ // 运行时注册(测试 / 嵌宿主用;YAML 只允许声明式)
895
+ const register = (rule, placement = {}) => {
896
+ assertActionRule(rule)
897
+ if (rule.id !== undefined && effective.some((r) => r.id === rule.id)) {
898
+ throw new Error(`action rule already registered: ${rule.id}(覆盖请用 override())`)
899
+ }
900
+ const before = typeof placement.before === 'string' ? effective.findIndex((r) => r.id === placement.before) : -1
901
+ const after = typeof placement.after === 'string' ? effective.findIndex((r) => r.id === placement.after) : -1
902
+ const next = [...effective]
903
+ if (before >= 0) next.splice(before, 0, rule)
904
+ else if (after >= 0) next.splice(after + 1, 0, rule)
905
+ else throw new Error(`action rule ${rule.id}: register() requires before/after naming an existing rule`)
906
+ effective = next
907
+ return rule
908
+ }
909
+ const override = (id, patch = {}) => {
910
+ const index = effective.findIndex((r) => r.id === id)
911
+ if (index < 0) throw new Error(`action rule not found: ${id}`)
912
+ const merged = assertActionRule({ ...effective[index], ...patch, id })
913
+ effective = [...effective.slice(0, index), merged, ...effective.slice(index + 1)]
914
+ return merged
915
+ }
916
+ const remove = (id) => {
917
+ const index = effective.findIndex((r) => r.id === id)
918
+ if (index < 0) return false
919
+ effective = [...effective.slice(0, index), ...effective.slice(index + 1)]
920
+ return true
921
+ }
922
+
923
+ return {
924
+ builtin,
925
+ get rules() { return [...effective] },
926
+ ids: () => effective.map((r) => r.id),
927
+ find,
928
+ register,
929
+ override,
930
+ remove,
931
+ reset: resetToBuiltin,
932
+ resetToBuiltin,
933
+ /** 用一份配置替换所有层(向后兼容 v2.8.0 的单文件语义)。 */
934
+ applyConfig(config) {
935
+ const out = computeRebuild([config])
936
+ if (out.applied) {
937
+ layers = [config]
938
+ effective = out.effective
939
+ status = out.status
940
+ return out
941
+ }
942
+ return { ...out, revertedToLayerIndex: layers.length - 1 }
943
+ },
944
+ /**
945
+ * 追加一层(基线 → 项目 → 环境)。
946
+ * 事务化:失败时 layers / effective / status / strictMode 全部保持上一次成功值,
947
+ * 失败层对后续层完全不可见(否则坏层会污染后续所有 rebuild)。
948
+ * 失败结果带 revertedToLayerIndex(-1 = 内置全集),供审计回答"回退到了哪一层"。
949
+ */
950
+ applyLayer(config) {
951
+ const candidate = [...layers, config]
952
+ const out = computeRebuild(candidate)
953
+ if (out.applied) {
954
+ layers = candidate
955
+ effective = out.effective
956
+ status = out.status
957
+ return out
958
+ }
959
+ return { ...out, revertedToLayerIndex: layers.length - 1 }
960
+ },
961
+ clearLayers() {
962
+ const out = computeRebuild([])
963
+ if (out.applied) {
964
+ layers = []
965
+ effective = out.effective
966
+ status = out.status
967
+ }
968
+ return out
969
+ },
970
+ layerCount: () => layers.length,
971
+ status: () => ({ ...status, ruleCount: effective.length }),
972
+ priorities: () => ({ ...defaultPriorities }),
973
+ }
974
+ }
975
+
976
+ // ─────────────────────────────────────────────────────────────────────────────
977
+ // 6. 文件加载 + 热加载
978
+ // ─────────────────────────────────────────────────────────────────────────────
979
+
980
+ /** 读取并校验规则文件。文件不存在 = {config:null, errors:[], found:false}(用纯内置)。 */
981
+ export function loadRuleConfigFile(file) {
982
+ let text
983
+ try {
984
+ text = fs.readFileSync(file, 'utf8')
985
+ } catch (e) {
986
+ if (e?.code === 'ENOENT') return { config: null, errors: [], found: false }
987
+ return { config: null, errors: [`read failed: ${e?.message ?? e}`], found: true }
988
+ }
989
+ const parsed = parseYamlSubset(text)
990
+ if (parsed.errors.length > 0) return { config: null, errors: parsed.errors, found: true }
991
+ const validated = validateRuleConfig(parsed.value)
992
+ return { config: validated.config, errors: validated.errors, found: true }
993
+ }
994
+
995
+ export function watchRuleConfigFiles(files, onChange = () => {}, options = {}) {
996
+ const debounceMs = Number(options.debounceMs) > 0 ? Number(options.debounceMs) : 200
997
+ const logger = options.logger ?? null
998
+ const list = [...new Set((Array.isArray(files) ? files : [files])
999
+ .filter((file) => typeof file === 'string' && file.length > 0))]
1000
+ const watchers = []
1001
+ let timer = null
1002
+ let stopped = false
1003
+
1004
+ const schedule = () => {
1005
+ if (stopped) return
1006
+ if (timer !== null) clearTimeout(timer)
1007
+ timer = setTimeout(() => {
1008
+ timer = null
1009
+ if (stopped) return
1010
+ try { onChange() } catch (error) {
1011
+ try { logger?.warn?.(`[umbrella-rules] reload callback failed: ${error?.message ?? error}`) } catch { /* ignore */ }
1012
+ }
1013
+ }, debounceMs)
1014
+ }
1015
+
1016
+ for (const file of list) {
1017
+ try {
1018
+ watchers.push(fs.watch(file, schedule))
1019
+ continue
1020
+ } catch { /* missing file: watch its directory */ }
1021
+ try {
1022
+ const dir = path.dirname(file)
1023
+ const base = path.basename(file)
1024
+ watchers.push(fs.watch(dir, (_event, name) => {
1025
+ if (!name || String(name) === base) schedule()
1026
+ }))
1027
+ } catch (error) {
1028
+ try { logger?.warn?.(`[umbrella-rules] cannot watch ${file}: ${error?.message ?? error}`) } catch { /* ignore */ }
1029
+ }
1030
+ }
1031
+
1032
+ return {
1033
+ files: list,
1034
+ reload: schedule,
1035
+ stop() {
1036
+ stopped = true
1037
+ if (timer !== null) clearTimeout(timer)
1038
+ timer = null
1039
+ for (const watcher of watchers) {
1040
+ try { watcher.close() } catch { /* ignore */ }
1041
+ }
1042
+ watchers.length = 0
1043
+ },
1044
+ }
1045
+ }
1046
+
1047
+ /**
1048
+ * 热加载:文件变化 → 防抖 → 重新读取 → 应用。失败保留旧规则。
1049
+ * @returns {{ stop: () => void }}
1050
+ */
1051
+ export function watchRuleConfigFile(file, registry, onResult = () => {}, options = {}) {
1052
+ const debounceMs = Number(options.debounceMs) > 0 ? Number(options.debounceMs) : 200
1053
+ const logger = options.logger ?? null
1054
+ let timer = null
1055
+ let watcher = null
1056
+ let stopped = false
1057
+
1058
+ const reload = () => {
1059
+ if (stopped) return
1060
+ const loaded = loadRuleConfigFile(file)
1061
+ if (loaded.errors.length > 0) {
1062
+ try { logger?.warn?.(`[umbrella-rules] reload failed, keeping previous rules: ${loaded.errors.join('; ')}`) } catch { /* ignore */ }
1063
+ onResult({ applied: false, errors: loaded.errors, warnings: [], reason: 'load-failed' })
1064
+ return
1065
+ }
1066
+ if (loaded.config === null) {
1067
+ registry.resetToBuiltin()
1068
+ onResult({ applied: true, errors: [], warnings: [], reason: 'no-config', ruleCount: registry.rules.length })
1069
+ return
1070
+ }
1071
+ const applied = registry.applyConfig(loaded.config)
1072
+ if (!applied.applied) {
1073
+ try { logger?.warn?.(`[umbrella-rules] apply rejected, keeping previous rules: ${applied.errors.join('; ')}`) } catch { /* ignore */ }
1074
+ }
1075
+ onResult({ ...applied, reason: applied.applied ? 'applied' : 'rejected' })
1076
+ }
1077
+
1078
+ try {
1079
+ watcher = fs.watch(file, () => {
1080
+ if (timer !== null) clearTimeout(timer)
1081
+ timer = setTimeout(() => {
1082
+ timer = null
1083
+ reload()
1084
+ }, debounceMs)
1085
+ })
1086
+ watcher.on?.('error', () => { /* watch 失败不致命:仍保留启动时加载的规则 */ })
1087
+ } catch {
1088
+ watcher = null
1089
+ }
1090
+
1091
+ return {
1092
+ reload,
1093
+ stop() {
1094
+ stopped = true
1095
+ if (timer !== null) clearTimeout(timer)
1096
+ timer = null
1097
+ try { watcher?.close() } catch { /* ignore */ }
1098
+ watcher = null
1099
+ },
1100
+ }
1101
+ }