@modusensus/dsh-mneme 0.8.3 → 0.8.4

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 (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +718 -636
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +502 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +495 -316
  7. package/lib/api.js +1382 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4475 -4366
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +533 -510
  12. package/lib/dream/clustering.js +118 -118
  13. package/lib/dream/decisions.js +658 -658
  14. package/lib/dream/narratives.js +44 -0
  15. package/lib/dream/sleep.js +700 -700
  16. package/lib/dream.js +1319 -1216
  17. package/lib/embedding.js +177 -177
  18. package/lib/entities/extractor.js +249 -249
  19. package/lib/heat.js +142 -136
  20. package/lib/hot-memory.js +46 -46
  21. package/lib/index.js +515 -515
  22. package/lib/inject.js +299 -295
  23. package/lib/lang.js +202 -179
  24. package/lib/local-embedder.js +320 -320
  25. package/lib/mirror.js +198 -198
  26. package/lib/quality-filter.js +126 -126
  27. package/lib/recall-stats.js +103 -0
  28. package/lib/reranker.js +269 -269
  29. package/lib/runtime/adopt.js +176 -176
  30. package/lib/runtime/closure.js +172 -172
  31. package/lib/runtime/download.js +247 -247
  32. package/lib/runtime/layout.js +235 -235
  33. package/lib/runtime/loader.js +249 -249
  34. package/lib/runtime/model-fetch.js +361 -361
  35. package/lib/runtime/provision.js +237 -237
  36. package/lib/runtime/tarball.js +130 -130
  37. package/lib/runtime/verify.js +191 -191
  38. package/lib/scope.js +118 -118
  39. package/lib/search/adaptive.js +22 -22
  40. package/lib/search/bm25.js +96 -96
  41. package/lib/service.js +2171 -2087
  42. package/lib/settings.js +430 -420
  43. package/lib/store.js +2448 -2367
  44. package/lib/summarize.js +575 -449
  45. package/lib/tools.js +574 -574
  46. package/lib/vector-index.js +110 -110
  47. package/lib/version-check.js +122 -122
  48. package/package.json +109 -108
  49. package/runtime-manifest.json +596 -596
  50. package/scripts/benchmark-embed.js +201 -201
  51. package/scripts/benchmark-recall.js +199 -199
  52. package/scripts/benchmark-rerank.js +166 -166
  53. package/scripts/build-runtime-manifest.mjs +217 -217
  54. package/scripts/check-sync.js +42 -42
  55. package/scripts/e2e-dsh.js +220 -220
  56. package/scripts/mneme-runtime.mjs +277 -277
  57. package/scripts/stress-dsh.js +255 -255
  58. package/scripts/sync-lib.js +47 -47
  59. package/scripts/sync-test-badge.mjs +61 -61
  60. package/src/api-standalone.js +495 -316
  61. package/src/api.js +1382 -1316
  62. package/src/bootstrap.js +211 -0
  63. package/src/commands.js +95 -95
  64. package/src/config.js +533 -510
  65. package/src/dream/clustering.js +118 -118
  66. package/src/dream/decisions.js +658 -658
  67. package/src/dream/narratives.js +44 -0
  68. package/src/dream/sleep.js +700 -700
  69. package/src/dream.js +1319 -1216
  70. package/src/embedding.js +177 -177
  71. package/src/entities/extractor.js +249 -249
  72. package/src/heat.js +142 -136
  73. package/src/hot-memory.js +46 -46
  74. package/src/index.js +515 -515
  75. package/src/inject.js +299 -295
  76. package/src/lang.js +202 -179
  77. package/src/local-embedder.js +320 -320
  78. package/src/mirror.js +198 -198
  79. package/src/quality-filter.js +126 -126
  80. package/src/recall-stats.js +103 -0
  81. package/src/reranker.js +269 -269
  82. package/src/runtime/adopt.js +176 -176
  83. package/src/runtime/closure.js +172 -172
  84. package/src/runtime/download.js +247 -247
  85. package/src/runtime/layout.js +235 -235
  86. package/src/runtime/loader.js +249 -249
  87. package/src/runtime/model-fetch.js +361 -361
  88. package/src/runtime/provision.js +237 -237
  89. package/src/runtime/tarball.js +130 -130
  90. package/src/runtime/verify.js +191 -191
  91. package/src/scope.js +118 -118
  92. package/src/search/adaptive.js +22 -22
  93. package/src/search/bm25.js +96 -96
  94. package/src/service.js +2171 -2087
  95. package/src/settings.js +430 -420
  96. package/src/store.js +2448 -2367
  97. package/src/summarize.js +575 -449
  98. package/src/tools.js +574 -574
  99. package/src/vector-index.js +110 -110
  100. package/src/version-check.js +122 -122
  101. package/test/api-routes-gaps.test.js +218 -218
  102. package/test/api.test.js +1578 -1482
  103. package/test/audit.test.js +448 -448
  104. package/test/benchmark.test.js +94 -94
  105. package/test/bootstrap.test.js +220 -0
  106. package/test/client.test.js +799 -736
  107. package/test/clustering.test.js +100 -100
  108. package/test/commands.test.js +106 -106
  109. package/test/config.test.js +66 -66
  110. package/test/conflict-freeze.test.js +300 -300
  111. package/test/dream-archive-guardrail.test.js +116 -116
  112. package/test/dream-candidate-hybrid.test.js +281 -281
  113. package/test/dream-coverage-degrade.test.js +86 -86
  114. package/test/dream.test.js +1257 -1254
  115. package/test/embedding-ready.test.js +196 -196
  116. package/test/entities.test.js +547 -547
  117. package/test/entity-recall.test.js +179 -0
  118. package/test/epistemic.test.js +298 -298
  119. package/test/fnew-0112.test.js +311 -311
  120. package/test/fnew-03.test.js +422 -422
  121. package/test/graph-api.test.js +175 -175
  122. package/test/heat.test.js +175 -148
  123. package/test/helpers/dream-mock.js +82 -82
  124. package/test/helpers/peer-worker.mjs +25 -25
  125. package/test/helpers/runtime-source.js +60 -60
  126. package/test/helpers/tar-builder.js +80 -80
  127. package/test/hot-memory.test.js +145 -145
  128. package/test/inject-content-cap.test.js +89 -0
  129. package/test/inject-first-round-bm25.test.js +89 -89
  130. package/test/inject-heat.test.js +61 -0
  131. package/test/inject-rotation.test.js +161 -161
  132. package/test/inject.test.js +249 -249
  133. package/test/lang.test.js +87 -87
  134. package/test/lib-smoke.test.js +96 -96
  135. package/test/llm-audit.test.js +309 -309
  136. package/test/llm-message-source.test.js +177 -177
  137. package/test/local-embedder.test.js +249 -249
  138. package/test/mcp-stdio.test.js +385 -0
  139. package/test/mirror-dirty.test.js +424 -424
  140. package/test/mirror-edit-digest.test.js +187 -187
  141. package/test/mirror-generation.test.js +499 -499
  142. package/test/mirror.test.js +249 -249
  143. package/test/narrative-bars.test.js +162 -0
  144. package/test/peer-blockers.test.js +193 -193
  145. package/test/policy-epoch.test.js +259 -259
  146. package/test/quality-filter.test.js +186 -186
  147. package/test/reasoning-effort.test.js +746 -746
  148. package/test/recall-evals.test.js +235 -235
  149. package/test/recall-layer.test.js +326 -326
  150. package/test/recall-stats.test.js +117 -0
  151. package/test/receipt-chain.test.js +451 -451
  152. package/test/reflection.test.js +226 -226
  153. package/test/reindex-backfill.test.js +62 -62
  154. package/test/reranker-single-logit.test.js +73 -73
  155. package/test/reranker.test.js +197 -197
  156. package/test/resident-status.test.js +83 -0
  157. package/test/runtime-adopt.test.js +206 -206
  158. package/test/runtime-cli.test.js +89 -89
  159. package/test/runtime-closure.test.js +193 -193
  160. package/test/runtime-download.test.js +302 -302
  161. package/test/runtime-layout.test.js +163 -163
  162. package/test/runtime-loader.test.js +237 -237
  163. package/test/runtime-manifest.test.js +158 -158
  164. package/test/runtime-model-fetch.test.js +348 -348
  165. package/test/runtime-provision.test.js +101 -101
  166. package/test/runtime-tarball.test.js +81 -81
  167. package/test/runtime-verify.test.js +214 -214
  168. package/test/scope-candidates.test.js +239 -239
  169. package/test/scope-explicit.test.js +452 -452
  170. package/test/scope-retrieval.test.js +197 -197
  171. package/test/scope-storage.test.js +255 -255
  172. package/test/scope-strict.test.js +231 -231
  173. package/test/search-fusion.test.js +90 -90
  174. package/test/semantic.test.js +124 -124
  175. package/test/service-search.test.js +174 -174
  176. package/test/service.test.js +405 -405
  177. package/test/settings.test.js +261 -261
  178. package/test/skip-invalid-restore.test.js +262 -262
  179. package/test/sleep-action-set.test.js +422 -422
  180. package/test/sleep-heat.test.js +126 -125
  181. package/test/sleep-scheduler-rearm.test.js +89 -89
  182. package/test/sleep.test.js +373 -373
  183. package/test/standalone-api.test.js +544 -359
  184. package/test/store-vector-cache.test.js +98 -98
  185. package/test/store.test.js +383 -383
  186. package/test/stress.test.js +209 -209
  187. package/test/summarize.test.js +884 -575
  188. package/test/tools-memory-get-schema.test.js +65 -65
  189. package/test/tools.test.js +341 -341
  190. package/test/updated-at-semantics.test.js +113 -113
  191. package/test/vector-index.test.js +221 -221
  192. package/test/version-check.test.js +152 -152
  193. package/test/webServer-optional.test.js +82 -82
@@ -1,110 +1,110 @@
1
- // Thin vector-index layer over the store's embedding column. Keeps the
2
- // current model fingerprint + stats in a dedicated `vector_meta` table so the
3
- // index can detect drift (embeddings generated by a different model) and the
4
- // Web panel can report index health. The heavy lifting (cosine search) lives
5
- // in store.searchVector; this module owns the index lifecycle.
6
-
7
- const META_SCHEMA = `
8
- CREATE TABLE IF NOT EXISTS vector_meta (
9
- key TEXT PRIMARY KEY,
10
- value TEXT NOT NULL
11
- );
12
- `;
13
-
14
- export function createVectorIndex({ store, logger }) {
15
- const db = store.db;
16
- db.exec(META_SCHEMA);
17
-
18
- function getMeta(key) {
19
- const row = db.prepare("SELECT value FROM vector_meta WHERE key = ?").get(key);
20
- return row?.value ?? undefined;
21
- }
22
-
23
- function setMeta(key, value) {
24
- db.prepare(
25
- `INSERT INTO vector_meta (key, value) VALUES (?, ?)
26
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`
27
- ).run(key, String(value));
28
- }
29
-
30
- return {
31
- /** Record the model that generated the current vectors. */
32
- markModel(modelHash, dimension) {
33
- setMeta("model_hash", modelHash);
34
- setMeta("dimension", String(dimension ?? ""));
35
- setMeta("updated_at", new Date().toISOString());
36
- },
37
-
38
- modelHash() {
39
- return getMeta("model_hash");
40
- },
41
-
42
- dimension() {
43
- const raw = getMeta("dimension");
44
- return raw && Number.isInteger(Number(raw)) ? Number(raw) : undefined;
45
- },
46
-
47
- /** Store (or clear with null vector) one memory's embedding. */
48
- saveEmbedding(id, vector) {
49
- store.setEmbedding(id, vector);
50
- },
51
-
52
- /** Drop one memory's embedding. */
53
- deleteEmbedding(id) {
54
- store.setEmbedding(id, null);
55
- },
56
-
57
- /** Read one memory's cached vector; undefined when none/parse failure. */
58
- getEmbedding(id) {
59
- // Issue #202:走 store 的解析缓存(与 searchVector/getEmbeddings 同源)。
60
- return store.getParsedEmbedding(id);
61
- },
62
-
63
- /** Cosine search over embedded rows; results carry a 0..1 score. */
64
- search(queryVector, { limit = 20, threshold = 0.65 } = {}) {
65
- return store.searchVector(queryVector, { limit, threshold });
66
- },
67
-
68
- /** Re-embed every row missing an embedding. Returns indexed count. */
69
- async rebuildIndex(embedder, { limit = 1000 } = {}) {
70
- // The loop needs a single-text embedder. Native embedSingle is preferred;
71
- // embed-only OpenAI-compatible clients (issue #10) are accepted too via
72
- // their `embed` single-text interface, so /vector-reindex no longer
73
- // silently returns 0 for them. An embedder exposing neither is ignored.
74
- let embedOne = null;
75
- if (embedder && typeof embedder.embedSingle === "function") {
76
- embedOne = (text) => embedder.embedSingle(text);
77
- } else if (embedder && typeof embedder.embed === "function") {
78
- embedOne = (text) => Promise.resolve(embedder.embed(text));
79
- }
80
- if (!embedOne) return { indexed: 0, skipped: 0 };
81
- const rows = store.needsEmbedding(limit);
82
- let indexed = 0;
83
- for (const row of rows) {
84
- try {
85
- const text = [row.title, row.content].filter(Boolean).join("\n");
86
- const vector = await embedOne(text);
87
- if (vector && vector.length) {
88
- store.setEmbedding(row.id, vector);
89
- indexed++;
90
- }
91
- } catch (error) {
92
- logger?.warn?.(`[dsh-mneme] rebuild embed failed for ${row.id}: ${String(error)}`);
93
- }
94
- }
95
- if (indexed > 0 && embedder.modelHash) this.markModel(embedder.modelHash, embedder.dimension);
96
- return { indexed, skipped: rows.length - indexed };
97
- },
98
-
99
- /** Index stats for the Web panel / debugging. */
100
- getStats() {
101
- return {
102
- modelHash: getMeta("model_hash"),
103
- dimension: this.dimension(),
104
- updatedAt: getMeta("updated_at"),
105
- embeddedCount: store.embeddedCount(),
106
- totalCount: store.count()
107
- };
108
- }
109
- };
110
- }
1
+ // Thin vector-index layer over the store's embedding column. Keeps the
2
+ // current model fingerprint + stats in a dedicated `vector_meta` table so the
3
+ // index can detect drift (embeddings generated by a different model) and the
4
+ // Web panel can report index health. The heavy lifting (cosine search) lives
5
+ // in store.searchVector; this module owns the index lifecycle.
6
+
7
+ const META_SCHEMA = `
8
+ CREATE TABLE IF NOT EXISTS vector_meta (
9
+ key TEXT PRIMARY KEY,
10
+ value TEXT NOT NULL
11
+ );
12
+ `;
13
+
14
+ export function createVectorIndex({ store, logger }) {
15
+ const db = store.db;
16
+ db.exec(META_SCHEMA);
17
+
18
+ function getMeta(key) {
19
+ const row = db.prepare("SELECT value FROM vector_meta WHERE key = ?").get(key);
20
+ return row?.value ?? undefined;
21
+ }
22
+
23
+ function setMeta(key, value) {
24
+ db.prepare(
25
+ `INSERT INTO vector_meta (key, value) VALUES (?, ?)
26
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`
27
+ ).run(key, String(value));
28
+ }
29
+
30
+ return {
31
+ /** Record the model that generated the current vectors. */
32
+ markModel(modelHash, dimension) {
33
+ setMeta("model_hash", modelHash);
34
+ setMeta("dimension", String(dimension ?? ""));
35
+ setMeta("updated_at", new Date().toISOString());
36
+ },
37
+
38
+ modelHash() {
39
+ return getMeta("model_hash");
40
+ },
41
+
42
+ dimension() {
43
+ const raw = getMeta("dimension");
44
+ return raw && Number.isInteger(Number(raw)) ? Number(raw) : undefined;
45
+ },
46
+
47
+ /** Store (or clear with null vector) one memory's embedding. */
48
+ saveEmbedding(id, vector) {
49
+ store.setEmbedding(id, vector);
50
+ },
51
+
52
+ /** Drop one memory's embedding. */
53
+ deleteEmbedding(id) {
54
+ store.setEmbedding(id, null);
55
+ },
56
+
57
+ /** Read one memory's cached vector; undefined when none/parse failure. */
58
+ getEmbedding(id) {
59
+ // Issue #202:走 store 的解析缓存(与 searchVector/getEmbeddings 同源)。
60
+ return store.getParsedEmbedding(id);
61
+ },
62
+
63
+ /** Cosine search over embedded rows; results carry a 0..1 score. */
64
+ search(queryVector, { limit = 20, threshold = 0.65 } = {}) {
65
+ return store.searchVector(queryVector, { limit, threshold });
66
+ },
67
+
68
+ /** Re-embed every row missing an embedding. Returns indexed count. */
69
+ async rebuildIndex(embedder, { limit = 1000 } = {}) {
70
+ // The loop needs a single-text embedder. Native embedSingle is preferred;
71
+ // embed-only OpenAI-compatible clients (issue #10) are accepted too via
72
+ // their `embed` single-text interface, so /vector-reindex no longer
73
+ // silently returns 0 for them. An embedder exposing neither is ignored.
74
+ let embedOne = null;
75
+ if (embedder && typeof embedder.embedSingle === "function") {
76
+ embedOne = (text) => embedder.embedSingle(text);
77
+ } else if (embedder && typeof embedder.embed === "function") {
78
+ embedOne = (text) => Promise.resolve(embedder.embed(text));
79
+ }
80
+ if (!embedOne) return { indexed: 0, skipped: 0 };
81
+ const rows = store.needsEmbedding(limit);
82
+ let indexed = 0;
83
+ for (const row of rows) {
84
+ try {
85
+ const text = [row.title, row.content].filter(Boolean).join("\n");
86
+ const vector = await embedOne(text);
87
+ if (vector && vector.length) {
88
+ store.setEmbedding(row.id, vector);
89
+ indexed++;
90
+ }
91
+ } catch (error) {
92
+ logger?.warn?.(`[dsh-mneme] rebuild embed failed for ${row.id}: ${String(error)}`);
93
+ }
94
+ }
95
+ if (indexed > 0 && embedder.modelHash) this.markModel(embedder.modelHash, embedder.dimension);
96
+ return { indexed, skipped: rows.length - indexed };
97
+ },
98
+
99
+ /** Index stats for the Web panel / debugging. */
100
+ getStats() {
101
+ return {
102
+ modelHash: getMeta("model_hash"),
103
+ dimension: this.dimension(),
104
+ updatedAt: getMeta("updated_at"),
105
+ embeddedCount: store.embeddedCount(),
106
+ totalCount: store.count()
107
+ };
108
+ }
109
+ };
110
+ }
@@ -1,122 +1,122 @@
1
- // 版本自检(issue #174 后续,2026-09-15 拍板):独立插件不把「用户在用哪个
2
- // 版本」托付给插件市场——市场收录有 ~26h 年龄闸门 + 30min 缓存,且安装时
3
- // 精确指定过版本的 profile 会被 pnpm 钉子挡住(update 尊重既有 semver 范围,
4
- // 永不跨 minor/major,#174 的报障者正是这样用着 0.7.32 的行为模型来报 bug)。
5
- //
6
- // 本模块只做三件事:
7
- // 1. 向 npm registry 查 @modusensus/dsh-mneme 的 latest dist-tag(带 TTL
8
- // 缓存 + 超时 + 全失败静默——离线/被墙/registry 异常都返回 null,调用方
9
- // 据 null 渲染「未知」,前端不打扰);
10
- // 2. 与运行版本做纯函数比对(classify);
11
- // 3. 对外暴露 registry URL 白名单校验(validateRegistryUrl)——发请求前
12
- // 强制 https + 精确 host,构造上排除本机与内网地址。
13
- import { readFileSync } from "node:fs";
14
-
15
- // 运行版本:src/ 与 lib/ 都在插件根下一层,相对 import.meta.url 解析一致;
16
- // 读取失败(打包/受限环境)降级 "unknown",横幅随之静默。
17
- const PACKAGE_VERSION = (() => {
18
- try {
19
- return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version ?? "unknown";
20
- } catch {
21
- return "unknown";
22
- }
23
- })();
24
-
25
- // registry 查询地址是模块常量而非用户输入;validateRegistryUrl 仍作为发请求
26
- // 前的强制闸(构造上即排除非 https 与非白名单 host,双保险且可单测)。
27
- const REGISTRY_URL = "https://registry.npmjs.org/@modusensus%2Fdsh-mneme/latest";
28
- const REGISTRY_HOST = "registry.npmjs.org";
29
- // 市场收录本身有 ~1 天年龄闸门,1h 的 registry 缓存远低于该粒度,足够新鲜。
30
- const CACHE_TTL_MS = 60 * 60 * 1000;
31
- const FETCH_TIMEOUT_MS = 5000;
32
-
33
- // 精确 host 白名单:协议必须 https,且 host 逐字等于 registry.npmjs.org。
34
- // 这一条即构造性排除本机回环、私有网段与保留地址——不做任何
35
- // 「看起来像公网」的宽松判断,将来换源必须显式改这里的常量。
36
- export function validateRegistryUrl(candidate) {
37
- let url;
38
- try {
39
- url = new URL(candidate);
40
- } catch {
41
- return false;
42
- }
43
- return url.protocol === "https:" && url.hostname === REGISTRY_HOST;
44
- }
45
-
46
- /** 解析 `x.y.z` / `x.y.z-后缀` 为可比较结构;解析失败返回 null。 */
47
- function parseVersion(text) {
48
- if (typeof text !== "string") return null;
49
- const match = text.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
50
- if (!match) return null;
51
- return {
52
- major: Number(match[1]),
53
- minor: Number(match[2]),
54
- patch: Number(match[3]),
55
- // 有 prerelease 后缀的同号版本视为更旧(0.9.0-rc.1 < 0.9.0)。
56
- prerelease: match[4] !== undefined
57
- };
58
- }
59
-
60
- /**
61
- * 三元组语义化比较:a<b → -1,a>b → 1,无法比较 → null(调用方归入 unknown)。
62
- * 仅比较数字部分;数字相等时,带 prerelease 的一方更旧(0.9.0-rc.1 < 0.9.0),
63
- * 两侧都带则视为同版——横幅只关心「是否落后于 latest」,不追求完整 semver 序。
64
- */
65
- export function compareVersions(a, b) {
66
- const va = parseVersion(a);
67
- const vb = parseVersion(b);
68
- if (!va || !vb) return null;
69
- for (const key of ["major", "minor", "patch"]) {
70
- if (va[key] !== vb[key]) return va[key] < vb[key] ? -1 : 1;
71
- }
72
- if (va.prerelease !== vb.prerelease) return va.prerelease ? -1 : 1;
73
- return 0;
74
- }
75
-
76
- /**
77
- * 运行版本 vs registry latest 的展示归类。latest 为 null(查询失败/离线)
78
- * 或任一侧解析失败时归 unknown——前端对 unknown 完全静默。
79
- */
80
- export function classify(version, latest) {
81
- const cmp = compareVersions(version, latest);
82
- if (cmp === null) return "unknown";
83
- if (cmp < 0) return "outdated";
84
- if (cmp > 0) return "ahead";
85
- return "up-to-date";
86
- }
87
-
88
- // 模块级缓存:面板可能多处/多次拉取,TTL 内一律复用,不重复打 registry。
89
- // at 用 -Infinity 作「从未拉取」哨兵:任何时钟下 now-at 都是正无穷,首轮
90
- // 必然真实请求(测试的假时钟从 0 起也不会被误判成新鲜缓存)。
91
- let cache = { at: -Infinity, latest: null };
92
-
93
- /**
94
- * 查询 registry latest。TTL 内直接命中缓存;任何失败(网络/超时/非 2xx/
95
- * 响应形状不对/URL 校验不过)都静默返回 null——版本提示是锦上添花,绝不
96
- * 让它成为新的故障面。失败不写缓存:TTL 起点保持旧值,下次调用立刻重试。
97
- */
98
- export async function fetchLatestVersion({ fetchImpl = typeof fetch === "function" ? fetch : () => Promise.reject(new Error("no fetch")), now = Date.now } = {}) {
99
- if (now() - cache.at < CACHE_TTL_MS) return cache.latest;
100
- if (!validateRegistryUrl(REGISTRY_URL)) return null;
101
- let manifest;
102
- try {
103
- const response = await fetchImpl(REGISTRY_URL, {
104
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
105
- headers: { accept: "application/json" }
106
- });
107
- if (!response.ok) return null;
108
- manifest = await response.json();
109
- } catch {
110
- return null;
111
- }
112
- const latest = typeof manifest?.version === "string" && manifest.version ? manifest.version : null;
113
- cache = { at: now(), latest };
114
- return latest;
115
- }
116
-
117
- /** 仅供测试:清空模块级缓存与时间戳。 */
118
- export function resetCacheForTest() {
119
- cache = { at: -Infinity, latest: null };
120
- }
121
-
122
- export { PACKAGE_VERSION, REGISTRY_URL, CACHE_TTL_MS };
1
+ // 版本自检(issue #174 后续,2026-09-15 拍板):独立插件不把「用户在用哪个
2
+ // 版本」托付给插件市场——市场收录有 ~26h 年龄闸门 + 30min 缓存,且安装时
3
+ // 精确指定过版本的 profile 会被 pnpm 钉子挡住(update 尊重既有 semver 范围,
4
+ // 永不跨 minor/major,#174 的报障者正是这样用着 0.7.32 的行为模型来报 bug)。
5
+ //
6
+ // 本模块只做三件事:
7
+ // 1. 向 npm registry 查 @modusensus/dsh-mneme 的 latest dist-tag(带 TTL
8
+ // 缓存 + 超时 + 全失败静默——离线/被墙/registry 异常都返回 null,调用方
9
+ // 据 null 渲染「未知」,前端不打扰);
10
+ // 2. 与运行版本做纯函数比对(classify);
11
+ // 3. 对外暴露 registry URL 白名单校验(validateRegistryUrl)——发请求前
12
+ // 强制 https + 精确 host,构造上排除本机与内网地址。
13
+ import { readFileSync } from "node:fs";
14
+
15
+ // 运行版本:src/ 与 lib/ 都在插件根下一层,相对 import.meta.url 解析一致;
16
+ // 读取失败(打包/受限环境)降级 "unknown",横幅随之静默。
17
+ const PACKAGE_VERSION = (() => {
18
+ try {
19
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version ?? "unknown";
20
+ } catch {
21
+ return "unknown";
22
+ }
23
+ })();
24
+
25
+ // registry 查询地址是模块常量而非用户输入;validateRegistryUrl 仍作为发请求
26
+ // 前的强制闸(构造上即排除非 https 与非白名单 host,双保险且可单测)。
27
+ const REGISTRY_URL = "https://registry.npmjs.org/@modusensus%2Fdsh-mneme/latest";
28
+ const REGISTRY_HOST = "registry.npmjs.org";
29
+ // 市场收录本身有 ~1 天年龄闸门,1h 的 registry 缓存远低于该粒度,足够新鲜。
30
+ const CACHE_TTL_MS = 60 * 60 * 1000;
31
+ const FETCH_TIMEOUT_MS = 5000;
32
+
33
+ // 精确 host 白名单:协议必须 https,且 host 逐字等于 registry.npmjs.org。
34
+ // 这一条即构造性排除本机回环、私有网段与保留地址——不做任何
35
+ // 「看起来像公网」的宽松判断,将来换源必须显式改这里的常量。
36
+ export function validateRegistryUrl(candidate) {
37
+ let url;
38
+ try {
39
+ url = new URL(candidate);
40
+ } catch {
41
+ return false;
42
+ }
43
+ return url.protocol === "https:" && url.hostname === REGISTRY_HOST;
44
+ }
45
+
46
+ /** 解析 `x.y.z` / `x.y.z-后缀` 为可比较结构;解析失败返回 null。 */
47
+ function parseVersion(text) {
48
+ if (typeof text !== "string") return null;
49
+ const match = text.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
50
+ if (!match) return null;
51
+ return {
52
+ major: Number(match[1]),
53
+ minor: Number(match[2]),
54
+ patch: Number(match[3]),
55
+ // 有 prerelease 后缀的同号版本视为更旧(0.9.0-rc.1 < 0.9.0)。
56
+ prerelease: match[4] !== undefined
57
+ };
58
+ }
59
+
60
+ /**
61
+ * 三元组语义化比较:a<b → -1,a>b → 1,无法比较 → null(调用方归入 unknown)。
62
+ * 仅比较数字部分;数字相等时,带 prerelease 的一方更旧(0.9.0-rc.1 < 0.9.0),
63
+ * 两侧都带则视为同版——横幅只关心「是否落后于 latest」,不追求完整 semver 序。
64
+ */
65
+ export function compareVersions(a, b) {
66
+ const va = parseVersion(a);
67
+ const vb = parseVersion(b);
68
+ if (!va || !vb) return null;
69
+ for (const key of ["major", "minor", "patch"]) {
70
+ if (va[key] !== vb[key]) return va[key] < vb[key] ? -1 : 1;
71
+ }
72
+ if (va.prerelease !== vb.prerelease) return va.prerelease ? -1 : 1;
73
+ return 0;
74
+ }
75
+
76
+ /**
77
+ * 运行版本 vs registry latest 的展示归类。latest 为 null(查询失败/离线)
78
+ * 或任一侧解析失败时归 unknown——前端对 unknown 完全静默。
79
+ */
80
+ export function classify(version, latest) {
81
+ const cmp = compareVersions(version, latest);
82
+ if (cmp === null) return "unknown";
83
+ if (cmp < 0) return "outdated";
84
+ if (cmp > 0) return "ahead";
85
+ return "up-to-date";
86
+ }
87
+
88
+ // 模块级缓存:面板可能多处/多次拉取,TTL 内一律复用,不重复打 registry。
89
+ // at 用 -Infinity 作「从未拉取」哨兵:任何时钟下 now-at 都是正无穷,首轮
90
+ // 必然真实请求(测试的假时钟从 0 起也不会被误判成新鲜缓存)。
91
+ let cache = { at: -Infinity, latest: null };
92
+
93
+ /**
94
+ * 查询 registry latest。TTL 内直接命中缓存;任何失败(网络/超时/非 2xx/
95
+ * 响应形状不对/URL 校验不过)都静默返回 null——版本提示是锦上添花,绝不
96
+ * 让它成为新的故障面。失败不写缓存:TTL 起点保持旧值,下次调用立刻重试。
97
+ */
98
+ export async function fetchLatestVersion({ fetchImpl = typeof fetch === "function" ? fetch : () => Promise.reject(new Error("no fetch")), now = Date.now } = {}) {
99
+ if (now() - cache.at < CACHE_TTL_MS) return cache.latest;
100
+ if (!validateRegistryUrl(REGISTRY_URL)) return null;
101
+ let manifest;
102
+ try {
103
+ const response = await fetchImpl(REGISTRY_URL, {
104
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
105
+ headers: { accept: "application/json" }
106
+ });
107
+ if (!response.ok) return null;
108
+ manifest = await response.json();
109
+ } catch {
110
+ return null;
111
+ }
112
+ const latest = typeof manifest?.version === "string" && manifest.version ? manifest.version : null;
113
+ cache = { at: now(), latest };
114
+ return latest;
115
+ }
116
+
117
+ /** 仅供测试:清空模块级缓存与时间戳。 */
118
+ export function resetCacheForTest() {
119
+ cache = { at: -Infinity, latest: null };
120
+ }
121
+
122
+ export { PACKAGE_VERSION, REGISTRY_URL, CACHE_TTL_MS };