@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,664 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang 2.3 修复子插件 — 自检 / 证据 / G1–G12 门禁 / 补丁建议(契约:docs/CONTRACTS.md 5.5)。
4
+ //
5
+ // 硬边界:**Healer 不放行,也不写盘**。本插件只读取插件目录并产出结构化证据与
6
+ // 建议补丁;放行权在 approver(见 CONTRACTS.md §1 硬约束 5)。
7
+ //
8
+ // 门禁设计原则(移植自 dsh-hot-update/packages/ci-gate):能确定性判定的才叫门禁;
9
+ // 拿不到证据的判 UNKNOWN 并**默认阻断**(fail-closed,可用 Config.blockingOnUnknown 关闭)。
10
+ //
11
+ // G1–G12 分配(v1.0.0):
12
+ // G1 manifest 字段 name/version/type=module
13
+ // G2 入口存在 可解析的 entry 文件
14
+ // G3 无 eval/new Function 静态源码扫描
15
+ // G4 无裸 child_process import 层扫描(局限:不做调用层)
16
+ // G5 依赖 allow-list dependencies ⊆ { @deepseek-ai/* } ∪ config.allowlist
17
+ // G6 资源闭合 裸定时器必须与 ctx.effect 同时出现(近似判定)
18
+ // G7 豁免诚实性 acceptRisk=true 必须带 {gate,reason} 豁免清单
19
+ // G8 构建脚本闭合 安装期 script 必须列入 dsh.buildApproved
20
+ // G9 秘密卫生 硬编码凭据模式
21
+ // G10 bundle patch 存在 dsh.bundle.patch 声明与文件一致(非 bundle 则 SKIP)
22
+ // G11 激活证据 facts.application === 'applied' 且证据不旧于入口
23
+ // G12 分数可复算 facts.signals/score 重算一致
24
+ // ↑ G11/G12 的 host facts 只在 load 之后才存在:静态预检(stage='load',默认)按 ci-gate
25
+ // G7 先例判 deferred/SKIP;stage='promote' 时必须给 facts,否则 UNKNOWN 阻断(fail-closed)。
26
+ //
27
+ // 证据来源:目录读取全部走 node:fs 只读;无任何写操作(suggestFix 也不写)。
28
+ import fs from 'node:fs'
29
+ import path from 'node:path'
30
+ import { SERVICE, AUDIT, z, readJson, listFiles, sha256, exists } from '../kernel/index.mjs'
31
+ import { scanSource, importsToSignals } from './imports.mjs'
32
+ import { scoreScan, familyOf, entryCandidates, resolvePluginFile } from './scorer.mjs'
33
+ import { roleGate } from '../kernel/index.mjs'
34
+
35
+ export const name = 'fang-healer'
36
+ export const inject = []
37
+
38
+ export const Config = z.object({
39
+ blockingOnUnknown: z.boolean().default(true)
40
+ .description('UNKNOWN 是否阻断(默认 true;关闭后拿不到证据的门禁不阻断),与 ci-gate 语义一致'),
41
+ reservedIds: z.array(z.string()).default([])
42
+ .description('保留插件 id(G5 之外的命名冲突检查;v1.0.0 只记录在 policy)'),
43
+ allowlist: z.array(z.string()).default([])
44
+ .description('额外允许的依赖名(默认放行 @deepseek-ai/*)'),
45
+ })
46
+
47
+ /** 安装期构建脚本(与 ci-gate 一致)。 */
48
+ export const BUILD_SCRIPTS = ['preinstall', 'install', 'postinstall', 'prepare']
49
+
50
+ /** 默认放行的依赖前缀:宿主提供的 @deepseek-ai/* 包。 */
51
+ export const DEFAULT_ALLOWLIST_PREFIXES = ['@deepseek-ai/']
52
+
53
+ /** 硬编码凭据模式(与 ci-gate 一致)。 */
54
+ export const SECRET_PATTERNS = [
55
+ { id: 'aws-access-key', re: /AKIA[0-9A-Z]{16}/ },
56
+ { id: 'github-token', re: /gh[pousr]_[A-Za-z0-9]{20,}/ },
57
+ { id: 'openai-key', re: /sk-[A-Za-z0-9]{20,}/ },
58
+ { id: 'pem-private-key', re: /-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----/ },
59
+ { id: 'slack-token', re: /xox[baprs]-[A-Za-z0-9-]{10,}/ },
60
+ ]
61
+
62
+ const CHILD_PROCESS = new Set(['child_process', 'node:child_process'])
63
+ const TIMER_RE = /(^|[^.\w$])(setInterval|setTimeout|setImmediate)\s*\(/g
64
+ const EVAL_RES = [/(^|[^.\w$])eval\s*\(/g, /\bnew\s+Function\s*\(/g]
65
+ const EFFECT_RE = /ctx\.effect\s*\(/
66
+ const PROVIDE_RE = /ctx\.provide\s*\(/
67
+ const INJECT_RE = /export\s+const\s+inject\s*=\s*(\[[^\]]*\])/
68
+
69
+ export const GATE_IDS = ['G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'G10', 'G11', 'G12']
70
+
71
+ function safeGet(ctx, key) {
72
+ try { return ctx?.get?.(key) } catch { return undefined }
73
+ }
74
+
75
+ function lineOf(src, index) {
76
+ return String(src ?? '').slice(0, index).split('\n').length
77
+ }
78
+
79
+ function findMatches(src, re) {
80
+ const out = []
81
+ if (typeof src !== 'string') return out
82
+ re.lastIndex = 0
83
+ let m
84
+ while ((m = re.exec(src)) !== null) {
85
+ out.push({ index: m.index, line: lineOf(src, m.index), text: m[0] })
86
+ if (m[0].length === 0) re.lastIndex += 1
87
+ }
88
+ return out
89
+ }
90
+
91
+ /** 裸定时器调用点(近似:只看文本,不建 AST)。 */
92
+ export function findTimers(src) {
93
+ return findMatches(src, TIMER_RE).map(m => ({ fn: m.text.trim().replace(/\s*\($/, ''), line: m.line }))
94
+ }
95
+
96
+ /** eval()/new Function() 调用点。 */
97
+ export function findEvalSites(src) {
98
+ const sites = []
99
+ for (const re of EVAL_RES) {
100
+ for (const m of findMatches(src, re)) sites.push({ line: m.line, text: m.text.trim() })
101
+ }
102
+ return sites.sort((a, b) => a.line - b.line)
103
+ }
104
+
105
+ export function findSecrets(src) {
106
+ const text = typeof src === 'string' ? src : ''
107
+ return SECRET_PATTERNS.filter(p => p.re.test(text)).map(p => p.id)
108
+ }
109
+
110
+ function parseInject(src) {
111
+ const m = INJECT_RE.exec(String(src ?? ''))
112
+ if (!m) return { declared: false, empty: false, raw: null }
113
+ const raw = m[1]
114
+ const empty = raw.replace(/\s+/g, '') === '[]'
115
+ return { declared: true, empty, raw }
116
+ }
117
+
118
+ function depsOf(pkg) {
119
+ const deps = pkg?.dependencies
120
+ return deps && typeof deps === 'object' ? Object.keys(deps) : []
121
+ }
122
+
123
+ function depAllowed(dep, cfg) {
124
+ const name = String(dep)
125
+ if (name.startsWith('node:') || name === 'fs' || name === 'path') return true // 防御性:builtin 不应出现在 dependencies
126
+ if (DEFAULT_ALLOWLIST_PREFIXES.some(p => name.startsWith(p))) return true
127
+ return Array.isArray(cfg.allowlist) && cfg.allowlist.includes(name)
128
+ }
129
+
130
+ /**
131
+ * 读取插件目录模型(只读)。
132
+ * @returns {{abs:string, pkg:object|null, manifest:object|null, entry:object|null, files:string[], scan:object|null}}
133
+ */
134
+ export function readModel(dir, opts = {}) {
135
+ const abs = path.resolve(String(dir ?? ''))
136
+ const pkgFile = resolvePluginFile(abs, 'package.json')
137
+ const pkg = pkgFile ? readJson(pkgFile, null) : null
138
+ const manifestFile = opts.manifest === undefined ? resolvePluginFile(abs, 'manifest.json') : null
139
+ const manifest = opts.manifest ?? (manifestFile ? readJson(manifestFile, null) : null)
140
+ let entry = null
141
+ for (const rel of entryCandidates(pkg ?? {}, manifest)) {
142
+ const file = resolvePluginFile(abs, rel)
143
+ if (!file) continue
144
+ try {
145
+ const st = fs.statSync(file)
146
+ if (!st.isFile()) continue
147
+ const src = fs.readFileSync(file, 'utf8')
148
+ entry = { rel, file, src, bytes: st.size, mtimeMs: st.mtimeMs, sha256: sha256(src) }
149
+ break
150
+ } catch { /* 试下一个候选 */ }
151
+ }
152
+ let scan = null
153
+ if (entry) {
154
+ try { scan = scanSource(entry.src) } catch { scan = { imports: [], warnings: [{ reason: 'scan-error' }], error: true } }
155
+ }
156
+ return { abs, pkg, manifest, entry, files: listFiles(abs), scan }
157
+ }
158
+
159
+ /** 目录的静态评分等级(复用 scorer 的同一套数学)。 */
160
+ function gradeOfModel(model) {
161
+ if (!model.entry) return { grade: 'E', S: 100, veto: false, degraded: true, reasons: ['no-entry-file'], signals: [] }
162
+ const mapped = importsToSignals(model.scan, model.pkg ?? {})
163
+ const scored = scoreScan(mapped.signals, { ...(model.pkg ?? {}), __parseErrors: (model.scan?.warnings ?? []).length })
164
+ return { ...scored, signals: mapped.signals.map(s => ({ id: s.id, weight: s.weight })) }
165
+ }
166
+
167
+ // ─────────────────────────────── selfCheck ───────────────────────────────
168
+
169
+ /**
170
+ * 静态自检(契约 5.5):ctx.effect 包裹 / 依赖 allow-list / inject 最小化 /
171
+ * 无裸定时器 / 入口存在。只读、同步、不写盘。
172
+ */
173
+ export function selfCheckOf(model, cfg) {
174
+ const findings = []
175
+ const add = (id, level, message, evidence = null) => findings.push({ id, level, message, evidence })
176
+ const src = model.entry?.src ?? ''
177
+ const effect = EFFECT_RE.test(src)
178
+ const provide = PROVIDE_RE.test(src)
179
+
180
+ if (!model.entry) {
181
+ add('entry-missing', 'block', `no resolvable entry file under ${model.abs}`)
182
+ } else {
183
+ add('entry-ok', 'info', `entry=${model.entry.rel}`, { bytes: model.entry.bytes, sha256: model.entry.sha256 })
184
+ }
185
+
186
+ if (!model.pkg) {
187
+ add('manifest-missing', 'block', 'package.json missing or unreadable')
188
+ } else {
189
+ const deps = depsOf(model.pkg)
190
+ const bad = deps.filter(d => !depAllowed(d, cfg))
191
+ if (bad.length > 0) {
192
+ add('deps-not-allowed', 'block', `dependencies outside allow-list: ${bad.join(', ')}`, { deps: bad })
193
+ } else {
194
+ add('deps-ok', 'info', deps.length > 0 ? `dependencies allow-listed: ${deps.join(', ')}` : 'no runtime dependencies', { deps })
195
+ }
196
+ }
197
+
198
+ if (!effect) add('no-effect-wrap', 'block', 'ctx.effect(...) not found — services/timers must be disposable')
199
+ else add('effect-ok', 'info', 'ctx.effect(...) present')
200
+ if (!provide) add('no-provide', 'block', 'ctx.provide(...) not found — plugin provides no service')
201
+
202
+ const inject = parseInject(src)
203
+ if (!inject.declared) add('inject-missing', 'block', 'module must export inject (hard deps only; middle-tier: inject = [])')
204
+ else if (!inject.empty) add('inject-not-minimal', 'warn', `inject is not empty (${inject.raw}) — declare only hard deps`, { inject: inject.raw })
205
+ else add('inject-minimal', 'info', 'inject = []')
206
+
207
+ const timers = findTimers(src)
208
+ if (timers.length === 0) add('timer-clean', 'info', 'no bare timers')
209
+ else if (!effect) add('bare-timer', 'block', `timers without any ctx.effect cleanup: ${timers.map(t => `${t.fn}@${t.line}`).join(',')}`, { timers })
210
+ else add('bare-timer-unwrapped', 'warn', 'timers found; ctx.effect present but static scan cannot prove each timer is registered inside it', { timers })
211
+
212
+ if (model.pkg?.dsh?.hotReload === false) {
213
+ add('hotreload-veto', 'warn', 'package.json dsh.hotReload === false → static grade is E (veto)')
214
+ }
215
+
216
+ const ok = !findings.some(f => f.level === 'block')
217
+ return { ok, grade: gradeOfModel(model).grade, dir: model.abs, findings }
218
+ }
219
+
220
+ // ─────────────────────────────── gates ───────────────────────────────
221
+
222
+ function makeGates(model, cfg, opts = {}) {
223
+ const gates = []
224
+ const facts = opts.facts ?? null
225
+ // 'load' = 装载前静态预检(默认,host facts 尚不存在);'promote' = 晋升裁决(必须 host facts)。
226
+ const stage = opts.stage === 'promote' ? 'promote' : 'load'
227
+ const blockingOnUnknown = cfg.blockingOnUnknown !== false
228
+ const add = (id, gate, verdict, detail, extra = {}) => {
229
+ const ok = verdict === 'pass'
230
+ || verdict === 'skip'
231
+ || (verdict === 'unknown' && !blockingOnUnknown)
232
+ gates.push({ id, gate, verdict, ok, detail, ...extra })
233
+ }
234
+
235
+ const pkg = model.pkg
236
+ const src = model.entry?.src ?? ''
237
+ const hasSrc = typeof model.entry?.src === 'string'
238
+
239
+ // G1 manifest 字段
240
+ if (!pkg || typeof pkg !== 'object') {
241
+ add('G1', 'manifest-fields', 'fail', 'package.json missing/unreadable')
242
+ } else if (typeof pkg.name !== 'string' || pkg.name.trim() === '') {
243
+ add('G1', 'manifest-fields', 'fail', 'missing package.json name')
244
+ } else if (typeof pkg.version !== 'string' || pkg.version.trim() === '') {
245
+ add('G1', 'manifest-fields', 'fail', `${pkg.name}: missing version`)
246
+ } else if (pkg.type !== undefined && pkg.type !== 'module') {
247
+ add('G1', 'manifest-fields', 'fail', `${pkg.name}@${pkg.version}: type must be "module" (got ${JSON.stringify(pkg.type)})`)
248
+ } else {
249
+ add('G1', 'manifest-fields', 'pass', `${pkg.name}@${pkg.version} (type=${pkg.type ?? 'module'})`)
250
+ }
251
+
252
+ // G2 入口存在
253
+ if (model.entry) add('G2', 'entry-exists', 'pass', `${model.entry.rel} (${model.entry.bytes}B)`)
254
+ else add('G2', 'entry-exists', 'fail', 'no entry file matched exports/module/main/index.js')
255
+
256
+ // G3 无 eval/new Function
257
+ if (!hasSrc) add('G3', 'static-danger', 'unknown', 'no entry source to inspect')
258
+ else {
259
+ const sites = findEvalSites(src)
260
+ if (sites.length > 0) add('G3', 'static-danger', 'fail', `eval()/new Function() at line(s) ${sites.map(s => s.line).join(',')}`, { sites })
261
+ else add('G3', 'static-danger', 'pass', 'no eval()/new Function() found')
262
+ }
263
+
264
+ // G4 无裸 child_process(import 层;不做调用层)
265
+ if (!model.scan) add('G4', 'no-bare-child-process', 'unknown', 'no import scan (entry unreadable)')
266
+ else {
267
+ const hits = model.scan.imports.filter(i => CHILD_PROCESS.has(i.specifier))
268
+ if (hits.length > 0) {
269
+ add('G4', 'no-bare-child-process', 'fail', `child_process imported at line(s) ${hits.map(h => h.line).join(',')}`, { imports: hits })
270
+ } else {
271
+ add('G4', 'no-bare-child-process', 'pass', 'no child_process import (import-layer only)')
272
+ }
273
+ }
274
+
275
+ // G5 依赖 allow-list
276
+ if (!pkg || typeof pkg !== 'object') {
277
+ add('G5', 'deps-allowlist', 'unknown', 'no manifest to read dependencies from')
278
+ } else {
279
+ const deps = depsOf(pkg)
280
+ const bad = deps.filter(d => !depAllowed(d, cfg))
281
+ add('G5', 'deps-allowlist', bad.length ? 'fail' : 'pass',
282
+ bad.length
283
+ ? `not allow-listed: ${bad.join(', ')} (allowed: @deepseek-ai/* + config.allowlist)`
284
+ : (deps.length ? `allow-listed: ${deps.join(', ')}` : 'no runtime dependencies'),
285
+ { deps, disallowed: bad })
286
+ }
287
+
288
+ // G6 资源闭合(裸定时器必须有 ctx.effect;静态近似)
289
+ if (!hasSrc) add('G6', 'resource-containment', 'unknown', 'no entry source to inspect')
290
+ else {
291
+ const timers = findTimers(src)
292
+ const effect = EFFECT_RE.test(src)
293
+ if (timers.length === 0) add('G6', 'resource-containment', 'pass', 'no bare timers')
294
+ else if (!effect) add('G6', 'resource-containment', 'fail', `timers without ctx.effect: ${timers.map(t => `${t.fn}@${t.line}`).join(',')}`, { timers })
295
+ else add('G6', 'resource-containment', 'pass', `timer(s) present with ctx.effect (approximate): ${timers.map(t => `@${t.line}`).join(',')}`, { approximate: true, timers })
296
+ }
297
+
298
+ // G7 豁免诚实性
299
+ if (pkg?.dsh?.acceptRisk === true) {
300
+ const exempted = pkg?.dsh?.exempted
301
+ const honest = Array.isArray(exempted) && exempted.length > 0
302
+ && exempted.every(e => e && typeof e.gate === 'string' && String(e.reason ?? '').trim() !== '')
303
+ add('G7', 'exemption-honesty', honest ? 'pass' : 'fail',
304
+ honest ? `${exempted.length} explicit exemption(s)` : 'dsh.acceptRisk=true without explicit {gate,reason} exemptions')
305
+ } else {
306
+ add('G7', 'exemption-honesty', 'pass', 'no acceptRisk claim')
307
+ }
308
+
309
+ // G8 构建脚本闭合
310
+ const scripts = pkg?.scripts ?? {}
311
+ const present = BUILD_SCRIPTS.filter(s => typeof scripts[s] === 'string')
312
+ if (present.length === 0) add('G8', 'build-scripts', 'pass', 'no install-time build scripts')
313
+ else {
314
+ const approved = Array.isArray(pkg?.dsh?.buildApproved) ? pkg.dsh.buildApproved : []
315
+ const missing = present.filter(s => !approved.includes(s))
316
+ add('G8', 'build-scripts', missing.length ? 'fail' : 'pass',
317
+ missing.length ? `unapproved install scripts: ${missing.join(', ')}` : `approved: ${present.join(', ')}`,
318
+ { present, missing })
319
+ }
320
+
321
+ // G9 秘密卫生
322
+ if (!hasSrc) add('G9', 'secret-hygiene', 'unknown', 'no entry source to inspect')
323
+ else {
324
+ const hits = findSecrets(src)
325
+ add('G9', 'secret-hygiene', hits.length ? 'fail' : 'pass', hits.length ? `hardcoded secret pattern(s): ${hits.join(', ')}` : 'clean', { hits })
326
+ }
327
+
328
+ // G10 bundle patch 声明与文件一致
329
+ const patchRel = pkg?.dsh?.bundle?.patch
330
+ if (typeof patchRel !== 'string' || patchRel === '') {
331
+ add('G10', 'bundle-patch', 'skip', 'not a bundle (no dsh.bundle.patch)')
332
+ } else {
333
+ // The declared patch is plugin-relative and must stay inside the plugin root.
334
+ const patchFile = resolvePluginFile(model.abs, patchRel)
335
+ const ok = patchFile !== null
336
+ add('G10', 'bundle-patch', ok ? 'pass' : 'fail',
337
+ ok ? patchRel : `declared bundle patch missing/unsafe: ${patchRel}`, { patch: patchRel })
338
+ }
339
+
340
+ // G11 激活证据:静态预检查看不了激活(load 之后才可观测)→ deferred/SKIP(ci-gate G7 同构);
341
+ // stage='promote' 时必须给出 host facts,否则 UNKNOWN 阻断(fail-closed)。
342
+ if (stage === 'load' && !facts) {
343
+ add('G11', 'activation-evidence', 'skip', 'deferred: activation is observed only after load')
344
+ } else if (!facts || typeof facts !== 'object') {
345
+ add('G11', 'activation-evidence', 'unknown', 'no host facts (activation not observed)')
346
+ } else if (facts.application !== 'applied') {
347
+ add('G11', 'activation-evidence', 'fail', `facts.application=${JSON.stringify(facts.application ?? null)} (expected "applied")`)
348
+ } else if (!Number.isFinite(facts.observedAt) || facts.observedAt <= 0) {
349
+ add('G11', 'activation-evidence', 'unknown', 'facts.observedAt missing/invalid; freshness cannot be established')
350
+ } else if (model.entry && facts.observedAt < model.entry.mtimeMs) {
351
+ add('G11', 'activation-evidence', 'fail', `facts stale: observedAt=${facts.observedAt} < entry.mtimeMs=${model.entry.mtimeMs}`)
352
+ } else {
353
+ add('G11', 'activation-evidence', 'pass', 'facts.application=applied and fresh enough')
354
+ }
355
+
356
+ // G12 分数可复算:同样只在有 host facts 时才可判定。
357
+ if (stage === 'load' && (!facts || !Array.isArray(facts.signals) || typeof facts.score !== 'number')) {
358
+ add('G12', 'score-reproducible', 'skip', 'deferred: persisted facts exist only after load')
359
+ } else if (!facts || !Array.isArray(facts.signals) || typeof facts.score !== 'number') {
360
+ add('G12', 'score-reproducible', 'unknown', 'no persisted facts.signals/score')
361
+ } else {
362
+ const recomputed = scoreScan(facts.signals, { dsh: pkg?.dsh }).S
363
+ add('G12', 'score-reproducible', recomputed === facts.score ? 'pass' : 'fail',
364
+ `stored=${facts.score} recomputed=${recomputed}`)
365
+ }
366
+
367
+ const count = (v) => gates.filter(g => g.verdict === v).length
368
+ const summary = {
369
+ total: gates.length,
370
+ pass: count('pass'),
371
+ fail: count('fail'),
372
+ unknown: count('unknown'),
373
+ skip: count('skip'),
374
+ }
375
+ return {
376
+ pass: gates.every(g => g.ok),
377
+ gates,
378
+ summary,
379
+ blockingOnUnknown,
380
+ dir: model.abs,
381
+ }
382
+ }
383
+
384
+ // ─────────────────────────────── evidence ───────────────────────────────
385
+
386
+ function evidenceOf(model, cfg) {
387
+ const scan = model.scan ?? { imports: [], warnings: [] }
388
+ const mapped = model.entry ? importsToSignals(scan, model.pkg ?? {}) : { signals: [] }
389
+ const self = selfCheckOf(model, cfg)
390
+ const gs = makeGates(model, cfg, {})
391
+ return {
392
+ plugin: model.pkg
393
+ ? {
394
+ name: model.pkg.name ?? null,
395
+ version: model.pkg.version ?? null,
396
+ type: model.pkg.type ?? null,
397
+ dsh: model.pkg.dsh ?? null,
398
+ dependencies: model.pkg.dependencies ?? {},
399
+ }
400
+ : null,
401
+ entry: model.entry
402
+ ? { file: model.entry.file, rel: model.entry.rel, bytes: model.entry.bytes, sha256: model.entry.sha256, mtimeMs: model.entry.mtimeMs }
403
+ : null,
404
+ files: model.files,
405
+ imports: {
406
+ count: scan.imports.length,
407
+ items: scan.imports.map(i => ({ specifier: i.specifier, kind: i.kind, line: i.line })),
408
+ warnings: scan.warnings,
409
+ coverage: 'import-only',
410
+ },
411
+ resources: {
412
+ timers: model.entry ? findTimers(model.entry.src) : [],
413
+ evalSites: model.entry ? findEvalSites(model.entry.src) : [],
414
+ secrets: model.entry ? findSecrets(model.entry.src) : [],
415
+ hasEffect: model.entry ? EFFECT_RE.test(model.entry.src) : false,
416
+ hasProvide: model.entry ? PROVIDE_RE.test(model.entry.src) : false,
417
+ deps: depsOf(model.pkg),
418
+ signals: mapped.signals.map(s => ({ id: s.id, weight: s.weight })),
419
+ },
420
+ checks: {
421
+ selfCheck: self.findings.map(f => ({ id: f.id, level: f.level })),
422
+ gates: gs.gates.map(g => ({ id: g.id, gate: g.gate, verdict: g.verdict, ok: g.ok })),
423
+ },
424
+ }
425
+ }
426
+
427
+ // ─────────────────────────────── suggestFix ───────────────────────────────
428
+
429
+ function patch(target, yaml, why, extra = {}) {
430
+ return { target, yaml, why, ...extra }
431
+ }
432
+
433
+ function suggestFixOf(model, cfg, opts = {}) {
434
+ const self = selfCheckOf(model, cfg)
435
+ const gs = makeGates(model, cfg, opts)
436
+ const gate = (id) => gs.gates.find(g => g.id === id)
437
+ const finding = (id) => self.findings.find(f => f.id === id)
438
+ const entryRel = model.entry?.rel ?? 'index.js'
439
+ const patches = []
440
+ const seen = new Set()
441
+ const add = (p) => {
442
+ const key = `${p.target}\u0000${p.why}`
443
+ if (seen.has(key)) return
444
+ seen.add(key)
445
+ patches.push(p)
446
+ }
447
+
448
+ const g1 = gate('G1')
449
+ if (g1 && !g1.ok && g1.verdict === 'fail') {
450
+ add(patch('package.json',
451
+ JSON.stringify({ name: model.pkg?.name ?? '@local/<plugin-name>', version: '1.0.0', type: 'module' }, null, 2),
452
+ `G1 manifest-fields: ${g1.detail} — merge these fields into the existing package.json; do not replace the file`,
453
+ { apply: 'merge', mergeInto: 'package.json' }))
454
+ }
455
+
456
+ const g2 = gate('G2')
457
+ if (g2 && !g2.ok) {
458
+ add(patch('package.json',
459
+ JSON.stringify({ exports: { '.': './index.js' } }, null, 2),
460
+ `G2 entry-exists: ${g2.detail} — create the entry file and merge this exports field`,
461
+ { apply: 'merge', mergeInto: 'package.json' }))
462
+ }
463
+
464
+ const g3 = gate('G3')
465
+ if (g3 && g3.verdict === 'fail') {
466
+ add(patch(entryRel,
467
+ '# remove eval()/new Function(): use a static branch, a schema, or a declared capability service\n# (healer only suggests; the code change is a manual edit)',
468
+ `G3 static-danger: ${g3.detail}`))
469
+ }
470
+
471
+ const g4 = gate('G4')
472
+ if (g4 && g4.verdict === 'fail') {
473
+ add(patch(entryRel,
474
+ '# drop the child_process import: delegate process work to the declared capability\n# (fangForker mother-side) or run this code in the container zone',
475
+ `G4 no-bare-child-process: ${g4.detail}`))
476
+ }
477
+
478
+ const g5 = gate('G5')
479
+ if (g5 && g5.verdict === 'fail') {
480
+ const bad = g5.disallowed ?? []
481
+ const yaml = [
482
+ '# merge into the plugin row config in cordis.patch.yml',
483
+ 'config:',
484
+ ' allowlist:',
485
+ ...bad.map(d => ` - ${JSON.stringify(d)}`),
486
+ ].join('\n')
487
+ add(patch('cordis.patch.yml', yaml, `G5 deps-allowlist: ${g5.detail}`))
488
+ }
489
+
490
+ const g6 = gate('G6')
491
+ if (g6 && g6.verdict === 'fail') {
492
+ add(patch(entryRel,
493
+ '# register every timer through ctx.effect so it is disposed with the fiber:\n# ctx.effect(() => { const t = setInterval(fn, ms); return () => clearInterval(t) })',
494
+ `G6 resource-containment: ${g6.detail}`))
495
+ }
496
+
497
+ const g8 = gate('G8')
498
+ if (g8 && g8.verdict === 'fail') {
499
+ // Never auto-approve install scripts: that would turn a security finding into a
500
+ // one-line bypass. The placeholder requires a human review step.
501
+ add(patch('package.json',
502
+ JSON.stringify({
503
+ dsh: {
504
+ buildApproved: ['<script-name-after-review>'],
505
+ },
506
+ }, null, 2),
507
+ `G8 build-scripts: ${g8.detail} — review each install script; only merge names you explicitly approve. An auto-filled buildApproved list would bypass this gate.`,
508
+ { apply: 'manual-review', mergeInto: 'package.json', requiresHumanReview: true }))
509
+ }
510
+
511
+ const g9 = gate('G9')
512
+ if (g9 && g9.verdict === 'fail') {
513
+ add(patch(entryRel,
514
+ '# remove the hardcoded credential; read it from ctx.config / environment at runtime',
515
+ `G9 secret-hygiene: ${g9.detail}`))
516
+ }
517
+
518
+ const g10 = gate('G10')
519
+ if (g10 && g10.verdict === 'fail') {
520
+ const declared = typeof g10.patch === 'string' ? g10.patch : ''
521
+ const safeTarget = declared && !path.isAbsolute(declared) && !declared.split(/[\\/]/).includes('..')
522
+ ? declared
523
+ : 'cordis.patch.yml'
524
+ add(patch(safeTarget,
525
+ '# create the declared bundle patch file; the declaration must stay inside the plugin root',
526
+ `G10 bundle-patch: ${g10.detail}`,
527
+ { apply: 'manual-create', declaredPatch: declared || null }))
528
+ }
529
+
530
+ const g7 = gate('G7')
531
+ if (g7 && g7.verdict === 'fail') {
532
+ add(patch('package.json',
533
+ JSON.stringify({ dsh: { exempted: [{ gate: '<gate-id>', reason: 'reviewed: <why this risk is acceptable>' }] } }, null, 2),
534
+ `G7 exemption-honesty: ${g7.detail} — merge only after a real review; a placeholder exemption must not be copied blindly`,
535
+ { apply: 'manual-review', mergeInto: 'package.json', requiresHumanReview: true }))
536
+ }
537
+
538
+ const fx = finding('inject-missing')
539
+ if (fx) {
540
+ add(patch(entryRel,
541
+ '# add at module top level (middle-tier plugins declare no hard deps):\n# export const inject = []',
542
+ `module shape: ${fx.message}`))
543
+ }
544
+ const fe = finding('no-effect-wrap')
545
+ if (fe) {
546
+ add(patch(entryRel,
547
+ '# wrap service registration: ctx.effect(() => ctx.provide(SERVICE.<key>, service))',
548
+ `module shape: ${fe.message}`))
549
+ }
550
+
551
+ const before = gradeOfModel(model)
552
+ let afterGrade = before.grade
553
+ const projectedGates = []
554
+ if (model.entry) {
555
+ const addressed = new Set()
556
+ if (g4 && g4.verdict === 'fail') {
557
+ addressed.add('S1')
558
+ projectedGates.push('G4')
559
+ }
560
+ const kept = before.signals.filter(s => !addressed.has(familyOf(s.id)))
561
+ const projected = scoreScan(kept, {
562
+ ...(model.pkg ?? {}),
563
+ __parseErrors: (model.scan?.warnings ?? []).length,
564
+ })
565
+ afterGrade = projected.grade
566
+ }
567
+
568
+ return {
569
+ patches,
570
+ before: { grade: before.grade, S: before.S },
571
+ after: {
572
+ grade: afterGrade,
573
+ note: projectedGates.length > 0
574
+ ? 'projected only by removing G4/S1 signals; G3/G5/G6/G7/G8/G9/G10 are not represented and host-fact gates (G11/G12) are unaffected'
575
+ : 'static projection only; no score-affecting patch was applied and host-fact gates (G11/G12) are unaffected',
576
+ projectedGates,
577
+ },
578
+ dir: model.abs,
579
+ applied: false,
580
+ }
581
+ }
582
+
583
+ // ─────────────────────────────── plugin ───────────────────────────────
584
+
585
+ export function apply(ctx, config) {
586
+ const gate = roleGate('healer', { cfgRole: config?.role, logger: ctx.logger })
587
+ // v2 deployment matrix: this plugin is not deployed in this role — register nothing.
588
+ if (!gate.active) return
589
+ const cfg = {
590
+ blockingOnUnknown: true,
591
+ reservedIds: [],
592
+ allowlist: [],
593
+ ...(config ?? {}),
594
+ }
595
+ const normalized = {
596
+ blockingOnUnknown: cfg.blockingOnUnknown !== false,
597
+ reservedIds: Array.isArray(cfg.reservedIds) ? cfg.reservedIds.map(String) : [],
598
+ allowlist: Array.isArray(cfg.allowlist) ? cfg.allowlist.map(String) : [],
599
+ }
600
+
601
+ const audit = (kind, data) => {
602
+ try { safeGet(ctx, SERVICE.auditor)?.append?.(kind, data) } catch { /* 审计缺失不得影响自检 */ }
603
+ }
604
+
605
+ const service = {
606
+ policy: { ...normalized },
607
+
608
+ /** 自检:只读,返回 {ok, grade, findings[]}(契约 5.5)。 */
609
+ selfCheck(dir, opts = {}) {
610
+ const model = readModel(dir, opts)
611
+ const out = selfCheckOf(model, normalized)
612
+ audit(AUDIT.SCORE, {
613
+ component: name,
614
+ check: 'self-check',
615
+ dir: out.dir,
616
+ ok: out.ok,
617
+ grade: out.grade,
618
+ findings: out.findings.length,
619
+ })
620
+ return out
621
+ },
622
+
623
+ /** 结构化证据 JSON(契约 5.5):{plugin, entry, files, imports, resources, checks}。 */
624
+ evidence(dir, opts = {}) {
625
+ return evidenceOf(readModel(dir, opts), normalized)
626
+ },
627
+
628
+ /**
629
+ * G1–G12 门禁(契约 5.5):{pass, gates:[{id, ok, detail, verdict}], summary}。
630
+ * opts.stage: 'load'(默认,静态预检,G11/G12 deferred/SKIP)| 'promote'(G11/G12 必须有 facts,否则 UNKNOWN 阻断)。
631
+ * opts.facts: host 证据 {application, observedAt, signals, score}(见 CONTRACTS 5.5)。
632
+ */
633
+ gates(dir, opts = {}) {
634
+ const out = makeGates(readModel(dir, opts), normalized, opts)
635
+ audit(AUDIT.SCORE, {
636
+ component: name,
637
+ check: 'gates',
638
+ dir: out.dir,
639
+ pass: out.pass,
640
+ fail: out.summary.fail,
641
+ unknown: out.summary.unknown,
642
+ })
643
+ return out
644
+ },
645
+
646
+ /** 补丁建议:{patches:[{target,yaml,why}], before, after};**不写盘**(契约 5.5)。 */
647
+ suggestFix(dir, opts = {}) {
648
+ const out = suggestFixOf(readModel(dir, opts), normalized, opts)
649
+ audit(AUDIT.SCORE, {
650
+ component: name,
651
+ check: 'suggest-fix',
652
+ dir: out.dir,
653
+ patches: out.patches.length,
654
+ before: out.before.grade,
655
+ after: out.after.grade,
656
+ })
657
+ return out
658
+ },
659
+ }
660
+
661
+ ctx.effect(() => ctx.provide(SERVICE.healer, service))
662
+ }
663
+
664
+ export const _internals = { selfCheckOf, makeGates, evidenceOf, suggestFixOf, readModel, gradeOfModel }