dsh-agent-control-center 0.3.1 → 0.4.0

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.
@@ -0,0 +1,862 @@
1
+ /**
2
+ * L · Health — one read-only, evidence-backed answer about the four host facts a
3
+ * control-center page cannot infer by itself:
4
+ *
5
+ * - `pluginManager.listPlugins()`: which plugin rows the running profile
6
+ * owns, and why some rows cannot be changed through its patch;
7
+ * - `settings.describe({ redactSecrets: true })`: settings namespaces as
8
+ * metadata only (id, revision, auto-generate, user-value presence and secret
9
+ * key names). `schema`, `value`, `base` and `user` never leave the module;
10
+ * - a static text scan of the client bundles under
11
+ * `$DSH_HOME/profiles/<profile>/node_modules/`: literal `settings.section`
12
+ * registrations, plus duplicate ids across packages;
13
+ * - the compatibility verdict, preferring a live `core.compatibility.current()`
14
+ * and otherwise evaluating the same core/compat layer locally.
15
+ *
16
+ * Every method answers `{ available: true, ... }` or
17
+ * `{ available: false, reason, hint }`; a missing or broken host service
18
+ * degrades that one answer and never throws. The module performs no writes,
19
+ * starts no command, and makes no network request. Scan bounds and the declared
20
+ * limitations of the static scan are part of the response so a page can state
21
+ * exactly what was proven.
22
+ *
23
+ * @module dsh-agent-control-center/modules/health
24
+ */
25
+ import { readdir, readFile, stat } from 'node:fs/promises'
26
+ import os from 'node:os'
27
+ import path from 'node:path'
28
+
29
+ /** Module id, also the prefix of every method name. */
30
+ const MODULE_ID = 'health'
31
+ /** Navigation order: after diagnostics (70) and before templates (80). */
32
+ const MODULE_ORDER = 75
33
+ /** A plugin row list is small; the cap bounds a pathological host answer. */
34
+ const MAX_PLUGIN_ITEMS = 1000
35
+ /** One anomaly entry per duplicate or unaddressable row, bounded. */
36
+ const MAX_ANOMALIES = 200
37
+ /** Settings namespaces the browser can render; a profile has far fewer. */
38
+ const MAX_NAMESPACES = 200
39
+ /** Secret key names reported per namespace. */
40
+ const MAX_SECRET_KEYS = 20
41
+ /** Compatibility reasons copied from the verdict. */
42
+ const MAX_REASONS = 100
43
+ /** Files read by the static scan. */
44
+ const MAX_SCAN_FILES = 200
45
+ /** Largest client bundle the scan reads, in bytes. */
46
+ const MAX_BUNDLE_BYTES = 4 * 1024 * 1024
47
+ /** Total bytes read across bundles; a scan is a bounded, one-shot read. */
48
+ const MAX_TOTAL_BUNDLE_BYTES = 24 * 1024 * 1024
49
+ /** How far after `settings.section` a literal `name:` / `name =` is searched. */
50
+ const CANDIDATE_BUNDLES = [
51
+ 'client.js',
52
+ 'index.js',
53
+ 'lib/client.js',
54
+ 'lib/client/index.js',
55
+ 'dist/client.js',
56
+ 'dist/client/index.js',
57
+ ]
58
+ const SECTION_WINDOW = 600
59
+ /** Settings-section entries the response carries; keeps the payload < 2 MiB. */
60
+ const MAX_SECTION_ENTRIES = 800
61
+ /** This plugin's own settings section id, mirrored from `src/client/app.js`. */
62
+ const OWN_SECTION_ID = 'agent-control-center'
63
+ /** Owner label for that row: the scan cannot read a linked checkout outside the fence. */
64
+ const OWN_OWNER = 'dsh-agent-control-center'
65
+ /** Duplicate-id findings the response carries. */
66
+ const MAX_CONFLICTS = 100
67
+ /** The literal a built client bundle must contain to register a settings section. */
68
+ const SECTION_TOKEN = 'settings.section'
69
+ /** Both `name: 'id'` and `name = "id"` shapes; single and double quotes. */
70
+ const SECTION_NAME = /\bname\s*[:=]\s*(['"])([^'"\r\n]{1,200})\1/g
71
+ /** Section ids sit beside the slot name: `{ name: 'settings.section', id: 'websearch' }`. */
72
+ const SECTION_ID = /\bid\s*[:=]\s*(['"])([^'"\r\n]{1,200})\1/g
73
+ /** Own settings namespace reported for this plugin row. */
74
+ const OWN_NS = 'acc'
75
+ /** Static scan limitation, stated in every successful section response. */
76
+ const STATIC_SCAN_NOTE = '静态扫描:只覆盖构建产物内的字面量注册,可能漏检动态生成的 id'
77
+ /** Settings evidence source and the explicit no-value promise. */
78
+ const SETTINGS_NOTE =
79
+ '来源 settings.describe({ redactSecrets:true }):只返回命名空间元数据与 secret 键名,schema/value/base/user 原值不进入响应'
80
+
81
+ /**
82
+ * @param {unknown} value
83
+ * @returns {boolean}
84
+ */
85
+ function isPlainObject(value) {
86
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
87
+ }
88
+
89
+ /**
90
+ * @param {unknown} error
91
+ * @returns {string} a short, readable failure text
92
+ */
93
+ function errorMessage(error) {
94
+ if (error !== null && typeof error === 'object' && typeof (/** @type {Record<string, unknown>} */ (error).message) === 'string') {
95
+ return /** @type {string} */ (/** @type {Record<string, unknown>} */ (error).message)
96
+ }
97
+ return String(error)
98
+ }
99
+
100
+ /**
101
+ * @param {unknown} error
102
+ * @returns {string} the errno-style code, when the error carries one
103
+ */
104
+ function errorCode(error) {
105
+ if (error !== null && typeof error === 'object') {
106
+ const code = /** @type {Record<string, unknown>} */ (error).code
107
+ if (typeof code === 'string' && code.length > 0) return code
108
+ }
109
+ return ''
110
+ }
111
+
112
+ /**
113
+ * Whether a namespace's `user` layer carries at least one user-defined value.
114
+ * The layer itself is never returned; only this boolean is.
115
+ * @param {unknown} user
116
+ * @returns {boolean}
117
+ */
118
+ function hasUserValue(user) {
119
+ if (typeof user === 'string') return user.length > 0
120
+ return isPlainObject(user) && Object.keys(user).length > 0
121
+ }
122
+
123
+ /**
124
+ * Only the names of a schema-declared secret slot, joined with dots. Values
125
+ * never appear in a host descriptor, so a name is the most the page needs.
126
+ * @param {unknown} slotPath
127
+ * @returns {string}
128
+ */
129
+ function secretPathKey(slotPath) {
130
+ if (typeof slotPath === 'string') return slotPath
131
+ if (!Array.isArray(slotPath)) return ''
132
+ const parts = []
133
+ for (const part of slotPath) {
134
+ if (typeof part === 'string' && part.length > 0) parts.push(part)
135
+ }
136
+ return parts.join('.')
137
+ }
138
+
139
+ /**
140
+ * Serialize one value only to test whether it is already in redacted form. A
141
+ * value JSON cannot represent is reported as unverified.
142
+ * @param {unknown} value
143
+ * @returns {string | null}
144
+ */
145
+ function serializable(value) {
146
+ try {
147
+ const text = JSON.stringify(value)
148
+ return typeof text === 'string' ? text : null
149
+ } catch {
150
+ return null
151
+ }
152
+ }
153
+
154
+ /**
155
+ * @param {Record<string, any>} core
156
+ * @returns {Record<string, any>} the health module record
157
+ */
158
+ export default function createModule(core) {
159
+ const { util, errors } = core
160
+
161
+ /**
162
+ * Read one host service. `ctx.get` throws for an unmounted service in the
163
+ * Cordis contract, so a missing service is an expected answer, not a failure.
164
+ * @param {string} name
165
+ * @returns {any}
166
+ */
167
+ function service(name) {
168
+ try {
169
+ return core.ctx.get(name)
170
+ } catch {
171
+ return undefined
172
+ }
173
+ }
174
+
175
+ /**
176
+ * A degradation record. Health methods never throw on a missing host fact;
177
+ * the reason states what could not be read and the hint names the next step.
178
+ * @param {string} reason
179
+ * @param {string} [hint]
180
+ * @returns {Record<string, unknown>}
181
+ */
182
+ function unavailable(reason, hint) {
183
+ return {
184
+ available: false,
185
+ reason: String(reason),
186
+ ...(hint === undefined ? {} : { hint: String(hint) }),
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Health methods accept no parameters. A non-object params bag is a caller
192
+ * bug that reaches the HTTP boundary as a structured 400, not a probe answer.
193
+ * @param {unknown} params
194
+ */
195
+ function assertParams(params) {
196
+ if (params === undefined || params === null) return
197
+ if (!util.isPlainObject(params)) {
198
+ throw errors.badRequest('params 必须是对象', { hint: '健康检查方法不使用参数,传空对象或省略即可' })
199
+ }
200
+ // Prototype-polluting keys are rejected here for the same boundary reason.
201
+ util.paramsObject(params)
202
+ }
203
+
204
+ /**
205
+ * The plugin's own row, as far as `core.config` proves it. The settings
206
+ * namespace is reported even when the row is absent so a page can say what it
207
+ * expected to find.
208
+ * @returns {{ ns: string, declared: boolean, enabled: boolean }}
209
+ */
210
+ function ownRow() {
211
+ const config = core.config
212
+ const declared = isPlainObject(config) && Object.keys(config).length > 0
213
+ return {
214
+ ns: OWN_NS,
215
+ declared,
216
+ enabled: declared && config.enabled !== false,
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Host version a fallback compatibility evaluation may use. Only a version
222
+ * the compatibility layer itself already recorded qualifies; guessing one
223
+ * would turn an unknown host into a claimed-compatible one.
224
+ * @returns {string | null}
225
+ */
226
+ function recordedHostVersion() {
227
+ const compatibility = core.compatibility
228
+ if (!isPlainObject(compatibility)) return null
229
+ if (typeof compatibility.version === 'string' && compatibility.version.length > 0) return compatibility.version
230
+ if (isPlainObject(compatibility.detection) && typeof compatibility.detection.version === 'string' && compatibility.detection.version.length > 0) {
231
+ return compatibility.detection.version
232
+ }
233
+ return null
234
+ }
235
+
236
+ /**
237
+ * Normalize a compatibility verdict to the five facts this module reports.
238
+ * Reason texts are redacted because a host version string can be arbitrary.
239
+ * @param {unknown} verdict
240
+ * @param {string} source
241
+ * @returns {Record<string, unknown>}
242
+ */
243
+ function normalizeVerdict(verdict, source) {
244
+ const reasons = []
245
+ const rawReasons = isPlainObject(verdict) && Array.isArray(verdict.reasons) ? verdict.reasons : []
246
+ for (const reason of rawReasons.slice(0, MAX_REASONS)) {
247
+ if (!isPlainObject(reason)) continue
248
+ reasons.push({
249
+ code: typeof reason.code === 'string' ? reason.code : '',
250
+ severity: reason.severity === 'error' || reason.severity === 'warn' ? reason.severity : 'info',
251
+ text: util.redact(typeof reason.text === 'string' ? reason.text : '', 300),
252
+ })
253
+ }
254
+ return {
255
+ available: true,
256
+ source,
257
+ level: isPlainObject(verdict) && typeof verdict.level === 'string' ? verdict.level : 'unknown',
258
+ version: isPlainObject(verdict) && typeof verdict.version === 'string' ? util.redact(verdict.version, 120) : null,
259
+ readOnly: isPlainObject(verdict) && verdict.readOnly === true,
260
+ reasons,
261
+ }
262
+ }
263
+
264
+ /** @returns {Promise<Record<string, unknown>>} */
265
+ async function pluginsMethod(params) {
266
+ assertParams(params)
267
+ const manager = service('pluginManager')
268
+ if (manager === undefined || manager === null) {
269
+ return unavailable('宿主未提供 pluginManager 服务', '请在 DSH 原生的插件管理页查看当前 profile 的插件行')
270
+ }
271
+ if (typeof manager.listPlugins !== 'function') {
272
+ return unavailable('pluginManager 缺少 listPlugins 方法', '该宿主版本的插件管理服务不提供清单读取;请改用原生插件页')
273
+ }
274
+ let rows
275
+ try {
276
+ rows = await manager.listPlugins()
277
+ } catch (error) {
278
+ return unavailable('读取插件清单失败', util.redact(errorMessage(error), 160))
279
+ }
280
+ if (!Array.isArray(rows)) {
281
+ return unavailable('pluginManager.listPlugins 的返回值不是数组', '宿主接口可能已变更;请提交该宿主版本的接口定义')
282
+ }
283
+
284
+ /** @type {Array<{ entryId: string, moduleName: string, patchId: string | null, readOnlyReason: string | null }>} */
285
+ const items = []
286
+ /** @type {Array<{ kind: string, detail: string }>} */
287
+ const anomalies = []
288
+ /** @type {Map<string, string[]>} */
289
+ const byModuleName = new Map()
290
+ for (const row of rows.slice(0, MAX_PLUGIN_ITEMS)) {
291
+ if (!isPlainObject(row)) continue
292
+ const entryId = util.redact(typeof row.entryId === 'string' ? row.entryId : '', 160)
293
+ const moduleName = util.redact(typeof row.moduleName === 'string' ? row.moduleName : '', 160)
294
+ const patchId = typeof row.patchId === 'string' && row.patchId.length > 0 ? util.redact(row.patchId, 160) : null
295
+ const readOnlyReason = typeof row.readOnlyReason === 'string' && row.readOnlyReason.length > 0 ? util.redact(row.readOnlyReason, 120) : null
296
+ items.push({ entryId, moduleName, patchId, readOnlyReason })
297
+ if (moduleName.length > 0) {
298
+ const ids = byModuleName.get(moduleName)
299
+ if (ids === undefined) byModuleName.set(moduleName, [entryId])
300
+ else ids.push(entryId)
301
+ }
302
+ if (readOnlyReason === 'unaddressable' && anomalies.length < MAX_ANOMALIES) {
303
+ anomalies.push({
304
+ kind: 'unaddressable',
305
+ detail: util.redact(`插件行 ${moduleName || entryId} 无法通过 profile patch 控制(readOnlyReason=unaddressable)`, 400),
306
+ })
307
+ }
308
+ }
309
+ for (const [moduleName, entryIds] of byModuleName) {
310
+ if (entryIds.length < 2 || anomalies.length >= MAX_ANOMALIES) continue
311
+ anomalies.push({
312
+ kind: 'duplicate-module',
313
+ detail: util.redact(`moduleName ${moduleName} 被 ${entryIds.length} 个 entry 重复注册(${entryIds.join(', ')})`, 400),
314
+ })
315
+ }
316
+
317
+ return { available: true, source: 'pluginManager', items, anomalies }
318
+ }
319
+
320
+ /** @returns {Promise<Record<string, unknown>>} */
321
+ async function settingsMethod(params) {
322
+ assertParams(params)
323
+ const own = ownRow()
324
+ const settings = service('settings')
325
+ if (settings === undefined || settings === null || typeof settings.describe !== 'function') {
326
+ return {
327
+ ...unavailable('宿主未提供 settings.describe 服务', '设置页仍需宿主完成命名空间注册;本插件不读取宿主配置值'),
328
+ own,
329
+ redactionVerified: false,
330
+ note: SETTINGS_NOTE,
331
+ }
332
+ }
333
+ let descriptors
334
+ try {
335
+ // RED LINE: without this option `describe()` returns plaintext keys. The
336
+ // option is the only reason the response may carry secret *names* at all.
337
+ descriptors = await settings.describe({ redactSecrets: true })
338
+ } catch (error) {
339
+ return {
340
+ ...unavailable('读取设置描述失败', util.redact(errorMessage(error), 160)),
341
+ own,
342
+ redactionVerified: false,
343
+ note: SETTINGS_NOTE,
344
+ }
345
+ }
346
+ if (!Array.isArray(descriptors)) {
347
+ return {
348
+ ...unavailable('settings.describe 的返回值不是数组', '宿主接口可能已变更;请提交该宿主版本的 settings 类型定义'),
349
+ own,
350
+ redactionVerified: false,
351
+ note: SETTINGS_NOTE,
352
+ }
353
+ }
354
+
355
+ let redactionVerified = true
356
+ let secretsIncomplete = false
357
+ /** @type {Array<{ ns: string, revision: number | null, autoGenerate: boolean, hasValue: boolean, secretKeys: string[] }>} */
358
+ const namespaces = []
359
+ for (const descriptor of descriptors.slice(0, MAX_NAMESPACES)) {
360
+ if (!isPlainObject(descriptor)) {
361
+ redactionVerified = false
362
+ continue
363
+ }
364
+ const ns = typeof descriptor.ns === 'string' ? descriptor.ns : ''
365
+ const emittedNs = util.redact(ns, 200)
366
+ if (emittedNs !== ns) redactionVerified = false
367
+ const secrets = Array.isArray(descriptor.secrets) ? descriptor.secrets : null
368
+ const secretKeys = []
369
+ if (secrets === null) {
370
+ // The host adds the slot list whenever `redactSecrets` is honoured. A
371
+ // minimal host-like double may omit it, so the claim is not failed
372
+ // outright; it is scoped to the slots the service actually returned.
373
+ secretsIncomplete = true
374
+ } else {
375
+ for (const secret of secrets) {
376
+ if (secretKeys.length >= MAX_SECRET_KEYS) break
377
+ const key = util.redact(secretPathKey(isPlainObject(secret) ? secret.path : undefined), 200)
378
+ secretKeys.push(key)
379
+ const payload = serializable(secret)
380
+ if (payload === null || util.redact(payload, payload.length + 1) !== payload) redactionVerified = false
381
+ }
382
+ }
383
+ namespaces.push({
384
+ ns: emittedNs,
385
+ revision: typeof descriptor.revision === 'number' && Number.isFinite(descriptor.revision) ? descriptor.revision : null,
386
+ autoGenerate: descriptor.autoGenerate === true,
387
+ hasValue: hasUserValue(descriptor.user),
388
+ secretKeys,
389
+ })
390
+ }
391
+
392
+ const noteParts = [SETTINGS_NOTE]
393
+ if (!redactionVerified) {
394
+ noteParts.push('检测到未按脱敏形态返回的 secrets(可能是未经 redactSecrets 的宿主),原值已丢弃')
395
+ } else if (secretsIncomplete) {
396
+ noteParts.push('部分命名空间未返回 secrets 槽位列表:脱敏只按已返回的槽位核对')
397
+ }
398
+ return {
399
+ available: true,
400
+ namespaces,
401
+ own,
402
+ redactionVerified,
403
+ note: noteParts.join(';'),
404
+ }
405
+ }
406
+
407
+ /**
408
+ * The DSH home the scan reads. `normalizeConfig` records it on `config`;
409
+ * the environment and the user home are the documented fallbacks.
410
+ * @returns {string}
411
+ */
412
+ function resolveDshHome() {
413
+ const configured = isPlainObject(core.config) ? core.config.dshHome : undefined
414
+ if (typeof configured === 'string' && configured.length > 0) return configured
415
+ const fromEnv = process.env.DSH_HOME
416
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv
417
+ return path.join(os.homedir(), '.dsh')
418
+ }
419
+
420
+ /**
421
+ * A scan target: one package directory under a profile's node_modules.
422
+ * @typedef {{ name: string, dir: string }} ScanPackage
423
+ */
424
+
425
+ /**
426
+ * A profile package entry is normally a directory, but pnpm links some
427
+ * packages as symlinks; both count as a package candidate. `resolveRead`
428
+ * later decides whether the target is admissible.
429
+ * @param {import('node:fs').Dirent} entry
430
+ * @returns {boolean}
431
+ */
432
+ function isPackageEntry(entry) {
433
+ return entry.isDirectory() || entry.isSymbolicLink()
434
+ }
435
+
436
+ /**
437
+ * One-level package discovery. `dsh-*` packages are taken directly; a
438
+ * `@scope` directory contributes every package one level below it. Packages
439
+ * seen in an earlier profile win, so the same shared bundle is not rescanned
440
+ * (and cannot self-conflict) across profiles.
441
+ * @param {string} profilesRoot
442
+ * @returns {Promise<ScanPackage[]>}
443
+ */
444
+ async function discoverPackages(profilesRoot) {
445
+ /** @type {ScanPackage[]} */
446
+ const packages = []
447
+ /** @type {Set<string>} */
448
+ const seen = new Set()
449
+ // Callers turn an absent profiles directory into the documented
450
+ // available:false answer; every other read failure degrades the same way.
451
+ const profileEntries = await readdir(profilesRoot, { withFileTypes: true })
452
+ for (const profile of profileEntries) {
453
+ if (!isPackageEntry(profile)) continue
454
+ const nodeModules = path.join(profilesRoot, profile.name, 'node_modules')
455
+ let entries
456
+ try {
457
+ entries = await readdir(nodeModules, { withFileTypes: true })
458
+ } catch {
459
+ continue
460
+ }
461
+ for (const entry of entries) {
462
+ if (entry.name.startsWith('dsh-') && isPackageEntry(entry)) {
463
+ if (seen.has(entry.name)) continue
464
+ seen.add(entry.name)
465
+ packages.push({ name: entry.name, dir: path.join(nodeModules, entry.name) })
466
+ continue
467
+ }
468
+ if (entry.name.startsWith('@') && isPackageEntry(entry)) {
469
+ let scoped
470
+ try {
471
+ scoped = await readdir(path.join(nodeModules, entry.name), { withFileTypes: true })
472
+ } catch {
473
+ continue
474
+ }
475
+ for (const child of scoped) {
476
+ if (!isPackageEntry(child)) continue
477
+ const name = `${entry.name}/${child.name}`
478
+ if (seen.has(name)) continue
479
+ seen.add(name)
480
+ packages.push({ name, dir: path.join(nodeModules, entry.name, child.name) })
481
+ }
482
+ }
483
+ }
484
+ }
485
+ packages.sort((left, right) => left.name.localeCompare(right.name))
486
+ return packages
487
+ }
488
+
489
+ /**
490
+ * Locate and read one package's client bundle through the path fence:
491
+ * `client.js` when it exists, otherwise `index.js`. A fence denial, an absent
492
+ * file, an oversized bundle and an unreadable file all skip the package and
493
+ * are reported as the scan's reason when nothing else was readable.
494
+ * @param {string} home
495
+ * @param {ScanPackage} packageEntry
496
+ * @param {string[]} skippedReasons
497
+ * @returns {Promise<{ file: string, text: string } | null>}
498
+ */
499
+ async function readBundle(home, packageEntry, skippedReasons, budget) {
500
+ if (core.paths === undefined || core.paths === null || typeof core.paths.resolveRead !== 'function') {
501
+ skippedReasons.push('core.paths.resolveRead 不可用')
502
+ return null
503
+ }
504
+ for (const filename of CANDIDATE_BUNDLES) {
505
+ const candidate = path.join(packageEntry.dir, filename)
506
+ let resolved
507
+ try {
508
+ resolved = await core.paths.resolveRead(candidate)
509
+ } catch (error) {
510
+ skippedReasons.push(`${packageEntry.name}/${filename}: ${util.redact(errorMessage(error), 120)}`)
511
+ continue
512
+ }
513
+ let info
514
+ try {
515
+ info = await stat(resolved.absolute)
516
+ } catch {
517
+ continue
518
+ }
519
+ if (!info.isFile()) continue
520
+ if (info.size > MAX_BUNDLE_BYTES) {
521
+ skippedReasons.push(`${packageEntry.name}/${filename}: 超过 ${MAX_BUNDLE_BYTES} 字节,已跳过`)
522
+ continue
523
+ }
524
+ if (budget.read + info.size > MAX_TOTAL_BUNDLE_BYTES) {
525
+ skippedReasons.push(`${packageEntry.name}/${filename}: 总读取量超过 ${MAX_TOTAL_BUNDLE_BYTES} 字节,已跳过`)
526
+ continue
527
+ }
528
+ budget.read += info.size
529
+ let text
530
+ try {
531
+ text = await readFile(resolved.absolute, 'utf8')
532
+ } catch (error) {
533
+ skippedReasons.push(`${packageEntry.name}/${filename}: ${util.redact(errorMessage(error), 120)}`)
534
+ continue
535
+ }
536
+ const relative = path.relative(home, resolved.absolute)
537
+ const display = relative.length > 0 && !relative.startsWith('..')
538
+ ? relative.split(path.sep).join('/')
539
+ : path.basename(resolved.absolute)
540
+ return { file: display, text }
541
+ }
542
+ return null
543
+ }
544
+
545
+ /**
546
+ * Read every `settings.section` occurrence and the literal `name:` /
547
+ * `name =` string values that follow within {@link SECTION_WINDOW}. The slot
548
+ * name itself is not a section id, so it is ignored. Duplicate ids keep every
549
+ * owner; the conflict list is derived from that set.
550
+ * @param {string} text
551
+ * @param {string} owner
552
+ * @param {string} file
553
+ * @param {Array<{ id: string, owner: string, file: string }>} sections
554
+ * @param {Set<string>} seen
555
+ * @param {Map<string, Set<string>>} ownersById
556
+ */
557
+ function extractSections(text, owner, file, sections, seen, ownersById) {
558
+ let cursor = text.indexOf(SECTION_TOKEN)
559
+ while (cursor !== -1) {
560
+ const window = text.slice(cursor + SECTION_TOKEN.length, cursor + SECTION_TOKEN.length + SECTION_WINDOW)
561
+ const ids = [...window.matchAll(SECTION_ID)].map((match) => match[2])
562
+ const names = [...window.matchAll(SECTION_NAME)].map((match) => match[2]).filter((name) => name !== SECTION_TOKEN)
563
+ for (const id of ids.length > 0 ? ids : names) {
564
+ if (id.length === 0 || id === SECTION_TOKEN || id.startsWith(`${SECTION_TOKEN}.`)) continue
565
+ const key = `${owner}\u0000${file}\u0000${id}`
566
+ if (seen.has(key)) continue
567
+ seen.add(key)
568
+ if (sections.length >= MAX_SECTION_ENTRIES) return
569
+ const entry = {
570
+ id: util.redact(id, 200),
571
+ owner: util.redact(owner, 160),
572
+ file: util.redact(file, 300),
573
+ }
574
+ sections.push(entry)
575
+ const owners = ownersById.get(entry.id)
576
+ if (owners === undefined) ownersById.set(entry.id, new Set([entry.owner]))
577
+ else owners.add(entry.owner)
578
+ }
579
+ cursor = text.indexOf(SECTION_TOKEN, cursor + SECTION_TOKEN.length)
580
+ }
581
+ }
582
+
583
+ /** @returns {Promise<Record<string, unknown>>} */
584
+ async function sectionsMethod(params) {
585
+ assertParams(params)
586
+ if (core.paths === undefined || core.paths === null || typeof core.paths.resolveRead !== 'function') {
587
+ return {
588
+ ...unavailable('路径围栏不可用:无法读取 DSH profiles 下的客户端 bundle', '请确认 core.paths 已装配;静态扫描不会绕过路径围栏直接读盘'),
589
+ note: STATIC_SCAN_NOTE,
590
+ }
591
+ }
592
+ const home = resolveDshHome()
593
+ let profilesRoot
594
+ try {
595
+ // Every filesystem access starts at a fenced path. The production fence
596
+ // refuses `$DSH_HOME/profiles` as host-internal data, so this answer is
597
+ // the honest one there instead of a scan behind the fence's back.
598
+ profilesRoot = (await core.paths.resolveRead(path.join(home, 'profiles'))).absolute
599
+ } catch (error) {
600
+ return {
601
+ ...unavailable('读取 DSH profiles 目录被路径围栏拒绝', util.redact(errorMessage(error), 160)),
602
+ note: STATIC_SCAN_NOTE,
603
+ }
604
+ }
605
+ let packages
606
+ try {
607
+ packages = await discoverPackages(profilesRoot)
608
+ } catch (error) {
609
+ if (errorCode(error) === 'ENOENT') {
610
+ return {
611
+ ...unavailable('未找到 DSH profiles 目录', '无法静态扫描 settings.section:该路径下没有 profiles;请确认 DSH_HOME 指向运行中的 profile 根'),
612
+ note: STATIC_SCAN_NOTE,
613
+ }
614
+ }
615
+ return {
616
+ ...unavailable('读取 DSH profiles 目录失败', util.redact(errorMessage(error), 160)),
617
+ note: STATIC_SCAN_NOTE,
618
+ }
619
+ }
620
+ if (packages.length === 0) {
621
+ return {
622
+ ...unavailable('profiles 下没有可扫描的客户端包(dsh-* 或 @*/*)', '该 profile 可能只安装了本插件;静态扫描没有输入'),
623
+ note: STATIC_SCAN_NOTE,
624
+ }
625
+ }
626
+
627
+ const scanned = { packages: 0, files: 0 }
628
+ /** @type {Array<{ id: string, owner: string, file: string }>} */
629
+ const sections = []
630
+ const seen = new Set()
631
+ /** @type {Map<string, Set<string>>} */
632
+ const ownersById = new Map()
633
+ /** @type {string[]} */
634
+ const skippedReasons = []
635
+ const budget = { read: 0 }
636
+
637
+ for (const packageEntry of packages) {
638
+ if (scanned.files >= MAX_SCAN_FILES) break
639
+ scanned.packages += 1
640
+ const bundle = await readBundle(home, packageEntry, skippedReasons, budget)
641
+ if (bundle === null) continue
642
+ scanned.files += 1
643
+ extractSections(bundle.text, packageEntry.name, bundle.file, sections, seen, ownersById)
644
+ }
645
+
646
+ if (scanned.files === 0) {
647
+ const firstSkip = skippedReasons.length > 0 ? `首个跳过原因:${skippedReasons[0]}` : '未找到 client.js/index.js'
648
+ return {
649
+ ...unavailable(
650
+ 'profiles 下没有可读的客户端 bundle',
651
+ `${firstSkip};扫描只读取经 core.paths.resolveRead 放行的 client.js/index.js(≤${MAX_BUNDLE_BYTES} 字节)`,
652
+ ),
653
+ note: STATIC_SCAN_NOTE,
654
+ }
655
+ }
656
+
657
+ /** @type {Array<{ kind: string, id: string, owners: string[], suggestion: string }>} */
658
+ // The plugin's own registration is known by constant (its bundle lives in a
659
+ // linked checkout the fence refuses), so it joins the inventory here.
660
+ const ownScanned = [...ownersById.values()].some((owners) => owners.has(OWN_OWNER))
661
+ if (!ownScanned) {
662
+ const existing = sections.find((entry) => entry.id === OWN_SECTION_ID)
663
+ if (existing === undefined) {
664
+ sections.push({ id: OWN_SECTION_ID, owner: OWN_OWNER, file: '(plugin constant)' })
665
+ } else {
666
+ existing.file = `${existing.file} + (plugin constant)`
667
+ }
668
+ const owners = ownersById.get(OWN_SECTION_ID)
669
+ if (owners === undefined) ownersById.set(OWN_SECTION_ID, new Set([OWN_OWNER]))
670
+ else owners.add(OWN_OWNER)
671
+ }
672
+
673
+ const conflicts = []
674
+ for (const [id, owners] of ownersById) {
675
+ if (owners.size < 2 || conflicts.length >= MAX_CONFLICTS) continue
676
+ const list = [...owners].sort().slice(0, 50)
677
+ conflicts.push({
678
+ kind: 'duplicate-id',
679
+ id,
680
+ owners: list,
681
+ suggestion: util.redact(
682
+ `settings.section id "${id}" 被多个客户端包注册(${list.join('、')}):宿主侧会出现重复设置项或 id 冲突,请只保留一个注册者或给 id 加包前缀`,
683
+ 600,
684
+ ),
685
+ })
686
+ }
687
+ conflicts.sort((left, right) => left.id.localeCompare(right.id))
688
+
689
+ return {
690
+ available: true,
691
+ method: 'static-scan',
692
+ scanned,
693
+ sections,
694
+ conflicts,
695
+ own: { id: OWN_SECTION_ID, owner: OWN_OWNER, source: 'plugin-constant', scanned: ownScanned },
696
+ note: STATIC_SCAN_NOTE,
697
+ }
698
+ }
699
+
700
+ /** @returns {Promise<Record<string, unknown>>} */
701
+ async function compatMethod(params) {
702
+ assertParams(params)
703
+ const compatibility = core.compatibility
704
+ if (isPlainObject(compatibility) && typeof compatibility.current === 'function') {
705
+ try {
706
+ return normalizeVerdict(compatibility.current(), 'compatibility.current')
707
+ } catch {
708
+ // A live verdict that cannot be read is not authoritative; evaluate the
709
+ // same layer locally rather than reporting a fabricated state.
710
+ }
711
+ }
712
+ if (core.caps === undefined || core.caps === null || typeof core.caps.snapshot !== 'function') {
713
+ return unavailable(
714
+ '兼容层不可用:core.compatibility.current() 与 core.caps.snapshot() 均不可用',
715
+ '请在宿主入口把兼容层实例挂到 core.compatibility,或确认 core.caps 已完成装配',
716
+ )
717
+ }
718
+ let evaluate
719
+ try {
720
+ const compat = await import('../core/compat.js')
721
+ evaluate = compat.evaluate
722
+ } catch (error) {
723
+ return unavailable('无法加载兼容层模块 core/compat.js', util.redact(errorMessage(error), 160))
724
+ }
725
+ try {
726
+ const verdict = evaluate({ version: recordedHostVersion(), capabilities: core.caps.snapshot() })
727
+ return normalizeVerdict(verdict, 'compat.evaluate')
728
+ } catch (error) {
729
+ return unavailable('兼容性判定失败', util.redact(errorMessage(error), 160))
730
+ }
731
+ }
732
+
733
+ /**
734
+ * Run one sub-probe, turning an unexpected throw into the same degradation
735
+ * record every other failure uses.
736
+ * @param {() => Promise<Record<string, unknown>>} probe
737
+ * @returns {Promise<Record<string, unknown>>}
738
+ */
739
+ async function safeProbe(probe) {
740
+ try {
741
+ return await probe()
742
+ } catch (error) {
743
+ return unavailable('健康检查子项执行失败', util.redact(errorMessage(error), 160))
744
+ }
745
+ }
746
+
747
+ /** @param {Record<string, any>} value @returns {'ok' | 'warn' | 'error'} */
748
+ function pluginsSeverity(value) {
749
+ if (value.available !== true) return 'error'
750
+ return Array.isArray(value.anomalies) && value.anomalies.length > 0 ? 'warn' : 'ok'
751
+ }
752
+
753
+ /** @param {Record<string, any>} value @returns {'ok' | 'warn' | 'error'} */
754
+ function settingsSeverity(value) {
755
+ if (value.available !== true || value.redactionVerified !== true) return 'error'
756
+ const own = isPlainObject(value.own) ? value.own : null
757
+ if (own === null || own.declared !== true || own.enabled !== true) return 'warn'
758
+ return 'ok'
759
+ }
760
+
761
+ /** @param {Record<string, any>} value @returns {'ok' | 'warn' | 'error'} */
762
+ function sectionsSeverity(value) {
763
+ if (value.available !== true) return 'error'
764
+ return Array.isArray(value.conflicts) && value.conflicts.length > 0 ? 'warn' : 'ok'
765
+ }
766
+
767
+ /** @param {Record<string, any>} value @returns {'ok' | 'warn' | 'error'} */
768
+ function compatSeverity(value) {
769
+ if (value.available !== true) return 'error'
770
+ if (value.level === 'unsupported') return 'error'
771
+ if (value.readOnly === true || value.level === 'degraded' || value.level === 'unknown') return 'warn'
772
+ return 'ok'
773
+ }
774
+
775
+ /**
776
+ * Pick the most severe section; order decides ties so the answer is stable.
777
+ * @param {Array<{ id: string, severity: 'ok' | 'warn' | 'error' }>} entries
778
+ * @returns {{ severity: 'ok' | 'warn' | 'error', id: string }}
779
+ */
780
+ function pickWorst(entries) {
781
+ const rank = { ok: 0, warn: 1, error: 2 }
782
+ /** @type {{ severity: 'ok' | 'warn' | 'error', id: string }} */
783
+ let worst = { severity: 'ok', id: 'none' }
784
+ let worstRank = 0
785
+ for (const entry of entries) {
786
+ if (rank[entry.severity] > worstRank) {
787
+ worstRank = rank[entry.severity]
788
+ worst = { severity: entry.severity, id: entry.id }
789
+ }
790
+ }
791
+ return worst
792
+ }
793
+
794
+ /** @returns {Promise<Record<string, unknown>>} */
795
+ async function summaryMethod(params) {
796
+ assertParams(params)
797
+ const [plugins, settings, sections, compat] = await Promise.all([
798
+ safeProbe(() => pluginsMethod()),
799
+ safeProbe(() => settingsMethod()),
800
+ safeProbe(() => sectionsMethod()),
801
+ safeProbe(() => compatMethod()),
802
+ ])
803
+ const own = ownRow()
804
+ const worst = pickWorst([
805
+ { id: 'plugins', severity: pluginsSeverity(plugins) },
806
+ { id: 'settings', severity: settingsSeverity(settings) },
807
+ { id: 'sections', severity: sectionsSeverity(sections) },
808
+ { id: 'compat', severity: compatSeverity(compat) },
809
+ ])
810
+ return {
811
+ generatedAt: new Date().toISOString(),
812
+ plugins: {
813
+ total: plugins.available === true && Array.isArray(plugins.items) ? plugins.items.length : null,
814
+ anomalies: plugins.available === true && Array.isArray(plugins.anomalies) ? plugins.anomalies.length : null,
815
+ },
816
+ settings: {
817
+ namespaces: settings.available === true && Array.isArray(settings.namespaces) ? settings.namespaces.length : null,
818
+ own: isPlainObject(settings.own) ? settings.own : own,
819
+ redactionVerified: settings.available === true && settings.redactionVerified === true,
820
+ },
821
+ sections: {
822
+ count: sections.available === true && Array.isArray(sections.sections) ? sections.sections.length : null,
823
+ conflicts: sections.available === true && Array.isArray(sections.conflicts) ? sections.conflicts.length : null,
824
+ },
825
+ compat: {
826
+ level: compat.available === true && typeof compat.level === 'string' ? compat.level : null,
827
+ readOnly: compat.available === true ? compat.readOnly === true : null,
828
+ },
829
+ worst,
830
+ }
831
+ }
832
+
833
+ return {
834
+ id: MODULE_ID,
835
+ title: 'nav.health',
836
+ order: MODULE_ORDER,
837
+ requires: [],
838
+ async init() {},
839
+ probe: () => {
840
+ const ctx = core.ctx
841
+ if (ctx === undefined || ctx === null) {
842
+ return { state: 'BLOCKED', detail: '宿主上下文不可用:无法读取插件、设置与兼容性状态' }
843
+ }
844
+ if (typeof ctx.get !== 'function') {
845
+ return { state: 'BLOCKED', detail: '宿主上下文缺少 ctx.get():无法读取宿主服务' }
846
+ }
847
+ return { state: 'FULL', detail: '' }
848
+ },
849
+ methods: {
850
+ /** Plugin rows and their control anomalies, from `pluginManager.listPlugins()`. */
851
+ 'health.plugins': (params) => pluginsMethod(params),
852
+ /** Redacted settings metadata only; `schema`/`value`/`base`/`user` never leave the module. */
853
+ 'health.settings': (params) => settingsMethod(params),
854
+ /** Static scan of client bundles for literal `settings.section` registrations. */
855
+ 'health.sections': (params) => sectionsMethod(params),
856
+ /** Compatibility verdict, preferring `core.compatibility.current()`. */
857
+ 'health.compat': (params) => compatMethod(params),
858
+ /** One concurrent aggregate over the four probes, plus the worst section. */
859
+ 'health.summary': (params) => summaryMethod(params),
860
+ },
861
+ }
862
+ }