@modusensus/dsh-mneme 0.7.31 → 0.8.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.
Files changed (93) hide show
  1. package/README.md +65 -27
  2. package/lib/api.js +139 -6
  3. package/lib/client.js +369 -32
  4. package/lib/commands.js +36 -5
  5. package/lib/config.js +101 -14
  6. package/lib/dream/decisions.js +147 -14
  7. package/lib/dream/sleep.js +84 -34
  8. package/lib/dream.js +250 -60
  9. package/lib/embedding.js +22 -2
  10. package/lib/index.js +68 -37
  11. package/lib/inject.js +54 -13
  12. package/lib/lang.js +168 -0
  13. package/lib/local-embedder.js +23 -9
  14. package/lib/mirror.js +17 -14
  15. package/lib/reranker.js +23 -8
  16. package/lib/runtime/adopt.js +176 -0
  17. package/lib/runtime/closure.js +172 -0
  18. package/lib/runtime/download.js +247 -0
  19. package/lib/runtime/layout.js +235 -0
  20. package/lib/runtime/loader.js +249 -0
  21. package/lib/runtime/provision.js +237 -0
  22. package/lib/runtime/tarball.js +130 -0
  23. package/lib/runtime/verify.js +191 -0
  24. package/lib/scope.js +83 -0
  25. package/lib/service.js +374 -55
  26. package/lib/settings.js +43 -2
  27. package/lib/store.js +126 -13
  28. package/lib/summarize.js +108 -35
  29. package/lib/tools.js +205 -12
  30. package/package.json +7 -2
  31. package/runtime-manifest.json +596 -0
  32. package/scripts/build-runtime-manifest.mjs +217 -0
  33. package/scripts/mneme-runtime.mjs +277 -0
  34. package/src/api.js +139 -6
  35. package/src/commands.js +36 -5
  36. package/src/config.js +101 -14
  37. package/src/dream/decisions.js +147 -14
  38. package/src/dream/sleep.js +84 -34
  39. package/src/dream.js +250 -60
  40. package/src/embedding.js +22 -2
  41. package/src/index.js +68 -37
  42. package/src/inject.js +54 -13
  43. package/src/lang.js +168 -0
  44. package/src/local-embedder.js +23 -9
  45. package/src/mirror.js +17 -14
  46. package/src/reranker.js +23 -8
  47. package/src/runtime/adopt.js +176 -0
  48. package/src/runtime/closure.js +172 -0
  49. package/src/runtime/download.js +247 -0
  50. package/src/runtime/layout.js +235 -0
  51. package/src/runtime/loader.js +249 -0
  52. package/src/runtime/provision.js +237 -0
  53. package/src/runtime/tarball.js +130 -0
  54. package/src/runtime/verify.js +191 -0
  55. package/src/scope.js +83 -0
  56. package/src/service.js +374 -55
  57. package/src/settings.js +43 -2
  58. package/src/store.js +126 -13
  59. package/src/summarize.js +108 -35
  60. package/src/tools.js +205 -12
  61. package/test/api.test.js +175 -9
  62. package/test/client.test.js +152 -10
  63. package/test/commands.test.js +40 -3
  64. package/test/config.test.js +17 -1
  65. package/test/dream-candidate-hybrid.test.js +281 -0
  66. package/test/dream.test.js +172 -0
  67. package/test/embedding-ready.test.js +196 -0
  68. package/test/helpers/runtime-source.js +60 -0
  69. package/test/helpers/tar-builder.js +80 -0
  70. package/test/inject.test.js +130 -1
  71. package/test/lang.test.js +87 -0
  72. package/test/quality-filter.test.js +68 -0
  73. package/test/reasoning-effort.test.js +106 -15
  74. package/test/reindex-backfill.test.js +62 -0
  75. package/test/runtime-adopt.test.js +206 -0
  76. package/test/runtime-cli.test.js +89 -0
  77. package/test/runtime-closure.test.js +193 -0
  78. package/test/runtime-download.test.js +302 -0
  79. package/test/runtime-layout.test.js +163 -0
  80. package/test/runtime-loader.test.js +237 -0
  81. package/test/runtime-manifest.test.js +158 -0
  82. package/test/runtime-provision.test.js +101 -0
  83. package/test/runtime-tarball.test.js +82 -0
  84. package/test/runtime-verify.test.js +214 -0
  85. package/test/scope-retrieval.test.js +197 -0
  86. package/test/scope-storage.test.js +247 -0
  87. package/test/scope-strict.test.js +165 -0
  88. package/test/service.test.js +76 -0
  89. package/test/sleep-action-set.test.js +422 -0
  90. package/test/store.test.js +14 -0
  91. package/test/summarize.test.js +224 -0
  92. package/test/tools.test.js +30 -5
  93. package/test/webServer-optional.test.js +34 -1
@@ -0,0 +1,217 @@
1
+ // 生成 runtime-manifest.json(issue #131 / PR-C)
2
+ //
3
+ // **平台无关**是这份清单的核心设计:数据源是 `package-lock.json` 而不是「本机装好的那棵树」。
4
+ // npm 的 lockfile 里包含**所有平台**的包条目(各自的 os / cpu 与 integrity),所以一份清单就能
5
+ // 覆盖 win32 / darwin / linux × x64 / arm64 —— 下载时再按平台过滤(`matchesPlatform`)。
6
+ //
7
+ // 为什么不做成「按平台各存一份、谁在哪个系统上生成」:那样 macOS 用户在一台没人跑过脚本的机器上
8
+ // 会看到「清单里没有 darwin-arm64 的条目」而直接卡住。清单是随包发布的静态数据,它必须一次覆盖
9
+ // 所有平台,而不是依赖某个贡献者手上有对应的机器。
10
+ //
11
+ // 哈希取自 lockfile 的 integrity(npm 自己算的),所以维护成本是「改依赖后重跑一次脚本」。
12
+ //
13
+ // 用法:
14
+ // node scripts/build-runtime-manifest.mjs # 生成/更新
15
+ // node scripts/build-runtime-manifest.mjs --check # 只校验现有文件与 lockfile 一致(CI 用)
16
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import { matchesPlatform } from "../src/runtime/closure.js";
20
+
21
+ const ROOT = fileURLToPath(new URL("..", import.meta.url));
22
+ const MANIFEST = join(ROOT, "runtime-manifest.json");
23
+ const MANIFEST_VERSION = 2;
24
+ const ENTRY = "@huggingface/transformers";
25
+
26
+ /**
27
+ * 证据:`@huggingface/transformers` 的 Node 构建(dist/transformers.node.mjs)顶层只 import
28
+ * onnxruntime-node 与 sharp,从不 import onnxruntime-web(把一个空的 onnxruntime-web 打桩进去,
29
+ * 嵌入结果逐字节相同:dims=[2,512]、L2 范数 1.0000、cos 0.3053)。而它解包后 127.7MB,占整个
30
+ * 闭包约三分之一。所以清单里剔除它,风险由 verify 的真实推理兜底。
31
+ */
32
+ const EXCLUDED = { "onnxruntime-web": "Node 构建从不 import 它(打桩验证:嵌入结果逐字节相同)" };
33
+
34
+ /**
35
+ * 被剔除的包,以及**它子树下的一切**。
36
+ *
37
+ * 只按包名过滤会漏掉嵌套条目:闭包是按源布局镜像的,所以存在
38
+ * `onnxruntime-web/node_modules/onnxruntime-common` 这种位于被剔除包内部的包 ——
39
+ * 那个位置根本不会被取回来,留在清单里就是让下载器去填一个不存在的坑。
40
+ * 同名但位于别处(例如顶层 onnxruntime-common)不受影响。
41
+ */
42
+ export function isExcluded(pkg) {
43
+ return Object.keys(EXCLUDED).some(
44
+ (name) => pkg.name === name || pkg.rel === name || pkg.rel.startsWith(`${name}/`)
45
+ );
46
+ }
47
+
48
+ /** lockfile 的路径 → 包名(最后一段 `node_modules/` 之后的部分)。 */
49
+ export function nameOfPath(path) {
50
+ const marker = path.lastIndexOf("node_modules/");
51
+ return marker === -1 ? path : path.slice(marker + "node_modules/".length);
52
+ }
53
+
54
+ /** lockfile 的路径 → payload 里的相对路径(去掉开头的 `node_modules/`)。 */
55
+ export function relOfPath(path) {
56
+ return path.startsWith("node_modules/") ? path.slice("node_modules/".length) : path;
57
+ }
58
+
59
+ /**
60
+ * 按 Node 的解析语义列出候选路径:从引用者自身的 `node_modules` 逐级向上,最后兜底到根部。
61
+ *
62
+ * 例:引用者在 `node_modules/a/node_modules/b`、依赖 `x` →
63
+ * `…/b/node_modules/x` → `node_modules/a/node_modules/x` → `node_modules/x`
64
+ * @param {string} fromPath - 引用者的 lockfile 路径。
65
+ * @param {string} name - 依赖名。
66
+ * @returns {string[]} 候选路径,由近到远。
67
+ */
68
+ export function resolveCandidates(fromPath, name) {
69
+ const out = [`${fromPath}/node_modules/${name}`];
70
+ let cursor = fromPath;
71
+ while (cursor.includes("/node_modules/")) {
72
+ cursor = cursor.slice(0, cursor.lastIndexOf("/node_modules/"));
73
+ out.push(cursor === "" ? `node_modules/${name}` : `${cursor}/node_modules/${name}`);
74
+ }
75
+ if (!out.includes(`node_modules/${name}`)) out.push(`node_modules/${name}`);
76
+ return out;
77
+ }
78
+
79
+ /** registry 的 tarball 地址:lockfile 记了 resolved 就用它(与 integrity 同源),否则按 npm 约定推。 */
80
+ function tarballUrl(name, version, resolved) {
81
+ if (typeof resolved === "string" && resolved.startsWith("http")) return resolved;
82
+ const base = name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
83
+ return `https://registry.npmjs.org/${name}/-/${base}-${version}.tgz`;
84
+ }
85
+
86
+ /**
87
+ * 从 lockfile 走一遍闭包。
88
+ * @param {object} lock - package-lock.json 的内容。
89
+ * @returns {{packages: object[], missing: string[]}} 包列表(按 rel 排序)与解析不到的依赖。
90
+ */
91
+ export function closureFromLockfile(lock) {
92
+ const all = lock.packages ?? {};
93
+ const known = new Set(
94
+ Object.entries(all)
95
+ .filter(([path, meta]) => path.includes("node_modules/") && meta?.version !== undefined)
96
+ .map(([path]) => path)
97
+ );
98
+ const seen = new Map();
99
+ const missing = [];
100
+ const queue = [`node_modules/${ENTRY}`];
101
+
102
+ while (queue.length > 0) {
103
+ const path = queue.shift();
104
+ if (seen.has(path)) continue;
105
+ const meta = all[path];
106
+ if (meta?.version === undefined) {
107
+ missing.push(path);
108
+ continue;
109
+ }
110
+ if (isExcluded({ name: nameOfPath(path), rel: relOfPath(path) })) continue;
111
+ seen.set(path, meta);
112
+
113
+ const deps = { ...(meta.dependencies ?? {}), ...(meta.optionalDependencies ?? {}) };
114
+ for (const name of Object.keys(deps)) {
115
+ const resolved = resolveCandidates(path, name).find((option) => known.has(option));
116
+ if (resolved === undefined) missing.push(`${name}(被 ${relOfPath(path)} 需要)`);
117
+ else queue.push(resolved);
118
+ }
119
+ }
120
+
121
+ const packages = [...seen.entries()]
122
+ .map(([path, meta]) => ({
123
+ name: nameOfPath(path),
124
+ version: meta.version,
125
+ rel: relOfPath(path),
126
+ integrity: meta.integrity ?? null,
127
+ tarball: tarballUrl(nameOfPath(path), meta.version, meta.resolved),
128
+ // 平台约束照抄 lockfile:下载器按它过滤。没有这三个字段 = 与平台无关。
129
+ ...(Array.isArray(meta.os) ? { os: meta.os } : {}),
130
+ ...(Array.isArray(meta.cpu) ? { cpu: meta.cpu } : {}),
131
+ // libc 也带上:linux-x64 的 glibc 机器靠它剔掉两套 musl 变体(十几 MB)。
132
+ // 下载器只在**确认**了本机 libc 时才据此过滤,拿不到证据就不看这个字段。
133
+ ...(Array.isArray(meta.libc) ? { libc: meta.libc } : {})
134
+ }))
135
+ .sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
136
+
137
+ return { packages, missing };
138
+ }
139
+
140
+ /** 某个平台实际需要取哪些包(与下载器用同一条判据)。 */
141
+ export function packagesForPlatform(manifest, platform, arch, libc = null) {
142
+ return manifest.packages.filter((pkg) => matchesPlatform(pkg, platform, arch, libc));
143
+ }
144
+
145
+ /** 生成一份**平台无关**的清单。 */
146
+ export function build() {
147
+ const lock = JSON.parse(readFileSync(join(ROOT, "package-lock.json"), "utf8"));
148
+ const { packages, missing } = closureFromLockfile(lock);
149
+ // 解析不到的依赖必须让生成**失败**:带缺口的清单会让用户在下载时才失败,而且「少了一个包」
150
+ // 这种缺口结构检查看不出来(它只点三个必需包)。生成期的数据问题就该在生成期炸掉 ——
151
+ // 这也是我第一版真正踩过的:被剔除包的孤儿依赖留在了清单里,而生成器一声不吭。
152
+ if (missing.length > 0) {
153
+ throw new Error(`这些依赖在 package-lock.json 里解析不到:${missing.slice(0, 10).join("、")}`);
154
+ }
155
+
156
+ const entry = packages.find((pkg) => pkg.rel === ENTRY);
157
+ if (entry === undefined) throw new Error(`闭包入口没解析出来:${missing.join("; ") || "lockfile 里没有它"}`);
158
+ // 查不到 sha512 就不能写进清单:那等于让下载器「先信任再校验」,是假校验。
159
+ const withoutIntegrity = packages.filter(
160
+ (pkg) => typeof pkg.integrity !== "string" || !pkg.integrity.startsWith("sha512-")
161
+ );
162
+ if (withoutIntegrity.length > 0) {
163
+ throw new Error(`这些包在 package-lock.json 里没有 sha512 integrity:${withoutIntegrity.map((p) => p.rel).join("、")}`);
164
+ }
165
+
166
+ return {
167
+ manifestVersion: MANIFEST_VERSION,
168
+ entry: ENTRY,
169
+ transformersVersion: entry.version,
170
+ excluded: EXCLUDED,
171
+ // 平台无关:下载时按 os/cpu/libc 过滤(payloadId 也由下载器按本机平台算)。
172
+ packages
173
+ };
174
+ }
175
+
176
+ /** 应当被覆盖的平台(自检与 CI 断言用)。 */
177
+ export const COVERED_PLATFORMS = [
178
+ ["win32", "x64"],
179
+ ["win32", "arm64"],
180
+ ["darwin", "x64"],
181
+ ["darwin", "arm64"],
182
+ ["linux", "x64"],
183
+ ["linux", "arm64"]
184
+ ];
185
+
186
+ /** 命令行入口。`--check` 只校验,不写文件。 */
187
+ export function main(args = process.argv.slice(2)) {
188
+ const check = args.includes("--check");
189
+ const built = build();
190
+ const coverage = COVERED_PLATFORMS.map(([platform, arch]) => {
191
+ const set = packagesForPlatform(built, platform, arch);
192
+ const hasEntry = set.some((pkg) => pkg.rel === ENTRY);
193
+ const hasNative = set.some((pkg) => pkg.rel === "onnxruntime-node");
194
+ // linux 再报一次「确认 glibc 时」的包数:下载器会剔掉另一套 libc 的变体,这行让
195
+ // 「剔掉了多少」在 --check 里看得见,而不是只能翻清单。
196
+ const glibc = platform === "linux" ? `;确认 glibc 时 ${packagesForPlatform(built, platform, arch, "glibc").length} 个` : "";
197
+ return `${platform}-${arch}: ${set.length} 个包${glibc}${hasEntry && hasNative ? "" : "(缺入口或原生依赖!)"}`;
198
+ });
199
+
200
+ if (check) {
201
+ const existing = existsSync(MANIFEST) ? readFileSync(MANIFEST, "utf8") : "";
202
+ const same = existing === `${JSON.stringify(built, null, 2)}\n`;
203
+ process.stdout.write(`${same ? "✓" : "✗"} 清单与 package-lock.json ${same ? "一致" : "不一致,请重跑生成"}\n`);
204
+ for (const line of coverage) process.stdout.write(` ${line}\n`);
205
+ return same ? 0 : 1;
206
+ }
207
+
208
+ writeFileSync(MANIFEST, `${JSON.stringify(built, null, 2)}\n`, "utf8");
209
+ process.stdout.write(`写入 ${MANIFEST}\n共 ${built.packages.length} 个包(已剔除 ${Object.keys(EXCLUDED).join("、")} 及其子树)\n`);
210
+ for (const line of coverage) process.stdout.write(` ${line}\n`);
211
+ return 0;
212
+ }
213
+
214
+ // 只有被直接执行时才干活:被 import 时(测试里)不该顺手改写清单文件。
215
+ const invokedDirectly =
216
+ process.argv[1] != null && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop() ?? "");
217
+ if (invokedDirectly) process.exitCode = main();
@@ -0,0 +1,277 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 本地推理运行时管理入口(issue #131 / PR-A)
4
+ *
5
+ * 为什么不在 bin/cli.mjs 里加子命令:那个 CLI 的契约是「外部 HTTP API 客户端」,
6
+ * 要求 dsh-mneme 服务正在运行。而收编/验证运行时恰恰发生在服务没起来、插件甚至
7
+ * 装不上的时候 —— 两者是相反的使用场景。scripts/ 是与 benchmark-embed.js 同类的
8
+ * 本地工具目录,放这里符合既有约定,也不用动物那个零依赖 CLI 的契约。
9
+ *
10
+ * 用法(在插件目录下运行):
11
+ * node scripts/mneme-runtime.mjs status [--runtime <dir>] [--json]
12
+ * node scripts/mneme-runtime.mjs adopt --from <宿主 node_modules 目录> [--runtime <dir>] [--overwrite] [--json]
13
+ * node scripts/mneme-runtime.mjs verify [--runtime <dir>] [--cache-dir <dir>] [--json]
14
+ *
15
+ * 退出码:0 = 健康 / 1 = 不健康或失败 / 2 = 用法错误。
16
+ * 每一档都要能被脚本直接拿去 gate,所以「没装」和「装坏了」返回的都是 1,
17
+ * 具体区别看输出里的 status。
18
+ */
19
+ import process from "node:process";
20
+ import { adoptRuntime } from "../lib/runtime/adopt.js";
21
+ import { describeLocalRuntime, resolveRuntimeEntry } from "../lib/runtime/loader.js";
22
+ import { defaultModelCacheDir, defaultRuntimeDir, describePayload } from "../lib/runtime/layout.js";
23
+ import { verifyPayload } from "../lib/runtime/verify.js";
24
+
25
+ // 注意:下面是模板字面量,帮助正文里**不能出现反引号** —— 会把字面量提前截断。
26
+ // 这个坑踩过一次,而且因为本文件原本不在任何测试覆盖里,CI 完全没抓到;
27
+ // 现在由 test/runtime-cli.test.js 动态 import 本文件来兜底(语法错会在测试里直接炸)。
28
+ const USAGE = `本地推理运行时管理(dsh-mneme / issue #131)
29
+
30
+ 用法:
31
+ node scripts/mneme-runtime.mjs status [--runtime <dir>] [--json]
32
+ node scripts/mneme-runtime.mjs adopt --from <宿主 node_modules 目录> [--runtime <dir>] [--overwrite] [--json]
33
+ node scripts/mneme-runtime.mjs verify [--runtime <dir>] [--cache-dir <dir>] [--json]
34
+
35
+ 说明:
36
+ status 只读探查:这份运行时在哪、来源是什么、结构完不完整。不加载模型。
37
+ adopt 把宿主 node_modules 里已有的那份依赖闭包收编进插件自管目录,
38
+ 优先用硬链接(同盘时几乎不额外占盘)。收编后宿主那份可以随时被 pnpm 删掉。
39
+ 本机哪里都没有这份依赖时,可在任意空目录先装一份:
40
+ npm i @huggingface/transformers@^4.2.0
41
+ 再把那个 node_modules 作为 --from 传进来。必须让安装脚本正常执行(npm 默认会,
42
+ pnpm 10+ 默认拦截构建脚本),否则取不到 onnxruntime-node / sharp 的原生二进制。
43
+ verify 真加载运行时并跑一次推理,外加结构与完整性检查。
44
+ ⚠ 功能验证是离线的(allowRemoteModels=false):模型必须已在缓存目录里,
45
+ 否则会明确失败 —— 这是有意的,验证不该偷偷触网。
46
+ 默认缓存目录若与你的 embedModelCacheDir 不一致,用 --cache-dir 指过去。
47
+
48
+ 默认运行时目录:${defaultRuntimeDir()}
49
+ 默认模型缓存目录:${defaultModelCacheDir()}
50
+ `;
51
+
52
+ class UsageError extends Error {}
53
+
54
+ /** 必须带值的选项;缺值时是用法错误,不能把 "true" 当成路径用下去。 */
55
+ const VALUE_OPTIONS = new Set(["runtime", "from", "cache-dir"]);
56
+ /** 纯开关。 */
57
+ const FLAG_OPTIONS = new Set(["json", "overwrite"]);
58
+
59
+ /**
60
+ * 参数解析:只支持 `--key value` 与 `--flag`。
61
+ * 够用就不引库 —— 这个脚本要在「插件装不上」的场景下还能跑,依赖越少越好。
62
+ *
63
+ * 两个刻意的严格行为:
64
+ * - 缺值的 `--runtime` / `--from` / `--cache-dir` 直接报用法错误(exit 2)。宽松处理会让
65
+ * 它们变成 `true`,再被当作一个叫 "true" 的路径用下去,最后以 exit 1 收场 ——
66
+ * 真正的「你少打了一个值」被伪装成「运行时坏了」。
67
+ * - 未知选项也报用法错误,而不是静默忽略:打错字应当立刻可见。
68
+ */
69
+ function parseArgs(argv) {
70
+ const options = {};
71
+ for (let i = 0; i < argv.length; i++) {
72
+ const token = argv[i];
73
+ const key = token.startsWith("--") ? token.slice(2) : null;
74
+ if (key === null || (!VALUE_OPTIONS.has(key) && !FLAG_OPTIONS.has(key))) {
75
+ const accepted = [
76
+ ...[...VALUE_OPTIONS].map((k) => `--${k} <值>`),
77
+ ...[...FLAG_OPTIONS].map((k) => `--${k}`)
78
+ ].join("、");
79
+ throw new UsageError(`无法识别的参数:${token}(可用:${accepted})`);
80
+ }
81
+ if (FLAG_OPTIONS.has(key)) {
82
+ options[key] = true;
83
+ continue;
84
+ }
85
+ const value = argv[i + 1];
86
+ if (value === undefined || value.startsWith("--")) {
87
+ throw new UsageError(`--${key} 需要带一个值`);
88
+ }
89
+ options[key] = value;
90
+ i++;
91
+ }
92
+ return options;
93
+ }
94
+
95
+ const printJson = (value) => process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
96
+
97
+ /** payloadId → 人类可读的标签,纯展示。 */
98
+ function describePayloadLabel(report) {
99
+ const parts = [];
100
+ if (report.version) parts.push(`transformers ${report.version}`);
101
+ if (report.procedure) parts.push(`来源 ${report.procedure}`);
102
+ if (report.materialize) parts.push(`物化 ${report.materialize}`);
103
+ return parts.join(",");
104
+ }
105
+
106
+ function runStatus({ runtimeDir, asJson }) {
107
+ const report = describeLocalRuntime({ runtimeDir });
108
+ const healthy = report.status === "available";
109
+ if (asJson) {
110
+ printJson(report);
111
+ return healthy ? 0 : 1;
112
+ }
113
+
114
+ const label = { available: "可用", missing: "未安装", broken: "损坏", unreadable: "读不到" }[report.status] ?? report.status;
115
+ console.log(`运行时目录:${report.runtimeDir}`);
116
+ console.log(`状态:${label}`);
117
+ if (report.payloadId) console.log(`payload:${report.payloadId}`);
118
+ const extra = describePayloadLabel(report);
119
+ if (extra) console.log(` ${extra}`);
120
+ if (healthy) {
121
+ console.log(`完整性:${report.integrity}`);
122
+ // 明说「结构通过 ≠ 验过」,否则这个面板会给出虚假的安心感。
123
+ console.log(`功能:${report.functional}(状态探查不加载模型,跑 verify 才能确认真的能推理)`);
124
+ }
125
+ for (const item of report.missing ?? []) console.log(`缺失:${item}`);
126
+ for (const reason of report.reasons ?? []) console.log(`原因:${reason}`);
127
+ if (report.reason) console.log(`原因:${report.reason}`);
128
+ if (!healthy) console.log(`\n${report.hint}`);
129
+ return healthy ? 0 : 1;
130
+ }
131
+
132
+ async function runAdopt({ runtimeDir, asJson, options }) {
133
+ const from = String(options.from ?? "").trim();
134
+ if (!from) {
135
+ throw new UsageError(
136
+ "adopt 需要 --from <宿主 node_modules 目录>,例如:\n" +
137
+ " .../profiles/<profile>/node_modules\n" +
138
+ "(就是当前装着 @huggingface/transformers 的那个 node_modules)"
139
+ );
140
+ }
141
+
142
+ const result = await adoptRuntime({
143
+ fromModulesDir: from,
144
+ runtimeDir,
145
+ overwrite: options.overwrite === true
146
+ });
147
+
148
+ // 收编失败时 adoptRuntime **不带 payloadDir**(入口包解析不到就是这条路径)。
149
+ // 必须先处理,否则下面拿 undefined 当路径喂给 describePayload,用户看到的是
150
+ // `TypeError: The "path" argument must be of type string` 的堆栈,
151
+ // 而不是「入口包不存在 + 下一步该做什么」——而这是文档里给用户的第一条命令。
152
+ if (result.ok === false) {
153
+ if (asJson) printJson(result);
154
+ else console.log(`收编失败:${result.reason}`);
155
+ return 1;
156
+ }
157
+
158
+ // 搬运完立刻做结构检查:缺件现在就能发现,不必等到第一次推理才炸。
159
+ const structural = describePayload(result.payloadDir);
160
+
161
+ // 两条判据都要过:describePayload 只点三个必需包,**不看闭包计划里的必需依赖缺口**。
162
+ // 只认 structural.ok 的话,「缺传递依赖、入口一 import 就炸」的收编会报 exit 0,
163
+ // 脚本化的 gate 就在最需要它的时候误报健康。
164
+ const gaps = result.plan.gaps;
165
+ const healthy = structural.ok && gaps.length === 0;
166
+
167
+ if (asJson) {
168
+ printJson({ ...result, structural, healthy });
169
+ return healthy ? 0 : 1;
170
+ }
171
+
172
+ console.log(`已收编到:${result.payloadDir}`);
173
+ console.log(`payload:${result.payloadId}`);
174
+ console.log(`包数:${result.plan.packages.length} 文件:${result.totals.files} 字节:${result.totals.bytes}`);
175
+ console.log(`物化方式:${result.manifest.materialize.mode}` + (result.manifest.materialize.linkError ? `(硬链接失败原因:${result.manifest.materialize.linkError})` : ""));
176
+ if (result.plan.skipped.length) {
177
+ console.log(`跳过(平台不适用):${result.plan.skipped.map((s) => s.name).join("、")}`);
178
+ }
179
+ for (const warning of result.manifest.warnings) console.log(`警告:${warning}`);
180
+ for (const gap of gaps) {
181
+ console.log(`缺失依赖:${gap.name}(被 ${gap.from} 需要:${gap.reason})`);
182
+ }
183
+ for (const item of structural.missing) console.log(`缺失文件:${item}`);
184
+ for (const reason of structural.reasons) console.log(`结构问题:${reason}`);
185
+ console.log(`结构检查:${structural.ok ? "通过" : "未通过"}`);
186
+ if (gaps.length > 0) {
187
+ console.log(`闭包完整性:未通过(${gaps.length} 个必需依赖缺失,入口加载时会失败)`);
188
+ }
189
+ if (healthy) {
190
+ console.log(`\n下一步:node scripts/mneme-runtime.mjs verify # 真跑一次推理确认可用`);
191
+ }
192
+ return healthy ? 0 : 1;
193
+ }
194
+
195
+ async function runVerify({ runtimeDir, asJson, options }) {
196
+ const candidate = resolveRuntimeEntry({ runtimeDir });
197
+ if (candidate === null) {
198
+ // 「没得验」不是用法错误,是不健康 —— 复用 status 的提示,别自己编一套说法。
199
+ const report = describeLocalRuntime({ runtimeDir });
200
+ if (asJson) printJson(report);
201
+ else console.log(`没有可用的运行时 payload。\n\n${report.hint}`);
202
+ return 1;
203
+ }
204
+
205
+ const cacheDir = String(options["cache-dir"] ?? "").trim() || defaultModelCacheDir();
206
+ if (!asJson) {
207
+ console.log(`验证 payload:${candidate.payloadId}`);
208
+ console.log(`模型缓存目录:${cacheDir}`);
209
+ console.log("正在加载运行时并推理(首次可能要几十秒)...");
210
+ }
211
+
212
+ const result = await verifyPayload(candidate.dir, { cacheDir });
213
+
214
+ if (asJson) {
215
+ printJson(result);
216
+ return result.ok ? 0 : 1;
217
+ }
218
+
219
+ console.log(`结构检查:${result.structural.ok ? "通过" : "未通过"}`);
220
+ for (const item of result.structural.missing) console.log(` 缺失:${item}`);
221
+ for (const reason of result.structural.reasons) console.log(` 原因:${reason}`);
222
+ const fn = result.functional;
223
+ console.log(`功能验证:${fn.ok ? `通过(维度 ${fn.dim},${fn.rows} 行,${fn.elapsedMs}ms)` : "未通过"}`);
224
+ if (!fn.ok) {
225
+ console.log(` 原因:${fn.reason}`);
226
+ // 最常见的失败是模型不在这个目录 —— 注意这里的默认值不一定等于用户配置的
227
+ // embedModelCacheDir,所以要明确告诉他能改。
228
+ console.log(` 提示:功能验证不触网(allowRemoteModels=false),模型必须已在缓存目录里。`);
229
+ console.log(` 若模型在别处,用 --cache-dir <目录> 指过去(应与配置项 embedModelCacheDir 一致);`);
230
+ console.log(` 或先用 embedProvider="local" 触发一次下载(走 embedModelMirror 镜像)。`);
231
+ }
232
+ console.log(`完整性:${result.integrity.status}${result.integrity.detail ? `(${result.integrity.detail})` : ""}`);
233
+ console.log(`\n总判定:${result.ok ? "通过" : "未通过"}`);
234
+ return result.ok ? 0 : 1;
235
+ }
236
+
237
+ async function main() {
238
+ const [command, ...rest] = process.argv.slice(2);
239
+ if (!command || command === "help" || command === "--help" || command === "-h") {
240
+ process.stdout.write(USAGE);
241
+ return command ? 0 : 2;
242
+ }
243
+ const options = parseArgs(rest);
244
+ const runtimeDir = String(options.runtime ?? "").trim() || defaultRuntimeDir();
245
+ const asJson = options.json === true;
246
+
247
+ if (command === "status") return runStatus({ runtimeDir, asJson });
248
+ if (command === "adopt") return runAdopt({ runtimeDir, asJson, options });
249
+ if (command === "verify") return runVerify({ runtimeDir, asJson, options });
250
+ throw new UsageError(`未知命令:${command}\n\n${USAGE}`);
251
+ }
252
+
253
+ /**
254
+ * 只有被直接执行时才跑 CLI。这样测试可以安全地 `import` 本文件来验证它能被解析并求值
255
+ * —— 脚本不在任何其它测试覆盖里,一个模板字面量里的反引号就足以让它整体坏掉而 CI 全绿。
256
+ * 与 scripts/benchmark-recall.js 的 invokedDirectly 同一套写法。
257
+ */
258
+ const invokedDirectly =
259
+ process.argv[1] != null && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop() ?? "");
260
+
261
+ if (invokedDirectly) {
262
+ try {
263
+ process.exitCode = await main();
264
+ } catch (error) {
265
+ if (error instanceof UsageError) {
266
+ process.stderr.write(`${error.message}\n`);
267
+ process.exitCode = 2;
268
+ } else {
269
+ // 验证/收编本身是 fail-safe 的;能走到这里的多半是环境问题(磁盘、权限),
270
+ // 如实打出来,别吞。
271
+ process.stderr.write(`失败:${error?.stack ?? error}\n`);
272
+ process.exitCode = 1;
273
+ }
274
+ }
275
+ }
276
+
277
+ export { main, parseArgs, runAdopt, UsageError };