dsh-composition-doctor 0.1.2 → 0.2.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ - Release the verified 0.2.0 package without changing the established diagnostic architecture or evidence boundaries.
6
+
7
+ ## 0.1.3
8
+
9
+ - Hardened the release package contract with the `dsh-doctor` binary entry.
10
+ - Added packed-package verification coverage and documented scan exit-code thresholds.
11
+ - Hardened npm artifact cache writes with integrity metadata and atomic temporary-file publication.
12
+ - Reject unsafe tar paths and link entries before reading package metadata.
13
+ - Kept DSH compatibility verified only for `0.1.5-rc.1` and `0.1.5-rc.2`; `0.1.6-alpha.1` remains expected-compatible only.
14
+ - Runtime smoke remains `not-run` unless a trusted OS-level isolation backend is available.
15
+ - Two Windows symlink regressions may remain `skipped` when the test process cannot create file symlinks; this is not a compatibility PASS.
16
+ - `0.1.6-alpha.1` is experimental/expected-compatible and is not part of the verified release range.
17
+ - A temporary directory is not a security sandbox; no runtime safety claim is made from temporary-directory execution.
package/README.md CHANGED
@@ -1,12 +1,14 @@
1
1
  # dsh-composition-doctor
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/dsh-composition-doctor)](https://www.npmjs.com/package/dsh-composition-doctor)
4
- [![CI](https://github.com/lemonxiny55/dsh-composition-doctor/actions/workflows/ci.yml/badge.svg)](https://github.com/lemonxiny55/dsh-composition-doctor/actions)
4
+ [![CI](https://github.com/lemonxiny55/dsh-composition-doctor/actions/workflows/ci.yml/badge.svg)](https://github.com/lemonxiny55/dsh-composition-doctor/actions/workflows/ci.yml)
5
5
 
6
6
  English | [中文](README.zh.md)
7
7
 
8
8
  Composition and upgrade preflight doctor for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`dsh`). It reads an explicitly selected profile and explains observable Cordis/plugin composition risks with concrete evidence. It never edits a real profile or silently changes permissions.
9
9
 
10
+ Current package release: `0.2.0`.
11
+
10
12
  ## What the model gets
11
13
 
12
14
  | Command | Purpose |
@@ -18,33 +20,45 @@ Composition and upgrade preflight doctor for [DeepSeek Harness](https://github.c
18
20
 
19
21
  The Web Settings page is display/export only: it reads the latest local report, shows a conflict graph, and exports JSON/Markdown. It has no repair, install, or uninstall action.
20
22
 
23
+ ## Reports and evidence boundaries
24
+
25
+ `scan --output <dir>` writes only to the requested directory. To make the same report visible to the read-only Settings page, opt in explicitly: `--publish` copies it to the default plugin directory `.dsh-composition-doctor/reports`, while `--report-dir <dir>` publishes to a configured plugin directory. Use `--format both` so the Web route has `report.json` and Markdown remains exportable. Do not use a profile directory, `.env` location, or any directory containing keys, tokens, or other secrets as a report directory.
26
+
27
+ Reports declare `evidenceMode`: `static` means allow-listed manifest/patch/package metadata only; `composed` means a public `dsh --profile <name> --dump-config` command returned a composition result; `runtime-observed` is reserved for a successful isolated runtime observation backend; and `mixed` is reserved for an adapter that supplies both. `dump-config` never proves runtime execution, including when a `!!js` or other runtime-dependent value is present. Static findings and bounded metadata coverage are not proof of the final runtime composition. If no compatible public DSH CLI is available, scan falls back to static and records a warning. Reports written before evidence schema 2 may still be read as legacy `resolved`, but new reports never emit that label.
28
+
29
+ `preflight --candidate package@version` records a validated exact reference in an isolated temporary `package.json`. Target artifact discovery is local-first (`--dsh-bin`, package directory, tarball, installed `dsh`, `--package-manager-cache`, then Doctor-owned cache); registry access is allowed only with explicit `--online`. Online resolution downloads exact registry tarballs into Doctor-owned cache, records source/version/integrity/hash, and never installs or runs lifecycle scripts. `--allow-build` does not grant permission to execute third-party runtime code.
30
+
31
+ `scan --fail-on never|info|warning|error` controls the scan exit code. The default is `never`: warnings and errors remain in the report without changing the exit code. `info` fails on any diagnostic, `warning` fails on warnings or errors, and `error` fails only on errors. Malformed arguments return exit code 2; operational failures return 1.
32
+
21
33
  ## Install
22
34
 
23
35
  ```powershell
24
36
  npm install -g dsh-composition-doctor
25
37
  npx @deepseek-ai/dsh plugin --profile web add dsh-composition-doctor
38
+ dsh-doctor --version
26
39
  ```
27
40
 
28
- Restart the Web UI (`npx @deepseek-ai/dsh web`) after changing a profile. The CLI can also run from a checkout with `node dist/cli/main.js`.
41
+ Restart the Web UI (`npx @deepseek-ai/dsh web`) after changing a profile.
29
42
 
30
43
  ## Example
31
44
 
32
45
  ```powershell
33
- dsh-doctor scan --profile C:\path\to\profile --format both --output .\reports\profile
46
+ dsh-doctor scan --profile C:\path\to\profile --format both --output .\reports\profile --publish
47
+ dsh-doctor scan --profile C:\path\to\profile --format both --output .\reports\archive --report-dir C:\safe\doctor-reports
34
48
  dsh-doctor snapshot --profile C:\path\to\profile --output .\reports\before.json
35
49
  dsh-doctor diff --before .\reports\before.json --after .\reports\after.json --format both
36
- dsh-doctor preflight --profile C:\path\to\profile --target-dsh 0.1.0-rc.6
50
+ dsh-doctor preflight --profile C:\path\to\profile --target-dsh 0.1.5-rc.2
37
51
  ```
38
52
 
39
- Each finding is `info`, `warning`, or `error` and includes evidence, explanation, and the smallest remediation. Missing runtime evidence is reported as a warning, never as a confirmed failure.
53
+ Each finding is `info`, `warning`, or `error` and includes evidence, explanation, and the smallest remediation. `runtimeSmoke.status=not-run` is not a runtime PASS; `artifact-unavailable` is not `incompatible`; and a warning is not a confirmed failure.
40
54
 
41
55
  ## Safety and privacy
42
56
 
43
- Default operations are read-only or isolated under the OS temporary directory. The plugin does not modify profiles, install/remove plugins, migrate configuration, escalate permissions, or perform network I/O by default. It never reads `.env`, keys, tokens, environment values, session bodies, or workspace file contents.
57
+ Default operations are read-only or isolated under the OS temporary directory. The plugin does not modify profiles, install/remove plugins, migrate configuration, escalate permissions, or perform network I/O by default. It never reads `.env`, profile secrets, session bodies, or workspace file contents, and does not collect or persist arbitrary environment-variable values. Public CLI execution receives only the minimal process-routing variables required by the host platform.
44
58
 
45
59
  ## Support and limitations
46
60
 
47
- Verified preview range: DSH `>=0.1.0-rc.5 <0.2.0`, Cordis `>=4 <5`, Node.js `>=20`; Windows is first-class and macOS/Linux are supported. DSH has not yet exposed a stable resolved-composition introspection API, so static findings are explicitly labelled when no public provider is available.
61
+ The real public CLI harness verifies `@deepseek-ai/dsh@0.1.5-rc.1` and `@deepseek-ai/dsh@0.1.5-rc.2`. `0.1.6-alpha.1` remains expected-compatible/experimental only; `0.1.0-rc.6` is historical context, not a current verified target. Missing artifacts are reported as unavailable, never as PASS. Verified development runtime: Node.js 24 on Windows; CI covers Node.js 20 on Ubuntu. Runtime hook/UI ownership is reported as unverified unless public metadata supplies it, and a temp profile is not a security sandbox.
48
62
 
49
63
  ## Development
50
64
 
@@ -54,4 +68,6 @@ pnpm typecheck
54
68
  pnpm build
55
69
  ```
56
70
 
71
+ For checkout-only development, run the CLI with `node dist/cli/main.js` after building.
72
+
57
73
  See [`README.zh.md`](README.zh.md), [`docs/compatibility.md`](docs/compatibility.md), and [`docs/examples/scan-report.md`](docs/examples/scan-report.md). MIT licensed.
package/README.zh.md CHANGED
@@ -1,28 +1,73 @@
1
1
  # dsh-composition-doctor(中文)
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/dsh-composition-doctor)](https://www.npmjs.com/package/dsh-composition-doctor)
4
+ [![CI](https://github.com/lemonxiny55/dsh-composition-doctor/actions/workflows/ci.yml/badge.svg)](https://github.com/lemonxiny55/dsh-composition-doctor/actions/workflows/ci.yml)
5
+
3
6
  [English](README.md) | 中文
4
7
 
5
- 面向 DeepSeek Harness(DSH)的本地只读组合与升级预检插件。它读取明确指定的 profile,分析 Cordis/plugin 组合风险,生成脱敏快照,比较升级差异,并在独立临时目录中演练升级。
8
+ 面向 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)(`dsh`)的组合与升级预检工具。它读取明确指定的 profile,用可追溯证据说明可观察到的 Cordis/plugin 组合风险;不会编辑真实 profile,也不会静默扩大权限。
9
+
10
+ 当前 package release:`0.2.0`。
6
11
 
7
- ## 功能
12
+ ## 模型可用能力
8
13
 
9
14
  | 命令 | 作用 |
10
15
  |---|---|
11
- | `dsh-doctor scan` | 检测重复 row、hook 顺序风险、UI slot/route 冲突、bundle 覆盖、peer/platform 不匹配和 profile 漂移。 |
12
- | `dsh-doctor snapshot` | 生成脱敏、可比较的 profile 快照和 lockfile 哈希。 |
13
- | `dsh-doctor diff` | 比较插件、rows、hooks、UIpeer 和平台变化。 |
14
- | `dsh-doctor preflight` | 在独立临时目录预演目标 DSH 升级。 |
16
+ | `dsh-doctor scan` | 检测重复 Cordis row、hook 顺序风险、UI slot/route 所有权冲突、bundle 覆盖、peer/platform 不匹配和 profile 漂移。 |
17
+ | `dsh-doctor snapshot` | 生成脱敏、可比较的 profile 快照及 lockfile 哈希。 |
18
+ | `dsh-doctor diff` | 汇总新增、删除或升级的插件,以及 rows、hooks、UI 声明、peer 和平台变化。 |
19
+ | `dsh-doctor preflight` | 在独立临时 profile 中演练目标 DSH 升级。 |
20
+
21
+ Web Settings 页面仅供显示与导出:它读取最新本地报告、展示冲突图,并导出 JSON/Markdown;不提供修复、安装或卸载操作。
22
+
23
+ ## 报告与证据边界
24
+
25
+ `scan --output <目录>` 只写入显式指定的目录。要让只读 Settings 页面看到同一份报告,必须显式选择 `--publish`,它会复制到默认插件目录 `.dsh-composition-doctor/reports`;也可以使用 `--report-dir <目录>` 发布到配置的插件报告目录。请使用 `--format both`,使 Web route 能读取 `report.json`,同时保留 Markdown 导出。报告目录不能是 profile、`.env` 所在位置,或任何含密钥、token 或其他敏感信息的目录。
26
+
27
+ 报告中的 `evidenceMode` 标明证据来源:`static` 仅表示 allow-list 中的 manifest、patch、package metadata 等静态证据;`composed` 表示公开 `dsh --profile <name> --dump-config` 返回了 composition 结果;`runtime-observed` 只允许真正启动隔离 runtime 并观察到注册/行为的后端使用;`mixed` 预留给同时提供多类来源的适配器。`dump-config` 即使成功,也不代表 runtime 已验证;存在 `!!js` 等运行时依赖时尤其如此。找不到兼容的公开 DSH CLI 时会回退到 static,并明确报告 warning。旧的 evidence schema 2 之前报告仍可按 legacy `resolved` 读取,但新报告不会再输出该标签。
15
28
 
16
- Web Settings 只读显示最近报告、冲突图并导出 JSON/Markdown,不提供修复、安装或卸载操作。
29
+ `preflight --candidate package@version` 只会把通过校验的精确引用记录到隔离临时 `package.json`。目标 artifact 默认按本地优先顺序查找:`--dsh-bin`、本地 package directory、本地 tarball、已安装 `dsh`、`--package-manager-cache`、Doctor 自己的 cache;只有显式 `--online` 才允许访问 registry。在线解析会把精确 tarball 写入 Doctor 自己的 cache,记录来源、版本、integrity 和 hash,并且不会安装或执行 lifecycle script。`--allow-build` 不等于允许执行第三方 runtime code。
17
30
 
18
- ## 安装与使用
31
+ `scan --fail-on never|info|warning|error` 控制 scan 的退出码。默认是 `never`:warning 和 error 会写入报告,但不改变退出码;`info` 遇到任意诊断时退出 1,`warning` 遇到 warning 或 error 时退出 1,`error` 只在 error 时退出 1。参数错误退出 2,执行失败退出 1。
32
+
33
+ ## 安装
19
34
 
20
35
  ```powershell
21
36
  npm install -g dsh-composition-doctor
22
37
  npx @deepseek-ai/dsh plugin --profile web add dsh-composition-doctor
23
- dsh-doctor scan --profile C:\path\to\profile --format both --output .\reports\profile
38
+ dsh-doctor --version
39
+ ```
40
+
41
+ 更改 profile 后重启 Web UI:`npx @deepseek-ai/dsh web`。
42
+
43
+ ## 示例
44
+
45
+ ```powershell
46
+ dsh-doctor scan --profile C:\path\to\profile --format both --output .\reports\profile --publish
47
+ dsh-doctor scan --profile C:\path\to\profile --format both --output .\reports\archive --report-dir C:\safe\doctor-reports
48
+ dsh-doctor snapshot --profile C:\path\to\profile --output .\reports\before.json
49
+ dsh-doctor diff --before .\reports\before.json --after .\reports\after.json --format both
50
+ dsh-doctor preflight --profile C:\path\to\profile --target-dsh 0.1.5-rc.2
51
+ ```
52
+
53
+ 每条诊断均为 `info`、`warning` 或 `error`,并附带 evidence、explanation 和最小 remediation。`runtimeSmoke.status=not-run` 不等于 runtime PASS;`artifact-unavailable` 不等于 `incompatible`;warning 也不等于已确认失败。
54
+
55
+ ## 安全与隐私
56
+
57
+ 默认操作只读,或仅在操作系统临时目录中隔离运行。插件不会修改 profile、安装或删除插件、迁移配置、扩大权限,默认也不会执行网络 I/O。它不会读取 `.env`、profile 密钥、会话正文或工作区源文件内容,也不会收集或持久化任意环境变量值;启动公开 CLI 时只传递平台所需的最小进程路由变量。
58
+
59
+ ## 支持范围与限制
60
+
61
+ real-release harness 已使用真实公开 CLI 验证 `@deepseek-ai/dsh@0.1.5-rc.1` 和 `@deepseek-ai/dsh@0.1.5-rc.2`。`0.1.6-alpha.1` 仍只是 expected-compatible/experimental;`0.1.0-rc.6` 仅作历史兼容背景,不是当前 verified target。artifact 不可用时会明确报告 unavailable,绝不记为 PASS。已验证开发环境为 Windows + Node.js 24;CI 覆盖 Ubuntu + Node.js 20。只有公开 metadata 能提供 hook/UI ownership 时才会确认,否则标为 unverified;临时目录不是安全 sandbox。
62
+
63
+ ## 开发
64
+
65
+ ```powershell
66
+ pnpm test
67
+ pnpm typecheck
68
+ pnpm build
24
69
  ```
25
70
 
26
- 默认操作只读或写入操作系统临时目录,不修改真实 profile,不扩大权限,不默认联网,不读取 `.env`、密钥、token、环境变量值、会话正文或工作区文件内容。证据不足时只报告 warning
71
+ 仅在 checkout 开发时,构建完成后使用 `node dist/cli/main.js` 运行 CLI
27
72
 
28
- 已验证范围:DSH `>=0.1.0-rc.5 <0.2.0`、Cordis `>=4 <5`、Node.js `>=20`;Windows 优先,同时支持 macOS/Linux
73
+ 参阅 [`README.md`](README.md)、[`docs/compatibility.md`](docs/compatibility.md) [`docs/examples/scan-report.md`](docs/examples/scan-report.md)MIT 许可。
package/dist/cli/main.js CHANGED
@@ -1,16 +1,27 @@
1
1
  import { fileURLToPath } from 'node:url';
2
+ import { readFileSync } from 'node:fs';
2
3
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
- import { resolve } from 'node:path';
4
+ import { dirname, resolve } from 'node:path';
4
5
  import { resolveComposition } from '../core/composition-adapter.js';
5
6
  import { diffSnapshots, renderSnapshotDiffMarkdown } from '../core/diff.js';
6
7
  import { readProfile } from '../core/profile-reader.js';
7
- import { createSnapshot } from '../core/snapshot.js';
8
+ import { createSnapshot, isSnapshotV1, isSnapshotV2 } from '../core/snapshot.js';
8
9
  import { analyseComposition } from '../core/rules.js';
9
10
  import { renderJson } from '../reports/json.js';
10
11
  import { renderMarkdown } from '../reports/markdown.js';
12
+ import { resolveReportDirectory } from '../reports/location.js';
11
13
  import { runPreflight } from '../core/preflight.js';
12
14
  const usage = 'Usage: dsh-doctor <scan | snapshot | diff | preflight>';
13
15
  const commands = new Set(['scan', 'snapshot', 'diff', 'preflight']);
16
+ function packageVersion() {
17
+ try {
18
+ const manifest = JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '../../package.json'), 'utf8'));
19
+ return typeof manifest.version === 'string' ? manifest.version : 'unknown';
20
+ }
21
+ catch {
22
+ return 'unknown';
23
+ }
24
+ }
14
25
  function option(argv, name) {
15
26
  const index = argv.indexOf(name);
16
27
  return index >= 0 && typeof argv[index + 1] === 'string' ? argv[index + 1] : undefined;
@@ -30,19 +41,41 @@ function invalid(io, message) {
30
41
  async function scan(argv, io) {
31
42
  const profile = option(argv, '--profile');
32
43
  const output = option(argv, '--output');
44
+ const configuredReportDir = option(argv, '--report-dir');
45
+ const publish = argv.includes('--publish') || configuredReportDir !== undefined;
33
46
  const format = option(argv, '--format') ?? 'json';
34
47
  if (profile === undefined || output === undefined)
35
48
  return invalid(io, 'scan requires --profile and --output');
36
49
  if (format !== 'json' && format !== 'markdown' && format !== 'both')
37
50
  return invalid(io, '--format must be json, markdown, or both');
38
- const report = analyseComposition(await resolveComposition(await readProfile({ profileDir: resolve(profile) })));
51
+ const failOn = option(argv, '--fail-on') ?? 'never';
52
+ if (failOn !== 'never' && failOn !== 'info' && failOn !== 'warning' && failOn !== 'error')
53
+ return invalid(io, '--fail-on must be info, warning, error, or never');
54
+ const primary = await resolveComposition(await readProfile({ profileDir: resolve(profile) }));
55
+ const compared = await Promise.all(options(argv, '--compare-profile').map(async (value) => ({ name: value, model: await resolveComposition(await readProfile({ profileDir: resolve(value) })) })));
56
+ const report = analyseComposition(compared.length === 0 ? primary : {
57
+ ...primary,
58
+ bundles: [...(primary.bundles ?? []), ...compared.flatMap(({ name, model }) => (model.bundles ?? []).map((bundle) => ({ ...bundle, profile: name })))],
59
+ adapterDiagnostics: [...primary.adapterDiagnostics, ...compared.flatMap(({ model }) => model.adapterDiagnostics)]
60
+ });
39
61
  const destination = resolve(output);
40
- await mkdir(destination, { recursive: true });
41
- if (format === 'json' || format === 'both')
42
- await writeFile(resolve(destination, 'report.json'), renderJson(report), 'utf8');
43
- if (format === 'markdown' || format === 'both')
44
- await writeFile(resolve(destination, 'report.md'), renderMarkdown(report), 'utf8');
62
+ const destinations = [destination, ...(publish ? [resolveReportDirectory(configuredReportDir)] : [])];
63
+ for (const directory of destinations) {
64
+ await mkdir(directory, { recursive: true });
65
+ if (format === 'json' || format === 'both')
66
+ await writeFile(resolve(directory, 'report.json'), renderJson(report), 'utf8');
67
+ if (format === 'markdown' || format === 'both')
68
+ await writeFile(resolve(directory, 'report.md'), renderMarkdown(report), 'utf8');
69
+ }
45
70
  io.write(`Wrote reports to ${destination}`);
71
+ if (publish)
72
+ io.write(`Published reports to ${destinations[1]}`);
73
+ if (failOn === 'info' && report.diagnostics.length > 0)
74
+ return 1;
75
+ if (failOn === 'error' && report.diagnostics.some((item) => item.severity === 'error'))
76
+ return 1;
77
+ if (failOn === 'warning' && report.diagnostics.some((item) => item.severity === 'warning' || item.severity === 'error'))
78
+ return 1;
46
79
  return 0;
47
80
  }
48
81
  async function snapshot(argv, io) {
@@ -51,13 +84,12 @@ async function snapshot(argv, io) {
51
84
  if (profile === undefined || output === undefined)
52
85
  return invalid(io, 'snapshot requires --profile and --output');
53
86
  const destination = resolve(output);
87
+ await mkdir(dirname(destination), { recursive: true });
54
88
  await writeFile(destination, `${JSON.stringify(await createSnapshot(await readProfile({ profileDir: resolve(profile) })), null, 2)}\n`, 'utf8');
55
89
  io.write(`Wrote snapshot to ${destination}`);
56
90
  return 0;
57
91
  }
58
- function isSnapshot(value) {
59
- return value !== null && typeof value === 'object' && value.schemaVersion === 1;
60
- }
92
+ function isSnapshot(value) { return isSnapshotV1(value) || isSnapshotV2(value); }
61
93
  async function diff(argv, io) {
62
94
  const beforePath = option(argv, '--before');
63
95
  const afterPath = option(argv, '--after');
@@ -69,12 +101,21 @@ async function diff(argv, io) {
69
101
  const before = JSON.parse(await readFile(resolve(beforePath), 'utf8'));
70
102
  const after = JSON.parse(await readFile(resolve(afterPath), 'utf8'));
71
103
  if (!isSnapshot(before) || !isSnapshot(after))
72
- return invalid(io, 'diff inputs must be schema version 1 snapshots');
104
+ return invalid(io, 'diff inputs must be schema version 1 or 2 snapshots');
73
105
  const result = diffSnapshots(before, after);
74
- if (format === 'json' || format === 'both')
75
- io.write(`${JSON.stringify(result, null, 2)}\n`);
76
- if (format === 'markdown' || format === 'both')
77
- io.write(renderSnapshotDiffMarkdown(result));
106
+ const output = option(argv, '--output');
107
+ const rendered = [
108
+ ...(format === 'json' || format === 'both' ? [`${JSON.stringify(result, null, 2)}\n`] : []),
109
+ ...(format === 'markdown' || format === 'both' ? [renderSnapshotDiffMarkdown(result)] : [])
110
+ ];
111
+ if (output === undefined)
112
+ rendered.forEach((value) => io.write(value));
113
+ else {
114
+ const destination = resolve(output);
115
+ await mkdir(dirname(destination), { recursive: true });
116
+ await writeFile(destination, rendered.join(''), 'utf8');
117
+ io.write(`Wrote diff to ${destination}`);
118
+ }
78
119
  return 0;
79
120
  }
80
121
  async function preflight(argv, io) {
@@ -89,14 +130,17 @@ async function preflight(argv, io) {
89
130
  candidates: options(argv, '--candidate'),
90
131
  allowBuild: argv.includes('--allow-build'),
91
132
  online: argv.includes('--online'),
92
- keepTemp: argv.includes('--keep-temp')
133
+ keepTemp: argv.includes('--keep-temp'),
134
+ dshBin: option(argv, '--dsh-bin'),
135
+ dshPackage: option(argv, '--dsh-package'),
136
+ packageManagerCacheDirs: options(argv, '--package-manager-cache')
93
137
  });
94
138
  const rendered = `${JSON.stringify(result, null, 2)}\n`;
95
139
  if (output === undefined)
96
140
  io.write(rendered);
97
141
  else {
98
142
  const destination = resolve(output);
99
- await mkdir(resolve(destination, '..'), { recursive: true });
143
+ await mkdir(dirname(destination), { recursive: true });
100
144
  await writeFile(destination, rendered, 'utf8');
101
145
  io.write(`Wrote preflight report to ${destination}`);
102
146
  }
@@ -108,6 +152,10 @@ export async function runCli(argv, io = { write: (line) => console.log(line) })
108
152
  io.write(usage);
109
153
  return 0;
110
154
  }
155
+ if (command === '--version') {
156
+ io.write(packageVersion());
157
+ return 0;
158
+ }
111
159
  if (!commands.has(command)) {
112
160
  io.write(`Unknown command: ${command}`);
113
161
  return 2;
@@ -1,13 +1,14 @@
1
- import { createReportView } from './report-view.js';
1
+ import { createElement } from 'react';
2
+ import { ReportView } from './report-view.js';
2
3
  export const name = 'dsh-composition-doctor';
3
4
  export const registration = Object.freeze({
4
5
  id: name,
5
6
  actions: ['export-json', 'export-markdown'],
6
- component: () => createReportView()
7
+ component: () => createElement(ReportView, { translate: (key) => key })
7
8
  });
8
9
  export const apply = Object.assign((ctx) => {
9
10
  const messages = {
10
- zh: { title: 'DSH 组合医生', exportJson: '导出 JSON', exportMarkdown: '导出 Markdown' },
11
+ zh: { title: 'DSH Composition Doctor', exportJson: '导出 JSON', exportMarkdown: '导出 Markdown' },
11
12
  en: { title: 'DSH Composition Doctor', exportJson: 'Export JSON', exportMarkdown: 'Export Markdown' }
12
13
  };
13
14
  const disposeLocale = ctx.locale?.register('dshCompositionDoctor', messages);
@@ -15,7 +16,7 @@ export const apply = Object.assign((ctx) => {
15
16
  const disposeSlot = ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
16
17
  name: 'settings.plugins.tab', id: registration.id, order: 70,
17
18
  locale: 'dshCompositionDoctor', label: () => t('title')
18
- }, () => createReportView(undefined, t)));
19
+ }, () => createElement(ReportView, { translate: t })));
19
20
  return () => {
20
21
  if (typeof disposeSlot === 'function')
21
22
  disposeSlot();
@@ -1,5 +1,20 @@
1
+ import { createElement, useEffect, useRef } from 'react';
1
2
  import { renderMarkdown } from '../reports/markdown.js';
2
3
  export const clientReportPath = '/dsh-composition-doctor/reports/latest';
4
+ export const downloadRevokeDelayMs = 1000;
5
+ export function evidenceBadgeLabel(mode, runtimeObserved) {
6
+ if (mode === 'runtime-observed' && runtimeObserved)
7
+ return 'runtime-observed';
8
+ if (mode === 'runtime-observed')
9
+ return 'composed; runtime not observed';
10
+ if (mode === 'composed')
11
+ return 'composed; runtime not observed';
12
+ if (mode === 'mixed')
13
+ return runtimeObserved ? 'mixed; runtime observed' : 'mixed; runtime not observed';
14
+ if (mode === 'resolved')
15
+ return 'legacy resolved; runtime not observed';
16
+ return 'static';
17
+ }
3
18
  export function buildConflictGraph(report) {
4
19
  const nodes = new Map();
5
20
  const edges = [];
@@ -22,6 +37,28 @@ export function toReportViewModel(report) {
22
37
  counts[diagnostic.severity] += 1;
23
38
  return { report, counts, graph: buildConflictGraph(report) };
24
39
  }
40
+ function renderConflictGraph(document, graph) {
41
+ const section = document.createElement('section');
42
+ section.setAttribute('aria-labelledby', 'dsh-composition-doctor-conflict-graph');
43
+ const heading = document.createElement('h3');
44
+ heading.id = 'dsh-composition-doctor-conflict-graph';
45
+ heading.textContent = 'Conflict graph';
46
+ section.append(heading);
47
+ const list = document.createElement('ul');
48
+ for (const node of graph.nodes) {
49
+ const item = document.createElement('li');
50
+ const outgoing = graph.edges.filter((edge) => edge.from === node.id).map((edge) => graph.nodes.find((candidate) => candidate.id === edge.to)?.label ?? edge.to);
51
+ item.textContent = `${node.label} (${node.source})${outgoing.length === 0 ? '' : ` → ${outgoing.join(', ')}`}`;
52
+ list.append(item);
53
+ }
54
+ if (graph.nodes.length === 0) {
55
+ const item = document.createElement('li');
56
+ item.textContent = 'No evidence relationships were produced.';
57
+ list.append(item);
58
+ }
59
+ section.append(list);
60
+ return section;
61
+ }
25
62
  function isReport(value) {
26
63
  if (value === null || typeof value !== 'object')
27
64
  return false;
@@ -47,12 +84,37 @@ async function fetchReport(fetcher = globalThis.fetch) {
47
84
  throw new Error('The latest report has an unsupported schema.');
48
85
  return value;
49
86
  }
50
- function download(document, content, filename, mime) {
87
+ const browserDownloadHooks = {
88
+ createObjectURL: (blob) => URL.createObjectURL(blob),
89
+ revokeObjectURL: (url) => URL.revokeObjectURL(url),
90
+ schedule: (callback, delay) => globalThis.setTimeout(callback, delay)
91
+ };
92
+ /** Create a local browser download without sending report data anywhere. */
93
+ export function download(document, content, filename, mime, hooks = browserDownloadHooks) {
94
+ const blob = new Blob([content], { type: mime });
51
95
  const link = document.createElement('a');
52
- link.href = URL.createObjectURL(new Blob([content], { type: mime }));
96
+ const objectUrl = hooks.createObjectURL(blob);
97
+ link.hidden = true;
98
+ link.href = objectUrl;
53
99
  link.download = filename;
54
- link.click();
55
- URL.revokeObjectURL(link.href);
100
+ document.body.append(link);
101
+ try {
102
+ link.click();
103
+ }
104
+ finally {
105
+ link.remove();
106
+ hooks.schedule(() => hooks.revokeObjectURL(objectUrl), downloadRevokeDelayMs);
107
+ }
108
+ }
109
+ export async function exportReport(document, format, dependencies = {}) {
110
+ const report = await fetchReport(dependencies.fetcher);
111
+ if (format === 'json') {
112
+ ;
113
+ (dependencies.download ?? download)(document, `${JSON.stringify(report, null, 2)}\n`, 'dsh-composition-doctor-report.json', 'application/json');
114
+ return;
115
+ }
116
+ ;
117
+ (dependencies.download ?? download)(document, renderMarkdown(report), 'dsh-composition-doctor-report.md', 'text/markdown');
56
118
  }
57
119
  /**
58
120
  * Browser-native settings section. It only performs a GET and offers local
@@ -60,7 +122,7 @@ function download(document, content, filename, mime) {
60
122
  */
61
123
  export function createReportView(document = globalThis.document, translate = (key) => ({
62
124
  title: 'DSH Composition Doctor', exportJson: 'Export JSON', exportMarkdown: 'Export Markdown', loading: 'Loading the latest local report…', unavailable: 'The latest report is unavailable.'
63
- }[key] ?? key)) {
125
+ }[key] ?? key), dependencies = {}) {
64
126
  const root = document.createElement('section');
65
127
  root.dataset.plugin = nameForDom;
66
128
  root.setAttribute('aria-labelledby', 'dsh-composition-doctor-title');
@@ -72,21 +134,58 @@ export function createReportView(document = globalThis.document, translate = (ke
72
134
  status.textContent = translate('loading');
73
135
  root.append(status);
74
136
  const actions = document.createElement('p');
75
- actions.append(button(document, translate('exportJson'), () => { void fetchReport().then((report) => download(document, `${JSON.stringify(report, null, 2)}\n`, 'dsh-composition-doctor-report.json', 'application/json')).catch(() => undefined); }), text(document, ' '), button(document, translate('exportMarkdown'), () => { void fetchReport().then((report) => download(document, renderMarkdown(report), 'dsh-composition-doctor-report.md', 'text/markdown')).catch(() => undefined); }));
137
+ actions.append(button(document, translate('exportJson'), () => { void exportReport(document, 'json', dependencies).catch(() => undefined); }), text(document, ' '), button(document, translate('exportMarkdown'), () => { void exportReport(document, 'markdown', dependencies).catch(() => undefined); }));
76
138
  root.append(actions);
77
- void fetchReport().then((report) => {
139
+ void fetchReport(dependencies.fetcher).then((report) => {
78
140
  const model = toReportViewModel(report);
79
- status.textContent = `Diagnostics: ${model.counts.error} error, ${model.counts.warning} warning, ${model.counts.info} info. Conflict graph: ${model.graph.nodes.length} evidence nodes.`;
141
+ const badge = document.createElement('span');
142
+ badge.dataset.evidenceKind = report.evidenceMode;
143
+ badge.setAttribute('aria-label', 'Evidence capability');
144
+ badge.textContent = `Evidence: ${evidenceBadgeLabel(report.evidenceMode, report.runtimeObserved === true)}`;
145
+ status.textContent = `Generated: ${report.generatedAt}. Profile: ${report.profileDir}. Diagnostics: ${model.counts.error} error, ${model.counts.warning} warning, ${model.counts.info} info.`;
146
+ status.append(document.createTextNode(' '), badge);
147
+ root.append(renderConflictGraph(document, model.graph));
80
148
  const list = document.createElement('ul');
81
149
  for (const diagnostic of report.diagnostics) {
82
150
  const item = document.createElement('li');
83
- item.textContent = `[${diagnostic.severity}] ${diagnostic.title}`;
151
+ const details = document.createElement('details');
152
+ const summary = document.createElement('summary');
153
+ summary.textContent = `[${diagnostic.severity}] ${diagnostic.title}`;
154
+ details.append(summary);
155
+ const explanation = document.createElement('p');
156
+ explanation.textContent = diagnostic.explanation;
157
+ const evidence = document.createElement('pre');
158
+ evidence.textContent = diagnostic.evidence.map((entry) => `${entry.source}: ${entry.detail}`).join('\n') || 'No concrete evidence.';
159
+ const remediation = document.createElement('p');
160
+ remediation.textContent = `Remediation: ${diagnostic.remediation}`;
161
+ details.append(explanation, evidence, remediation);
162
+ item.append(details);
84
163
  list.append(item);
85
164
  }
86
165
  root.append(list);
87
- }).catch((error) => {
88
- status.textContent = error instanceof Error ? error.message : translate('unavailable');
166
+ }).catch(() => {
167
+ status.textContent = translate('unavailable');
89
168
  });
90
169
  return root;
91
170
  }
171
+ /**
172
+ * DSH settings slots are rendered by React. Keep the browser-native report
173
+ * view as the implementation detail, but mount it through a React component
174
+ * rather than returning an HTMLElement directly to the slot renderer.
175
+ */
176
+ export function ReportView({ translate }) {
177
+ const host = useRef(null);
178
+ useEffect(() => {
179
+ const container = host.current;
180
+ if (container === null)
181
+ return;
182
+ const view = createReportView(globalThis.document, translate);
183
+ container.replaceChildren(view);
184
+ return () => {
185
+ view.remove();
186
+ container.replaceChildren();
187
+ };
188
+ }, [translate]);
189
+ return createElement('div', { className: 'dsh-composition-doctor-report-view', ref: host });
190
+ }
92
191
  const nameForDom = 'dsh-composition-doctor';