@modusensus/dsh-mneme 0.8.3 → 0.8.5

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 (205) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +727 -636
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +510 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +506 -316
  7. package/lib/api.js +1403 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4657 -4366
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +615 -510
  12. package/lib/document.js +221 -0
  13. package/lib/dream/clustering.js +118 -118
  14. package/lib/dream/decisions.js +658 -658
  15. package/lib/dream/narratives.js +44 -0
  16. package/lib/dream/sleep.js +702 -700
  17. package/lib/dream.js +147 -16
  18. package/lib/embedding.js +177 -177
  19. package/lib/entities/extractor.js +249 -249
  20. package/lib/guide.js +44 -0
  21. package/lib/heat.js +144 -136
  22. package/lib/hot-memory.js +46 -46
  23. package/lib/index.js +515 -515
  24. package/lib/inject.js +375 -295
  25. package/lib/lang.js +208 -179
  26. package/lib/local-embedder.js +320 -320
  27. package/lib/mirror.js +198 -198
  28. package/lib/organize.js +450 -0
  29. package/lib/quality-filter.js +126 -126
  30. package/lib/recall-stats.js +125 -0
  31. package/lib/reranker.js +269 -269
  32. package/lib/runtime/adopt.js +176 -176
  33. package/lib/runtime/closure.js +172 -172
  34. package/lib/runtime/download.js +247 -247
  35. package/lib/runtime/layout.js +265 -235
  36. package/lib/runtime/loader.js +252 -249
  37. package/lib/runtime/model-fetch.js +361 -361
  38. package/lib/runtime/provision.js +237 -237
  39. package/lib/runtime/tarball.js +130 -130
  40. package/lib/runtime/verify.js +204 -191
  41. package/lib/scope.js +118 -118
  42. package/lib/search/adaptive.js +60 -22
  43. package/lib/search/bm25.js +96 -96
  44. package/lib/service.js +2324 -2087
  45. package/lib/settings.js +459 -420
  46. package/lib/store.js +2549 -2367
  47. package/lib/summarize.js +820 -449
  48. package/lib/tools.js +702 -574
  49. package/lib/vector-index.js +110 -110
  50. package/lib/version-check.js +122 -122
  51. package/package.json +109 -108
  52. package/runtime-manifest.json +526 -596
  53. package/scripts/benchmark-embed.js +201 -201
  54. package/scripts/benchmark-recall.js +199 -199
  55. package/scripts/benchmark-rerank.js +166 -166
  56. package/scripts/build-runtime-manifest.mjs +224 -217
  57. package/scripts/check-sync.js +42 -42
  58. package/scripts/e2e-dsh.js +220 -220
  59. package/scripts/mneme-runtime.mjs +277 -277
  60. package/scripts/stress-dsh.js +255 -255
  61. package/scripts/sync-lib.js +47 -47
  62. package/scripts/sync-test-badge.mjs +67 -61
  63. package/src/api-standalone.js +506 -316
  64. package/src/api.js +1403 -1316
  65. package/src/bootstrap.js +211 -0
  66. package/src/commands.js +95 -95
  67. package/src/config.js +615 -510
  68. package/src/document.js +221 -0
  69. package/src/dream/clustering.js +118 -118
  70. package/src/dream/decisions.js +658 -658
  71. package/src/dream/narratives.js +44 -0
  72. package/src/dream/sleep.js +702 -700
  73. package/src/dream.js +147 -16
  74. package/src/embedding.js +177 -177
  75. package/src/entities/extractor.js +249 -249
  76. package/src/guide.js +44 -0
  77. package/src/heat.js +144 -136
  78. package/src/hot-memory.js +46 -46
  79. package/src/index.js +515 -515
  80. package/src/inject.js +375 -295
  81. package/src/lang.js +208 -179
  82. package/src/local-embedder.js +320 -320
  83. package/src/mirror.js +198 -198
  84. package/src/organize.js +450 -0
  85. package/src/quality-filter.js +126 -126
  86. package/src/recall-stats.js +125 -0
  87. package/src/reranker.js +269 -269
  88. package/src/runtime/adopt.js +176 -176
  89. package/src/runtime/closure.js +172 -172
  90. package/src/runtime/download.js +247 -247
  91. package/src/runtime/layout.js +265 -235
  92. package/src/runtime/loader.js +252 -249
  93. package/src/runtime/model-fetch.js +361 -361
  94. package/src/runtime/provision.js +237 -237
  95. package/src/runtime/tarball.js +130 -130
  96. package/src/runtime/verify.js +204 -191
  97. package/src/scope.js +118 -118
  98. package/src/search/adaptive.js +60 -22
  99. package/src/search/bm25.js +96 -96
  100. package/src/service.js +2324 -2087
  101. package/src/settings.js +459 -420
  102. package/src/store.js +2549 -2367
  103. package/src/summarize.js +820 -449
  104. package/src/tools.js +702 -574
  105. package/src/vector-index.js +110 -110
  106. package/src/version-check.js +122 -122
  107. package/test/adaptive-inject-budget.test.js +85 -0
  108. package/test/api-routes-gaps.test.js +218 -218
  109. package/test/api.test.js +1640 -1482
  110. package/test/audit.test.js +448 -448
  111. package/test/benchmark.test.js +94 -94
  112. package/test/bootstrap.test.js +220 -0
  113. package/test/client.test.js +860 -736
  114. package/test/clustering.test.js +100 -100
  115. package/test/commands.test.js +106 -106
  116. package/test/config.test.js +66 -66
  117. package/test/conflict-freeze.test.js +300 -300
  118. package/test/document.test.js +523 -0
  119. package/test/dream-archive-guardrail.test.js +116 -116
  120. package/test/dream-candidate-hybrid.test.js +281 -281
  121. package/test/dream-coverage-degrade.test.js +86 -86
  122. package/test/dream.test.js +1308 -1254
  123. package/test/embedding-ready.test.js +196 -196
  124. package/test/entities.test.js +547 -547
  125. package/test/entity-recall.test.js +179 -0
  126. package/test/epistemic.test.js +298 -298
  127. package/test/fnew-0112.test.js +311 -311
  128. package/test/fnew-03.test.js +422 -422
  129. package/test/graph-api.test.js +175 -175
  130. package/test/heat.test.js +175 -148
  131. package/test/helpers/dream-mock.js +82 -82
  132. package/test/helpers/peer-worker.mjs +25 -25
  133. package/test/helpers/runtime-source.js +60 -60
  134. package/test/helpers/tar-builder.js +80 -80
  135. package/test/hot-memory.test.js +145 -145
  136. package/test/inject-content-cap.test.js +91 -0
  137. package/test/inject-first-round-bm25.test.js +89 -89
  138. package/test/inject-heat.test.js +61 -0
  139. package/test/inject-pools.test.js +170 -0
  140. package/test/inject-recall.test.js +105 -0
  141. package/test/inject-rotation.test.js +161 -161
  142. package/test/inject.test.js +283 -249
  143. package/test/lang.test.js +87 -87
  144. package/test/lib-smoke.test.js +96 -96
  145. package/test/llm-audit.test.js +462 -309
  146. package/test/llm-message-source.test.js +177 -177
  147. package/test/local-embedder.test.js +249 -249
  148. package/test/mcp-stdio.test.js +385 -0
  149. package/test/mirror-dirty.test.js +424 -424
  150. package/test/mirror-edit-digest.test.js +187 -187
  151. package/test/mirror-generation.test.js +499 -499
  152. package/test/mirror.test.js +249 -249
  153. package/test/narrative-bars.test.js +162 -0
  154. package/test/organize.test.js +418 -0
  155. package/test/peer-blockers.test.js +193 -193
  156. package/test/policy-epoch.test.js +259 -259
  157. package/test/quality-filter.test.js +186 -186
  158. package/test/reasoning-effort.test.js +746 -746
  159. package/test/recall-evals.test.js +235 -235
  160. package/test/recall-layer.test.js +326 -326
  161. package/test/recall-stats.test.js +123 -0
  162. package/test/receipt-chain.test.js +451 -451
  163. package/test/reflection.test.js +226 -226
  164. package/test/reindex-backfill.test.js +62 -62
  165. package/test/reranker-single-logit.test.js +73 -73
  166. package/test/reranker.test.js +197 -197
  167. package/test/resident-status.test.js +83 -0
  168. package/test/runtime-adopt.test.js +206 -206
  169. package/test/runtime-cli.test.js +89 -89
  170. package/test/runtime-closure.test.js +193 -193
  171. package/test/runtime-download.test.js +302 -302
  172. package/test/runtime-layout.test.js +163 -163
  173. package/test/runtime-loader.test.js +255 -237
  174. package/test/runtime-manifest.test.js +159 -158
  175. package/test/runtime-model-fetch.test.js +348 -348
  176. package/test/runtime-provision.test.js +101 -101
  177. package/test/runtime-tarball.test.js +81 -81
  178. package/test/runtime-verify.test.js +279 -214
  179. package/test/scope-candidates.test.js +239 -239
  180. package/test/scope-explicit.test.js +452 -452
  181. package/test/scope-retrieval.test.js +197 -197
  182. package/test/scope-storage.test.js +255 -255
  183. package/test/scope-strict.test.js +231 -231
  184. package/test/search-fusion.test.js +90 -90
  185. package/test/semantic.test.js +124 -124
  186. package/test/service-search.test.js +174 -174
  187. package/test/service.test.js +405 -405
  188. package/test/settings.test.js +261 -261
  189. package/test/skip-invalid-restore.test.js +262 -262
  190. package/test/sleep-action-set.test.js +422 -422
  191. package/test/sleep-heat.test.js +126 -125
  192. package/test/sleep-scheduler-rearm.test.js +89 -89
  193. package/test/sleep.test.js +410 -373
  194. package/test/standalone-api.test.js +544 -359
  195. package/test/store-vector-cache.test.js +98 -98
  196. package/test/store.test.js +396 -383
  197. package/test/stress.test.js +209 -209
  198. package/test/summarize.test.js +1288 -575
  199. package/test/tools-dto-schema-matrix.test.js +325 -0
  200. package/test/tools-memory-get-schema.test.js +65 -65
  201. package/test/tools.test.js +374 -341
  202. package/test/updated-at-semantics.test.js +113 -113
  203. package/test/vector-index.test.js +221 -221
  204. package/test/version-check.test.js +152 -152
  205. 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 };