dsh-drydock 1.0.4 → 1.1.0-desktop.3

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/README.en.md CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  > Community plugin — not an official DSH package. npm: `dsh-drydock` (formerly `dsh-plugin-manager-pro`, which is deprecated on npm but not deleted; kept for installing historical versions) · GitHub: [nonentity303/dsh-drydock](https://github.com/nonentity303/dsh-drydock) · Cross-platform (Windows / macOS / Linux).
12
12
  >
13
- > **Current version: 1.0.4** (`npm view dsh-drydock version`; tags: <https://github.com/nonentity303/dsh-drydock/tags>).
13
+ > **Current version: 1.1.0-desktop.3** (desktop channel; `npm view dsh-drydock dist-tags`; tags: <https://github.com/nonentity303/dsh-drydock/tags>).
14
14
  > ⚠️ A brand-new release is blocked by pnpm's **24 h cool-down** (`minimumReleaseAge`) — pin the version explicitly if it does not install (see "Install" below).
15
15
 
16
16
  ## Four signature features
package/README.md CHANGED
@@ -10,8 +10,9 @@
10
10
 
11
11
  > 社区/本地插件,非 DSH 官方包。npm:`dsh-drydock`(原名 `dsh-plugin-manager-pro`,旧包已挂弃用提示、不删包,仅保留供历史版本安装)· GitHub:[nonentity303/dsh-drydock](https://github.com/nonentity303/dsh-drydock) · 跨平台(Windows / macOS / Linux)
12
12
  >
13
- > **本页对应版本:1.0.4**(核对:`npm view dsh-drydock version`;标签见 <https://github.com/nonentity303/dsh-drydock/tags>)
13
+ > **本页对应版本:1.1.0-desktop.3**(桌面通道;`npm view dsh-drydock dist-tags` 可核对;标签见 <https://github.com/nonentity303/dsh-drydock/tags>)
14
14
  > ⚠️ 刚发布的版本会被 pnpm 的 **24 小时冷静期**(`minimumReleaseAge`)挡住:装不到或装完还是旧版时,**显式写版本号**(见下方安装)。
15
+ > 版本与通道口径见 [docs/版本与轨道.md](docs/版本与轨道.md):`-desktop.N` = 桌面通道、`-rc.N` = 网页预发布、无后缀 = 正式版。
15
16
 
16
17
  ## 四个主打特色
17
18
 
@@ -30,14 +31,18 @@
30
31
  ## 安装(30 秒)
31
32
 
32
33
  ```sh
33
- # 推荐:显式版本号,不会被 24 小时冷静期挡住
34
+ # 网页版(正式版通道,= npm latest)
34
35
  dsh plugin --profile web add dsh-drydock@1.0.4
35
-
36
- # 发版满 24 小时后,也可以用 latest
36
+ # 发版满 24 小时后,也可以不带版本号
37
37
  dsh plugin --profile web add dsh-drydock
38
38
 
39
+ # 桌面版(DSH Desktop,独立 profile;桌面通道 = npm dist-tag desktop)
40
+ # 1) 先启动一次桌面版以初始化 profiles/desktop → 2) 从系统托盘**完全退出**
41
+ # 3) 用桌面版自带 CLI(不是 npm 的 dsh)执行,4) 重开桌面版并在设置里确认插件已启用
42
+ dsh plugin --profile desktop add dsh-drydock@desktop
43
+
39
44
  # 离线 tgz(GitHub Release 页下载,或 npm pack 自建)
40
- dsh plugin --profile web add ./dsh-drydock-1.0.4.tgz
45
+ dsh plugin --profile web add ./dsh-drydock-<版本>.tgz
41
46
 
42
47
  # 回退上一个正式版(1.0.x 之间回退走同一包名)
43
48
  dsh plugin --profile web add dsh-drydock@1.0.3
@@ -49,8 +54,26 @@ dsh web
49
54
  装好后两个入口:**3080 侧边栏「插件管理」**(接管引擎内置插件页)与 **3081 兜底页** `http://127.0.0.1:3081/plugins`。浏览器主页设为 `http://127.0.0.1:3081/` = 打开即自检 → 修复 → 启动 → 跳转主界面。
50
55
 
51
56
  - **不想装进 profile?** `npx dsh-drydock` 起 3081 启动器、`npx dsh-drydock-boot --repair-only` 命令行自检 + 修复、`npx dsh-drydock-rescue` 起 3082 备份救援——都无需安装。
57
+ - **它自己怎么升级?** `npx dsh-drydock-update --check` 查、`--fetch` 校验暂存、`--now` 现在装(停引擎→装→健康检查→重启,失败自动回滚)、`--later` 稍后(下次启动再提示)。只认 https + SRI 摘要,桌面形态不自动装。→ [docs/自更新.md](docs/自更新.md)
52
58
  - **装不到 / 装完还是旧版?** ① 客户端 bundle 只在引擎启动时加载,**必须重启 `dsh web`**;② 24 小时冷静期内务必写显式版本号(或把 `dsh-drydock@1.0.4` 加入 profile `pnpm-workspace.yaml` 的 `minimumReleaseAgeExclude`)。完整安装 / 更新 / 卸载 / 回退 / 离线 tgz / 开机自启见 [docs/INSTALL.md](docs/INSTALL.md)。
53
59
 
60
+ ## 桌面版(DSH Desktop)支持(1.1.0 新增)
61
+
62
+ > 桌面版官方已把安装 / 启停 / 更新 / 卸载 / 崩溃恢复吃进 app,所以 drydock 在桌面只做**官方覆盖不到**的三件事:
63
+ > **离线只读诊断、官方恢复后自愈、走官方通道重建救援 profile**(不接管插件页 / 不自启 / 不拉起或停止 Host / 不写 `node_modules`)。
64
+
65
+ ```sh
66
+ npx dsh-drydock-doctor # ① 离线只读诊断(--json 可贴进 issue)
67
+ npx dsh-drydock-boot --heal-recovery [--apply --confirm web] # ② 官方恢复后自愈(默认 dry-run)
68
+ npx dsh-drydock-boot --rescue-profile # ③ 官方通道重建救援 profile(桌面形态拒绝执行)
69
+ npx dsh-drydock-modules --audit # ④ 本环境永远不会执行的文件 + 行数(首启已自动探测)
70
+ ```
71
+
72
+ **首启环境探测 + 自动剥离(本版新增)**:装完第一次启动即探测宿主形态(web / desktop / unknown)并落盘,
73
+ **不属于本形态的模块连 `import` 都不发生**(实测桌面形态整体剥离 `lib/rescue-profile.mjs` 1331 行)。
74
+ → [docs/环境自适应与剥离.md](docs/环境自适应与剥离.md) · [docs/桌面版移植-1.1.0设计.md](docs/桌面版移植-1.1.0设计.md)
75
+ > ⚠️ 桌面能力有 fixture + 注入式单测覆盖,但**真机链路未验收**:首次请先跑 `dsh-drydock-doctor`。
76
+
54
77
  ## 升级自查(0.9.1 之前的老用户必看)
55
78
 
56
79
  > ⛔ **0.9.1 之前的 `dsh-plugin-manager-pro`(含 `0.9.1-rc2`)已淘汰**:存在已知供应链风险,且 Node < 22.14 加载即崩。npm 上已挂**强化弃用提示**(不删包,历史版本仍可安装,但**不要用**)。
@@ -127,9 +150,12 @@ dsh web # 重启生效
127
150
  | [docs/FAQ.md](docs/FAQ.md) | 常见问题与排错(含旧包升级问题) |
128
151
  | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | 三进程架构、槽位契约、侧车字段、卸载事务数据流 |
129
152
  | [docs/LAUNCHER.md](docs/LAUNCHER.md) | 三个 bin 的全部命令与退出码、`--uninstall` 闭环、写接口防护 |
130
- | [docs/RELEASING.md](docs/RELEASING.md) | 发布流程 |
153
+ | [docs/RELEASING.md](docs/RELEASING.md) | 发布流程(§11 多通道发布:dist-tag 由 `release/channels.json` 派生) |
154
+ | [docs/版本与轨道.md](docs/版本与轨道.md) | 三条发布通道(web / desktop / community)、版本号怎么升、各通道安装命令 |
155
+ | [docs/环境自适应与剥离.md](docs/环境自适应与剥离.md) | 首启环境探测、能力表、环境专属模块的惰性装载与剥离清单(死代码审查输入) |
156
+ | [docs/自更新.md](docs/自更新.md) | 自更新:权威源 + SRI 校验 + 现在/稍后 + detached worker(停引擎→装→健康检查→重启→失败回滚) |
131
157
  | [CHANGELOG.md](CHANGELOG.md) | 版本历史(脚本生成) |
132
- | [docs/releases/](docs/releases/) | 每版发布说明(本页对应 [1.0.4](docs/releases/1.0.4.md)) |
158
+ | [docs/releases/](docs/releases/) | 每版发布说明(本页对应 [1.1.0-desktop.3](docs/releases/1.1.0-desktop.3.md)) |
133
159
  | [docs/README-full.md](docs/README-full.md) | 0.9.1 时代完整存档(能力对比 / 兼容矩阵全文),**非当前手册** |
134
160
 
135
161
  ## 许可证
@@ -0,0 +1,307 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * drydock-doctor.mjs — 离线只读诊断报告 CLI(1.1.0 桌面版支持 M4)。
4
+ *
5
+ * 设计目标(用户视角):Electron 起不来的时候,普通用户不会开终端、不知道 DSH_HOME
6
+ * 在哪、看不懂 cordis.patch.yml、连日志在哪也不知道。这条命令要能一条命令产出
7
+ * **一份用户能直接粘贴给插件作者/官方**的诊断文本,且**零风险**:
8
+ * - 默认只把中文报告打到 stdout,**不落盘**;
9
+ * - 不写 profile、不启停进程、不解析日志取 token(详见 lib/diagnostics.mjs 的只读承诺)。
10
+ *
11
+ * 用法(对齐 bin/dsh-boot.mjs 的风格:--help / isDirectRun() 保护 / 退出码语义):
12
+ * node bin/drydock-doctor.mjs 人读中文报告(stdout)
13
+ * node bin/drydock-doctor.mjs --json 机器可读 JSON(stdout)
14
+ * node bin/drydock-doctor.mjs --out <file> 同时落盘(默认不落盘;落盘路径打印到 stderr)
15
+ * node bin/drydock-doctor.mjs --profile web 聚焦某个 profile(名称或目录)
16
+ * node bin/drydock-doctor.mjs --home D:\x 覆盖 DSH_HOME
17
+ * node bin/drydock-doctor.mjs --include-logs / --no-logs 是否包含日志尾部(默认不含)
18
+ *
19
+ * 退出码:
20
+ * 0 = 收集完成(**即使有 unavailable 段**也算成功:缺数据不等于失败)
21
+ * 1 = 完全无法定位 DSH_HOME(或 --out 报告落盘失败)
22
+ * 2 = 参数错误(未知参数 / 选项缺取值 / --include-logs 与 --no-logs 互斥)
23
+ *
24
+ * 注意:本文件**不注册进 package.json 的 bin**(那是共享文件,由 lead 统一改);
25
+ * 建议的 bin 行见交付说明。
26
+ */
27
+ import { realpathSync, writeFileSync } from "node:fs";
28
+ import { resolve, sep } from "node:path";
29
+ import { fileURLToPath } from "node:url";
30
+ import { collectDiagnostics, defaultResourcesDirs, renderReport, SCHEMA } from "../lib/diagnostics.mjs";
31
+ import { hostProfilePath, readHostProfile, resolveHostForm } from "../lib/host-profile.mjs";
32
+ import { auditModules } from "../lib/host-registry.mjs";
33
+
34
+ const SELF = fileURLToPath(import.meta.url);
35
+
36
+ const HELP_TEXT = `dsh-drydock 离线只读诊断报告(drydock-doctor)
37
+
38
+ 用法:
39
+ node bin/drydock-doctor.mjs [选项]
40
+
41
+ 选项:
42
+ --json 输出机器可读 JSON(默认输出人读中文报告)
43
+ --out <file> 同时把报告写入文件(默认不落盘;落盘绝对路径打印到 stderr)
44
+ --profile <name|dir>
45
+ 只聚焦某个 profile(名称如 web / desktop,或直接给目录)
46
+ --home <dir> 覆盖 DSH_HOME(默认按 $DSH_HOME > ~/.dsh 解析)
47
+ --include-logs 包含引擎日志尾部(每 profile 最多 64 KiB,官方 stderr 口径)
48
+ --no-logs 不包含引擎日志尾部(默认行为;与 --include-logs 互斥)
49
+ --help, -h 显示本帮助
50
+
51
+ 报告内容(数据源按官方桌面版诊断文档 + 真包静态分析):
52
+ · 环境 / DSH_HOME 与全部候选(解析优先级:--home > $DSH_HOME > ~/.dsh)
53
+ · profile 清单:package.json、cordis.patch.yml(大小/BOM/是否空 patch/条目数)、
54
+ lock、.open-boot.pid、drydock 侧车 plugin-manager.json、.dsh-market/state.json
55
+ · 桌面 profile 状态:是否初始化、lock 内容(截断 200 字符)、dsh.profile.bundles
56
+ · 桌面宿主:安装目录 resources/app.asar/dsh/desktop-runtime.json 的 release
57
+ (version / hostProtocolVersion / nodeVersion / pnpmVersion,只读前部、不整读 4.7 MB)、
58
+ resources/runtime/versions.json、桌面自带 CLI(不是 npm 的 dsh)
59
+ · 官方恢复痕迹检测(空 patch + cordis.patch.yml.bak-<时间戳> → 建议"恢复后自愈")
60
+ · 崩溃报告 <userData>/logs/crash-<UTC>-<source>.log(最新 3 份,每份只读前 4 KiB)
61
+ · 插件操作记录 <userData>/plugin-operations(最多 100 条 / 64 KiB)
62
+ · 端口事实:候选端口清单 + 每个端口是否有监听(**不**据此断言引擎健康)
63
+
64
+ 退出码:
65
+ 0 = 收集完成(即使有"不可用"段)
66
+ 1 = 完全无法定位 DSH_HOME(或报告落盘失败)
67
+ 2 = 参数错误(含 --out 指向桌面安装目录:那里只读,拒绝写入)
68
+
69
+ 示例:
70
+ node bin/drydock-doctor.mjs --profile desktop --json --out .\\doctor.json
71
+ node bin/drydock-doctor.mjs --home "D:\\dsh-home" --include-logs
72
+ DSH_DESKTOP_RESOURCES_DIR="C:\\...\\resources" node bin/drydock-doctor.mjs # 已解包的安装目录
73
+
74
+ 说明:报告已脱敏(令牌/密钥/邮箱/绝对路径里的用户名);含"不可用"段属正常,
75
+ 表示那一项在你这台机器上不存在(例如没装桌面版就没有崩溃报告)。
76
+ 桌面安装目录里的 app.asar / desktop-runtime.json 只读,不会写;--out 默认不落盘,
77
+ 显式落盘时写到用户指定路径(落在桌面安装目录会被拒绝)。
78
+ `;
79
+
80
+ /**
81
+ * 解析 argv。错误进 `errors`(由 main 转成退出码 2),不在解析阶段直接退出。
82
+ */
83
+ function parseArgs(argv) {
84
+ const args = {
85
+ help: false,
86
+ json: false,
87
+ out: null,
88
+ profile: null,
89
+ home: null,
90
+ includeLogs: false,
91
+ errors: []
92
+ };
93
+ const wantValue = (option, index) => {
94
+ const value = argv[index + 1];
95
+ if (value === undefined || value === "" || (value.startsWith("-") && value !== "-")) {
96
+ args.errors.push(`选项 ${option} 缺少取值`);
97
+ return null;
98
+ }
99
+ return value;
100
+ };
101
+ let sawInclude = false;
102
+ let sawNoLogs = false;
103
+ for (let index = 0; index < argv.length; index += 1) {
104
+ const argument = argv[index];
105
+ switch (argument) {
106
+ case "--help":
107
+ case "-h":
108
+ args.help = true;
109
+ break;
110
+ case "--json":
111
+ args.json = true;
112
+ break;
113
+ case "--include-logs":
114
+ sawInclude = true;
115
+ break;
116
+ case "--no-logs":
117
+ sawNoLogs = true;
118
+ break;
119
+ case "--out": {
120
+ const value = wantValue(argument, index);
121
+ if (value !== null) {
122
+ args.out = value;
123
+ index += 1;
124
+ }
125
+ break;
126
+ }
127
+ case "--profile": {
128
+ const value = wantValue(argument, index);
129
+ if (value !== null) {
130
+ args.profile = value;
131
+ index += 1;
132
+ }
133
+ break;
134
+ }
135
+ case "--home": {
136
+ const value = wantValue(argument, index);
137
+ if (value !== null) {
138
+ args.home = value;
139
+ index += 1;
140
+ }
141
+ break;
142
+ }
143
+ default:
144
+ if (argument.startsWith("-")) args.errors.push(`无法识别的参数 ${argument}`);
145
+ else args.errors.push(`多余的位置参数 ${argument}`);
146
+ break;
147
+ }
148
+ }
149
+ if (sawInclude && sawNoLogs) args.errors.push("--include-logs 与 --no-logs 互斥,只能选一个");
150
+ args.includeLogs = sawInclude;
151
+ return args;
152
+ }
153
+
154
+ /**
155
+ * 桌面安装目录只读:`--out` 落在 `<安装目录>/resources` 里一律拒绝(app.asar / desktop-runtime.json
156
+ * 只读)。返回"包含该目标的安装目录"或 null。
157
+ */
158
+ function installDirContaining(target) {
159
+ const normalized = target.replace(/\//g, "\\").toLowerCase();
160
+ for (const dir of defaultResourcesDirs({})) {
161
+ const base = dir.replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase();
162
+ if (normalized === base || normalized.startsWith(`${base}\\`)) return dir;
163
+ }
164
+ return null;
165
+ }
166
+
167
+ /**
168
+ * 环境剥离审计段(**只读**:不写 host-profile、不 import 任何环境专属模块)。
169
+ *
170
+ * 与 `bin/drydock-modules.mjs` 的分工:那条命令会**写**首启画像(它是"首次启动探测"的执行者),
171
+ * 而本命令的只读承诺不能被打破(`test-diagnostics.mjs` 有"跑完 fixture 一字节不变"的断言)。
172
+ * 所以这里只做两件事:读已有画像(没有就干跑一次探测、不落盘)+ 算剥离清单。
173
+ */
174
+ function collectHostStrip({ dshHome }) {
175
+ const home = typeof dshHome === "string" && dshHome !== "" ? dshHome : null;
176
+ const cached = home === null ? null : readHostProfile({ dshHome: home });
177
+ let form = null;
178
+ let source = "cache";
179
+ let reason = "";
180
+ let confidence = null;
181
+ if (cached !== null) {
182
+ form = cached.form;
183
+ reason = cached.reason;
184
+ confidence = cached.confidence ?? null;
185
+ } else {
186
+ // 没有画像 → 干跑一次探测(`resolveHostForm` 只读盘,不写任何文件);标记"尚未落盘"。
187
+ const resolved = resolveHostForm();
188
+ form = resolved.form;
189
+ source = "probe(尚未落盘,首次启动会写入)";
190
+ reason = resolved.reason;
191
+ confidence = resolved.confidence ?? null;
192
+ }
193
+ const audit = auditModules(form);
194
+ return {
195
+ profileFile: home === null ? null : hostProfilePath(home),
196
+ persisted: cached !== null,
197
+ form,
198
+ source,
199
+ reason,
200
+ confidence,
201
+ profiledAt: cached?.profiledAt ?? null,
202
+ loadable: audit.loadable.map((m) => ({ id: m.id, file: m.file, lines: m.lines, capability: m.capability })),
203
+ stripped: audit.stripped.map((m) => ({ id: m.id, file: m.file, lines: m.lines, capability: m.capability, value: m.value, reason: m.reason })),
204
+ totalLoadableLines: audit.totalLoadableLines,
205
+ totalStrippedLines: audit.totalStrippedLines
206
+ };
207
+ }
208
+
209
+ function renderHostStrip(strip) {
210
+ if (!strip) return "";
211
+ const lines = [];
212
+ lines.push("");
213
+ lines.push("## 环境剥离(哪些代码在当前宿主上不会执行)");
214
+ lines.push(`- 宿主形态:${strip.form}(${strip.source}${strip.persisted ? `,画像已落盘:${strip.profileFile}` : ",画像尚未落盘"})`);
215
+ if (strip.reason) lines.push(`- 判定理由(截断):${String(strip.reason).slice(0, 200)}`);
216
+ lines.push(`- 装载:${strip.loadable.map((m) => m.id).join(", ") || "(无)"}(${strip.totalLoadableLines} 行)`);
217
+ if (strip.stripped.length === 0) {
218
+ lines.push("- 剥离:无(所有登记模块都适用)");
219
+ } else {
220
+ lines.push(`- 剥离(连 import 都不发生,共 ${strip.totalStrippedLines} 行):`);
221
+ for (const item of strip.stripped) {
222
+ lines.push(` · ${item.id} — ${item.lines ?? "?"} 行 [${item.capability}=${JSON.stringify(item.value)}]`);
223
+ lines.push(` 理由:${item.reason}`);
224
+ }
225
+ }
226
+ lines.push("- 完整清单 / 强制重探测:`npx dsh-drydock-modules`(`--audit` 只看剥离,`--refresh` 重探测)");
227
+ return `${lines.join("\n")}\n`;
228
+ }
229
+
230
+ async function main() {
231
+ const args = parseArgs(process.argv.slice(2));
232
+ if (args.help) {
233
+ process.stdout.write(HELP_TEXT);
234
+ return 0;
235
+ }
236
+ if (args.errors.length > 0) {
237
+ console.error(`[drydock-doctor] 参数错误:${args.errors.join(";")}`);
238
+ console.error("[drydock-doctor] 用 --help 查看用法。");
239
+ return 2;
240
+ }
241
+ const outTarget = args.out ? resolve(args.out) : null;
242
+ if (outTarget) {
243
+ const blocked = installDirContaining(outTarget);
244
+ if (blocked) {
245
+ console.error(`[drydock-doctor] 拒绝把报告写进桌面安装目录:${outTarget}`);
246
+ console.error(`[drydock-doctor] 安装目录(${blocked})里的 app.asar / desktop-runtime.json 只读;请换一个输出路径。退出码 2`);
247
+ return 2;
248
+ }
249
+ }
250
+
251
+ const diagnostics = await collectDiagnostics({
252
+ dshHome: args.home,
253
+ profile: args.profile,
254
+ includeLogs: args.includeLogs
255
+ });
256
+ const hostStrip = collectHostStrip({ dshHome: typeof diagnostics.home?.resolved === "string" ? diagnostics.home.resolved : args.home });
257
+ const text = args.json
258
+ ? JSON.stringify({ ...diagnostics, hostStrip }, null, 2)
259
+ : `${renderReport(diagnostics)}${renderHostStrip(hostStrip)}`;
260
+ process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
261
+
262
+ if (args.out) {
263
+ const target = outTarget ?? resolve(args.out);
264
+ try {
265
+ writeFileSync(target, text.endsWith("\n") ? text : `${text}\n`, "utf8");
266
+ } catch (error) {
267
+ // 落盘失败不影响已经打到 stdout 的报告;但明确报错 + 非 0 退出,绝不静默
268
+ console.error(`[drydock-doctor] 报告落盘失败:${target}(${error.code ?? error.message});上面的报告仍已输出到 stdout。`);
269
+ return 1;
270
+ }
271
+ console.error(`[drydock-doctor] 报告已写入:${target}(未使用 --out 时默认不落盘)`);
272
+ }
273
+
274
+ if (!diagnostics.home.resolved) {
275
+ console.error(`[drydock-doctor] 无法定位 DSH_HOME(见报告「DSH_HOME」段):可用 --home <dir> 指定。退出码 1`);
276
+ return 1;
277
+ }
278
+ return 0;
279
+ }
280
+
281
+ /**
282
+ * 只在"直接运行本文件"时执行入口(被 import 时不执行,便于测试)。
283
+ * 语义与 bin/dsh-boot.mjs:151-162 完全对齐(同一判定,不另写一套)。
284
+ */
285
+ function isDirectRun() {
286
+ if (process.env.DSH_LAUNCHER_IMPORT_ONLY === "1") return false;
287
+ const entry = process.argv[1];
288
+ if (!entry) return false;
289
+ const norm = (path) => {
290
+ try {
291
+ return realpathSync(path).replace(/\\/g, "/").toLowerCase();
292
+ } catch {
293
+ try {
294
+ return resolve(path).replace(/\\/g, "/").toLowerCase();
295
+ } catch {
296
+ return path;
297
+ }
298
+ }
299
+ };
300
+ return norm(entry) === norm(SELF);
301
+ }
302
+
303
+ if (isDirectRun()) {
304
+ process.exit(await main());
305
+ }
306
+
307
+ export { HELP_TEXT, SCHEMA, main, parseArgs };
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-drydock-modules — 环境剥离审计(1.1.0 起)
4
+ *
5
+ * 回答三个问题,一条命令:
6
+ * 1. 这台机器上的 drydock 认为自己跑在**哪种宿主**(web / desktop / unknown),凭什么这么判;
7
+ * 2. 按该形态,**哪些环境专属模块会被装载、哪些被剥离**(剥离 = 连 import 都不发生);
8
+ * 3. 「本环境永远不会执行的代码」共有多少行、分别是哪些文件 —— 这就是"死代码审查"的输入清单。
9
+ *
10
+ * 用法:
11
+ * npx dsh-drydock-modules # 人读报告(不 import 任何环境专属模块)
12
+ * npx dsh-drydock-modules --json # 机器可读(CI / issue 里可直接贴)
13
+ * npx dsh-drydock-modules --audit # 只列被剥离的文件 + 行数 + 理由
14
+ * npx dsh-drydock-modules --refresh # 强制重新探测并覆盖画像(换机器/换安装方式后用)
15
+ * npx dsh-drydock-modules --load # 真正装载适用模块(验证"该装的装得起来")
16
+ * npx dsh-drydock-modules --profile <名> # 只看某个 profile 的判定?—— 本命令是**机器级**的,不吃 profile
17
+ *
18
+ * 退出码:0 = 正常;1 = 装载失败(仅 --load);2 = 用法错误。
19
+ */
20
+ import { ensureHostProfile, hostProfilePath, HOST_PROFILE_TTL_MS } from "../lib/host-profile.mjs";
21
+ import { auditModules, loadModules } from "../lib/host-registry.mjs";
22
+
23
+ const HELP = `用法: dsh-drydock-modules [--json] [--audit] [--refresh] [--load]
24
+
25
+ (默认) 人读报告:形态判定 + 装载/剥离清单 + 剥离行数
26
+ --json 机器可读(含 evidence 与每个模块的行数)
27
+ --audit 只列被剥离的文件、行数与理由
28
+ --refresh 强制重新探测并覆盖 host-profile.json
29
+ --load 真正 import 适用模块(默认只算不装)
30
+ --help 本帮助
31
+
32
+ 画像文件:<DSH_HOME>/.drydock/host-profile.json(机器级;TTL ${Math.round(HOST_PROFILE_TTL_MS / 86400000)} 天)`;
33
+
34
+ function main(argv = process.argv.slice(2)) {
35
+ const known = ["--json", "--audit", "--refresh", "--load", "--help", "-h"];
36
+ const unknown = argv.filter((a) => !known.includes(a));
37
+ if (unknown.length > 0) {
38
+ console.error(`未知参数:${unknown.join(" ")}\n\n${HELP}`);
39
+ return 2;
40
+ }
41
+ if (argv.includes("--help") || argv.includes("-h")) {
42
+ console.log(HELP);
43
+ return 0;
44
+ }
45
+
46
+ const json = argv.includes("--json");
47
+ const auditOnly = argv.includes("--audit");
48
+ const refresh = argv.includes("--refresh");
49
+
50
+ const ensured = ensureHostProfile({ force: refresh });
51
+ const form = ensured.profile.form;
52
+ const audit = auditModules(form);
53
+ const file = hostProfilePath(ensured.profile.dshHome ?? "");
54
+
55
+ return run({ json, auditOnly, refresh, ensured, form, audit, file, argv }).catch((error) => {
56
+ console.error(`环境剥离审计失败:${error instanceof Error ? error.message : String(error)}`);
57
+ return 1;
58
+ });
59
+ }
60
+
61
+ async function run({ json, auditOnly, refresh, ensured, form, audit, file, argv }) {
62
+ const wantLoad = argv.includes("--load");
63
+ const loadResult = wantLoad ? await loadModules(form) : null;
64
+
65
+ if (json) {
66
+ console.log(
67
+ JSON.stringify(
68
+ {
69
+ schema: 1,
70
+ generatedAt: new Date().toISOString(),
71
+ hostProfile: { file, ...ensured.profile },
72
+ cache: { source: ensured.source, firstLaunch: ensured.firstLaunch, expired: ensured.expired, writeOk: ensured.write?.ok !== false },
73
+ audit,
74
+ loaded: loadResult ? { loaded: loadResult.loaded, failed: loadResult.failed } : null
75
+ },
76
+ null,
77
+ 2
78
+ )
79
+ );
80
+ return loadResult && loadResult.failed.length > 0 ? 1 : 0;
81
+ }
82
+
83
+ const p = ensured.profile;
84
+ if (auditOnly) {
85
+ console.log(`宿主形态:${form}(来源 ${p.source}) 画像:${file}`);
86
+ if (audit.stripped.length === 0) {
87
+ console.log("本环境没有需要剥离的环境专属模块(所有登记模块都适用)。");
88
+ return 0;
89
+ }
90
+ console.log("");
91
+ console.log("本环境永远不会执行的文件:");
92
+ for (const item of audit.stripped) {
93
+ console.log(` - ${item.id} ${item.file} ${item.lines ?? "?"} 行`);
94
+ console.log(` 能力键 ${item.capability} = ${JSON.stringify(item.value)}(需要 ${JSON.stringify(item.expect)})`);
95
+ console.log(` 理由:${item.reason}`);
96
+ }
97
+ console.log("");
98
+ console.log(`合计剥离 ${audit.totalStrippedLines} 行(占登记模块 ${audit.totalStrippedLines + audit.totalLoadableLines} 行)。`);
99
+ console.log("提示:新增环境专属模块时,在 lib/host-registry.mjs 的 ENV_MODULES 里登记一条,它就会自动进这份清单。");
100
+ return 0;
101
+ }
102
+
103
+ console.log(`drydock 环境剥离审计${refresh ? "(已强制重新探测)" : ""}`);
104
+ console.log(` 宿主形态 : ${form}(来源:${p.source},置信度 ${p.confidence ?? "?"})`);
105
+ console.log(` 判定理由 : ${p.reason}`);
106
+ console.log(` 画像文件 : ${file}`);
107
+ console.log(` 首次探测 : ${p.firstLaunchAt} 最近探测:${p.profiledAt}`);
108
+ if (p.previousForm && p.previousForm !== form) console.log(` ⚠ 形态变化 : ${p.previousForm} → ${form}(已按新形态重算装载表)`);
109
+ if (ensured.write && ensured.write.ok === false) console.log(` ⚠ 画像写入失败:${ensured.write.error}(本次仍按探测结果执行)`);
110
+
111
+ console.log("");
112
+ console.log("装载(本环境需要,会 import):");
113
+ if (audit.loadable.length === 0) console.log(" (无)");
114
+ for (const item of audit.loadable) {
115
+ console.log(` ✓ ${item.id.padEnd(18)} ${item.file} ${item.lines ?? "?"} 行${item.capability ? ` [${item.capability}=${JSON.stringify(item.value)}]` : ""}`);
116
+ }
117
+
118
+ console.log("");
119
+ console.log("剥离(本环境不需要,连 import 都不会发生):");
120
+ if (audit.stripped.length === 0) console.log(" (无)");
121
+ for (const item of audit.stripped) {
122
+ console.log(` ✂ ${item.id.padEnd(18)} ${item.file} ${item.lines ?? "?"} 行 [${item.capability}=${JSON.stringify(item.value)}]`);
123
+ console.log(` 理由:${item.reason}`);
124
+ }
125
+ console.log("");
126
+ console.log(`合计:装载 ${audit.totalLoadableLines} 行 / 剥离 ${audit.totalStrippedLines} 行(占登记模块 ${audit.totalLoadableLines + audit.totalStrippedLines} 行)。`);
127
+
128
+ if (loadResult) {
129
+ console.log("");
130
+ console.log(`实际装载:${loadResult.loaded.length} 个(${loadResult.loaded.join(", ") || "无"})`);
131
+ for (const fail of loadResult.failed) console.log(` ✘ ${fail.id} 装载失败:${fail.error}`);
132
+ }
133
+
134
+ console.log("");
135
+ console.log("说明:剥离是**文件级**的(一个模块整体装载或整体剥离),所以环境专属逻辑必须独立成文件;");
136
+ console.log(" 边界由 test-isolation.mjs(host 侧 import 白名单)与 test-host-strip.mjs(本表)共同守。");
137
+ return loadResult && loadResult.failed.length > 0 ? 1 : 0;
138
+ }
139
+
140
+ main().then((code) => process.exit(code));