dsh-memu-memory 1.4.3 → 1.4.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 (183) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +34 -15
  4. package/README.zh.md +35 -13
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/preset-mount.js +13 -7
  63. package/lib/private.js +47 -21
  64. package/lib/recall-cache.js +20 -34
  65. package/lib/retention.js +173 -0
  66. package/lib/rpc.js +135 -52
  67. package/lib/rt-index/builder.js +209 -0
  68. package/lib/rt-index/format.js +231 -0
  69. package/lib/rt-index/manifest.js +105 -0
  70. package/lib/rt-index/reader.js +673 -0
  71. package/lib/rt-index-retention.js +151 -0
  72. package/lib/rt-index-service.js +283 -0
  73. package/lib/rt-index-worker.js +21 -0
  74. package/lib/salient-wake.js +55 -4
  75. package/lib/state.js +195 -24
  76. package/lib/temporal.js +39 -13
  77. package/lib/token-measurement.js +126 -0
  78. package/lib/tools.js +101 -6
  79. package/lib/turn-log.js +108 -3
  80. package/lib/webui/graph-layout-worker.js +68 -0
  81. package/lib/webui/graph-local-physics.js +390 -0
  82. package/lib/webui/graph-spatial-grid.js +64 -0
  83. package/lib/webui/graph-view.bundle.js +6 -1
  84. package/lib/webui/graph-view.js +478 -135
  85. package/lib/webui/graph-webgl-renderer.js +74 -0
  86. package/lib/webui/standalone.js +1 -1
  87. package/lib/worker-pool.js +38 -7
  88. package/package.json +3 -2
  89. package/scripts/acceptance-local.mjs +4 -10
  90. package/scripts/bench-all-libraries.mjs +47 -0
  91. package/scripts/check-classic-graph-browser.mjs +189 -0
  92. package/scripts/check-client-browser.mjs +929 -0
  93. package/scripts/check-graph-browser.mjs +6 -0
  94. package/scripts/check-graph-elastic-browser.mjs +139 -0
  95. package/scripts/check-memory-review-browser.mjs +124 -0
  96. package/scripts/entity-dedupe.mjs +19 -3
  97. package/scripts/graph-artifact-provenance.mjs +30 -0
  98. package/scripts/graph-freeze-manifest.mjs +129 -0
  99. package/scripts/graph-geometry-fixture.mjs +40 -0
  100. package/scripts/graph-physics-bench.mjs +218 -0
  101. package/scripts/graph-scale-bench.mjs +213 -0
  102. package/scripts/graph-scale-memory.mjs +48 -0
  103. package/scripts/graph-service-bench.mjs +72 -0
  104. package/scripts/make-readme-shots.mjs +17 -5
  105. package/scripts/preview.mjs +1 -0
  106. package/scripts/rebuild-rt.mjs +18 -0
  107. package/scripts/scale-bench.mjs +183 -0
  108. package/scripts/simulate-injection.mjs +47 -8
  109. package/scripts/verify-host-fixtures.mjs +108 -0
  110. package/scripts/verify-host-recovery.mjs +565 -0
  111. package/scripts/verify-vector-recovery.mjs +740 -0
  112. package/tests/auto-link-candidates.test.mjs +20 -0
  113. package/tests/browser.test.mjs +16 -2
  114. package/tests/client-export.test.mjs +16 -1
  115. package/tests/client-pagination.test.mjs +1495 -0
  116. package/tests/client-render.test.mjs +223 -28
  117. package/tests/consolidation-fork.test.mjs +97 -13
  118. package/tests/consolidation-ledger.test.mjs +17 -1
  119. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  120. package/tests/diagnostic-report.test.mjs +429 -0
  121. package/tests/diagnostic-wiring.test.mjs +88 -0
  122. package/tests/diagnostics.test.mjs +27 -0
  123. package/tests/embedding-download.test.mjs +44 -0
  124. package/tests/engine-source-settings.test.mjs +69 -0
  125. package/tests/engine-sources.test.mjs +145 -0
  126. package/tests/entity-dedupe.test.mjs +143 -0
  127. package/tests/entity-merge-review.test.mjs +363 -0
  128. package/tests/entity-merge.test.mjs +12 -4
  129. package/tests/entity-review.test.mjs +87 -0
  130. package/tests/environment-check.test.mjs +51 -1
  131. package/tests/feedback.test.mjs +95 -0
  132. package/tests/graph-adjacency-index.test.mjs +536 -0
  133. package/tests/graph-cascade.test.mjs +229 -0
  134. package/tests/graph-import-diagnostic.test.mjs +25 -0
  135. package/tests/graph-overview.test.mjs +709 -0
  136. package/tests/graph-session-authorization.test.mjs +419 -0
  137. package/tests/graph-view-geometry.test.mjs +426 -0
  138. package/tests/graph-view-scale.test.mjs +88 -0
  139. package/tests/graph-view.test.mjs +444 -5
  140. package/tests/graph.test.mjs +43 -0
  141. package/tests/help-page.test.mjs +128 -54
  142. package/tests/inbound.test.mjs +19 -0
  143. package/tests/index-pagination.test.mjs +113 -0
  144. package/tests/index-read-view.test.mjs +212 -0
  145. package/tests/inject-guide.test.mjs +9 -0
  146. package/tests/injection-dedupe.test.mjs +213 -0
  147. package/tests/lexicon-recall.test.mjs +641 -0
  148. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  149. package/tests/lexicon-rt.test.mjs +468 -0
  150. package/tests/local-embedding-worker.test.mjs +38 -0
  151. package/tests/local-vector-service.test.mjs +32 -3
  152. package/tests/maintenance-compat.test.mjs +128 -0
  153. package/tests/maintenance-settlement.test.mjs +1003 -0
  154. package/tests/managed-memory.test.mjs +39 -11
  155. package/tests/managed-runtime.test.mjs +109 -0
  156. package/tests/memory-fields.test.mjs +24 -12
  157. package/tests/observed-evidence.test.mjs +52 -0
  158. package/tests/port-surface.test.mjs +93 -1
  159. package/tests/preset-mount.test.mjs +12 -4
  160. package/tests/recall-cache.test.mjs +56 -3
  161. package/tests/recall-dedup.test.mjs +63 -2
  162. package/tests/retention.test.mjs +260 -0
  163. package/tests/rt-index-cross-library.test.mjs +230 -0
  164. package/tests/rt-index-integration.test.mjs +194 -0
  165. package/tests/rt-index-retention.test.mjs +552 -0
  166. package/tests/rt-index-scale.test.mjs +204 -0
  167. package/tests/rt-index.test.mjs +705 -0
  168. package/tests/salient-date-boundaries.test.mjs +121 -0
  169. package/tests/salient-wake.test.mjs +29 -0
  170. package/tests/scale-bench.test.mjs +53 -0
  171. package/tests/settings-plumbing.test.mjs +25 -0
  172. package/tests/simulate-injection.test.mjs +15 -1
  173. package/tests/standalone-navigation.test.mjs +44 -0
  174. package/tests/state.test.mjs +51 -0
  175. package/tests/temporal-precision.test.mjs +102 -0
  176. package/tests/temporal.test.mjs +10 -6
  177. package/tests/token-measurement.test.mjs +98 -0
  178. package/tests/tool-schema.test.mjs +41 -5
  179. package/tests/tools.test.mjs +6 -3
  180. package/tests/turn-token-budget.test.mjs +149 -0
  181. package/tests/webui-auth.test.mjs +57 -1
  182. package/tests/webui.test.mjs +40 -15
  183. package/tests/worker-lifecycle.test.mjs +2 -1
@@ -0,0 +1,286 @@
1
+ // Platform-aware download sources for the managed engine bootstrap.
2
+ //
3
+ // Everything in this file is pure data + pure parsing so tests can exercise the
4
+ // fallback chain without touching the network. The installer in
5
+ // managed-runtime.js consumes the plan and does the I/O.
6
+ //
7
+ // Two policies exist on purpose:
8
+ // pinned (default) install exactly UV_VERSION / MANAGED_PYTHON and verify the
9
+ // digests pinned in this file; mirrors that do not carry that
10
+ // exact release are skipped.
11
+ // unpinned allowed only when the user opts in (settings or
12
+ // DSH_MEMU_ALLOW_UNPINNED): a rolling mirror may serve its
13
+ // newest release, verified against the mirror's own
14
+ // sha256.sum instead of a code-pinned digest.
15
+ //
16
+ // Domestic mirrors keep only the newest release tag, so a pinned version almost
17
+ // never exists there; unpinned is what makes GitHub-blocked machines install.
18
+ import fs from 'node:fs'
19
+
20
+ export const UV_VERSION = '0.13.6'
21
+ export const MANAGED_PYTHON = '3.12.14'
22
+ export const MANAGED_PYTHON_SERIES = '3.12'
23
+
24
+ export const UV_OFFICIAL_BASE = 'https://github.com/astral-sh/uv/releases/download'
25
+ export const PYTHON_OFFICIAL_BASE = 'https://github.com/astral-sh/python-build-standalone/releases/download'
26
+ // USTC keeps only the latest tag per project and exposes sha256.sum for it.
27
+ export const USTC_UV_BASE = 'https://mirrors.ustc.edu.cn/github-release/astral-sh/uv'
28
+ export const USTC_PYTHON_BASE = 'https://mirrors.ustc.edu.cn/github-release/astral-sh/python-build-standalone'
29
+
30
+ export const ENGINE_SOURCES = ['auto', 'mirror', 'official', 'custom']
31
+
32
+ // Pinned release digests, verified against astral-sh/uv release metadata on
33
+ // 2026-10-28. `null` means "no code-pinned digest": the artifact can still be
34
+ // installed from a mirror that publishes sha256.sum (unpinned mode), because a
35
+ // digest we never saw cannot be verified.
36
+ const ASSETS = {
37
+ 'win32-x64': ['uv-x86_64-pc-windows-msvc.zip', 'a2a8820d5eea32f08ef467ef3b7f66883a9b076d5737a2fc2fbb5f458d1bb50f'],
38
+ 'win32-arm64': ['uv-aarch64-pc-windows-msvc.zip', 'c2426c0c8e28b53d8c440e47a18d96ad4db51e159866c0e81435b196d7f0081c'],
39
+ 'linux-x64': ['uv-x86_64-unknown-linux-gnu.tar.gz', 'f29c3e94ffabd7e6f3ba521dba169a9b7ec12100bf3257087f0f24f6123f3645'],
40
+ 'linux-arm64': ['uv-aarch64-unknown-linux-gnu.tar.gz', '229e194255c7958d86d56e8790d969a6f74736592133f0dfd0076f754c642c1d'],
41
+ 'linux-x64-musl': ['uv-x86_64-unknown-linux-musl.tar.gz', null],
42
+ 'linux-arm64-musl': ['uv-aarch64-unknown-linux-musl.tar.gz', null],
43
+ 'darwin-x64': ['uv-x86_64-apple-darwin.tar.gz', '63ba17fdda55ad1a230d4b37fc6017ffa10c23688c83818bd3bfdf914c652a02'],
44
+ 'darwin-arm64': ['uv-aarch64-apple-darwin.tar.gz', '60fbd5c8a1ed681845eea28d9d622fcde03c51e91a43465b64a1e17db1ed3472'],
45
+ }
46
+
47
+ // python-build-standalone's own target triples, used to pick a mirror's newest
48
+ // install_only archive for the current machine.
49
+ const PYTHON_TRIPLES = {
50
+ 'win32-x64': 'x86_64-pc-windows-msvc',
51
+ 'win32-arm64': 'aarch64-pc-windows-msvc',
52
+ 'linux-x64': 'x86_64-unknown-linux-gnu',
53
+ 'linux-arm64': 'aarch64-unknown-linux-gnu',
54
+ 'linux-x64-musl': 'x86_64-unknown-linux-musl',
55
+ 'linux-arm64-musl': 'aarch64-unknown-linux-musl',
56
+ 'darwin-x64': 'x86_64-apple-darwin',
57
+ 'darwin-arm64': 'aarch64-apple-darwin',
58
+ }
59
+
60
+ const ARCH_LABEL = { x64: 'x86_64', arm64: 'aarch64' }
61
+
62
+ function reportHeader() {
63
+ try {
64
+ return typeof process.report?.getReport === 'function' ? process.report.getReport().header : null
65
+ } catch {
66
+ return null
67
+ }
68
+ }
69
+
70
+ // Linux has two libc worlds and uv ships separate binaries for them. glibc is
71
+ // the default everywhere except Alpine/musl containers; DSH_MEMU_LIBC exists so
72
+ // a mismatched probe can be overridden without patching the plugin.
73
+ export function detectLibc({ platform = process.platform, env = process.env, exists = fs.existsSync, header = reportHeader() } = {}) {
74
+ if (platform !== 'linux') return 'gnu'
75
+ const forced = String(env.DSH_MEMU_LIBC || '').trim().toLowerCase()
76
+ if (forced === 'musl' || forced === 'gnu') return forced
77
+ if (header?.glibcVersionRuntime) return 'gnu'
78
+ try {
79
+ if (exists('/etc/alpine-release')) return 'musl'
80
+ } catch {}
81
+ return 'gnu'
82
+ }
83
+
84
+ export function resolveRuntimePlatform({ platform = process.platform, arch = process.arch, libc = detectLibc({ platform }) } = {}) {
85
+ const baseKey = `${platform}-${arch}`
86
+ const key = platform === 'linux' && libc === 'musl' ? `${baseKey}-musl` : baseKey
87
+ const asset = ASSETS[key] || null
88
+ return {
89
+ key,
90
+ platform,
91
+ arch,
92
+ libc: platform === 'linux' ? libc : null,
93
+ supported: Boolean(asset),
94
+ asset: asset ? asset[0] : null,
95
+ archiveKind: asset && asset[0].endsWith('.zip') ? 'zip' : 'tar.gz',
96
+ sha256: asset ? asset[1] : null,
97
+ pythonTriple: PYTHON_TRIPLES[key] || null,
98
+ }
99
+ }
100
+
101
+ export function runtimeGuidance(platform) {
102
+ const arch = ARCH_LABEL[platform.arch] || platform.arch
103
+ const where = platform.key
104
+ return [
105
+ `no managed runtime is published for ${where} (${arch}).`,
106
+ 'Install Python 3.11+ with pip (or uv) yourself and point DSH_MEMU_PYTHON at it,',
107
+ 'or set DSH_MEMU_LIBC=musl/gnu when the libc probe guessed wrong.',
108
+ ].join(' ')
109
+ }
110
+
111
+ // Transport failures are a different animal: the platform is supported and a
112
+ // Python may already exist, we simply could not reach any source.
113
+ export function downloadGuidance() {
114
+ return [
115
+ 'Every configured source failed at the network layer.',
116
+ 'If GitHub is unreachable from this machine, turn on "Let mirrors serve their newest version" (DSH_MEMU_ALLOW_UNPINNED=1),',
117
+ 'or install Python 3.11+ with pip (apt install python3-pip) and point DSH_MEMU_PYTHON at it.',
118
+ ].join(' ')
119
+ }
120
+
121
+ function trimUrl(value) {
122
+ const base = typeof value === 'string' ? value.trim().replace(/\/+$/, '') : ''
123
+ if (base) {
124
+ try {
125
+ const url = new URL(base)
126
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error('invalid base')
127
+ } catch { throw new Error('engine mirror must be an HTTP(S) base URL without credentials, query or fragment') }
128
+ }
129
+ return base
130
+ }
131
+
132
+ function readSource(value) {
133
+ const source = String(value || '').trim().toLowerCase()
134
+ return ENGINE_SOURCES.includes(source) ? source : 'auto'
135
+ }
136
+
137
+ function readFlag(value, fallback) {
138
+ if (value === undefined || value === null || value === '') return fallback === true
139
+ const text = String(value).trim().toLowerCase()
140
+ if (['1', 'true', 'yes', 'on'].includes(text)) return true
141
+ if (['0', 'false', 'no', 'off'].includes(text)) return false
142
+ return fallback === true
143
+ }
144
+
145
+ function uvSource(id, label, base, kind, latestOk) {
146
+ return { id, label, base, kind, latestOk }
147
+ }
148
+
149
+ function pythonSource(id, label, base, latestOk) {
150
+ return { id, label, base, kind: base ? 'mirror' : 'official', latestOk }
151
+ }
152
+
153
+ // Builds the ordered source plan for one install. Order rules:
154
+ // auto / mirror / custom -> custom (if any), USTC, GitHub
155
+ // official -> custom (if any), GitHub, USTC
156
+ // `latestOk` only says the source *could* serve a rolling newest release; the
157
+ // digest policy (allowUnpinned) still decides whether it is used.
158
+ export function resolveEngineSources({ settings = {}, env = process.env, platform = process.platform, arch = process.arch, libc } = {}) {
159
+ const requested = readSource(env.DSH_MEMU_ENGINE_SOURCE || settings.engineSource)
160
+ const allowUnpinned = readFlag(env.DSH_MEMU_ALLOW_UNPINNED, settings.engineAllowUnpinned)
161
+ const customUv = trimUrl(env.DSH_MEMU_UV_MIRROR || settings.engineUvMirror)
162
+ const customPython = trimUrl(env.DSH_MEMU_CPYTHON_MIRROR || settings.enginePythonMirror)
163
+ const runtime = resolveRuntimePlatform({ platform, arch, libc: libc || detectLibc({ platform, env }) })
164
+
165
+ const uvCandidates = []
166
+ const addUv = (source) => {
167
+ if (!source || !source.base) return
168
+ if (uvCandidates.some((item) => item.base === source.base)) return
169
+ uvCandidates.push(source)
170
+ }
171
+ const customUvSource = customUv ? uvSource('custom', 'custom uv mirror', customUv, 'custom', true) : null
172
+ const ustcUv = uvSource('ustc', 'USTC mirror', USTC_UV_BASE, 'mirror', true)
173
+ const officialUv = uvSource('official', 'GitHub releases', UV_OFFICIAL_BASE, 'official', false)
174
+ if (requested === 'official') {
175
+ addUv(customUvSource)
176
+ addUv(officialUv)
177
+ addUv(ustcUv)
178
+ } else {
179
+ addUv(customUvSource)
180
+ addUv(ustcUv)
181
+ addUv(officialUv)
182
+ }
183
+
184
+ const pythonCandidates = []
185
+ const addPython = (source) => {
186
+ if (!source) return
187
+ if (pythonCandidates.some((item) => item.base === source.base)) return
188
+ pythonCandidates.push(source)
189
+ }
190
+ const customPythonSource = customPython ? pythonSource('custom', 'custom CPython mirror', customPython, true) : null
191
+ const ustcPython = pythonSource('ustc', 'USTC mirror', USTC_PYTHON_BASE, true)
192
+ const officialPython = pythonSource('official', 'python-build-standalone (GitHub)', null, false)
193
+ if (requested === 'official') {
194
+ addPython(customPythonSource)
195
+ addPython(officialPython)
196
+ addPython(ustcPython)
197
+ } else {
198
+ addPython(customPythonSource)
199
+ addPython(ustcPython)
200
+ addPython(officialPython)
201
+ }
202
+
203
+ return {
204
+ requested,
205
+ allowUnpinned,
206
+ runtime,
207
+ pinned: { uv: UV_VERSION, python: MANAGED_PYTHON, series: MANAGED_PYTHON_SERIES },
208
+ uv: uvCandidates,
209
+ python: pythonCandidates,
210
+ }
211
+ }
212
+
213
+ export function describeSources(plan) {
214
+ const annotate = (source) => `${source.label}${plan.allowUnpinned && source.latestOk ? ' (may serve newest)' : ''}`
215
+ const uv = (plan.uv || []).map(annotate).join(' -> ')
216
+ const python = (plan.python || []).map(annotate).join(' -> ')
217
+ return `${plan.allowUnpinned ? 'pinned+newest-allowed' : 'pinned'}; uv: ${uv}; cpython: ${python}; platform: ${plan.runtime.key}`
218
+ }
219
+
220
+ export function parseSha256Sum(text) {
221
+ const out = new Map()
222
+ for (const line of String(text || '').split(/\r?\n/)) {
223
+ const match = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(line.trim())
224
+ if (match) out.set(match[2].trim(), match[1].toLowerCase())
225
+ }
226
+ return out
227
+ }
228
+
229
+ export function compareVersions(a, b) {
230
+ const left = String(a || '').split('.').map((part) => Number(part.replace(/[^0-9].*$/, '')) || 0)
231
+ const right = String(b || '').split('.').map((part) => Number(part.replace(/[^0-9].*$/, '')) || 0)
232
+ for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
233
+ const diff = (left[i] || 0) - (right[i] || 0)
234
+ if (diff) return diff
235
+ }
236
+ return 0
237
+ }
238
+
239
+ // The mirror's directory listing is a plain HTML index: one href per version.
240
+ export function pickLatestUvVersion(text) {
241
+ const versions = []
242
+ for (const match of String(text || '').matchAll(/href="[^"]*?\/(\d+\.\d+\.\d+)\/?"/g)) versions.push(match[1])
243
+ versions.sort(compareVersions)
244
+ return versions.length ? versions[versions.length - 1] : null
245
+ }
246
+
247
+ // Finds the newest install_only CPython archive for one series/triple. The
248
+ // listing may be the project root or a LatestRelease directory; both expose
249
+ // hrefs like `.../20261124/cpython-3.12.16%2B20261124-x86_64-...-install_only.tar.gz`.
250
+ export function pickLatestPythonBuild(text, { triple = null, series = MANAGED_PYTHON_SERIES } = {}) {
251
+ // Directory indexes wrap entries in href="..."; plain listings (and tests) may
252
+ // paste the path bare. Strip the markup and match the archive names directly.
253
+ const hrefs = [...String(text || '').replace(/href="/g, ' ').replace(/"/g, ' ').matchAll(/(\S+\.tar\.gz)/g)].map((match) => decodeURIComponent(match[1]))
254
+ const pattern = new RegExp('^cpython-(\\d+\\.\\d+\\.\\d+)\\+(\\d+)-(.+)-install_only\\.tar\\.gz$')
255
+ const found = []
256
+ for (const href of hrefs) {
257
+ const name = href.split('/').pop() || ''
258
+ const match = pattern.exec(name)
259
+ if (!match) continue
260
+ const version = match[1]
261
+ const build = match[2]
262
+ const archTriple = match[3]
263
+ if (triple && archTriple !== triple) continue
264
+ if (!String(version).startsWith(`${series}.`)) continue
265
+ found.push({ version, build, triple: archTriple, filename: name })
266
+ }
267
+ found.sort((a, b) => compareVersions(b.version, a.version) || Number(b.build) - Number(a.build))
268
+ return found[0] || null
269
+ }
270
+
271
+ // Node's fetch reports every transport failure as `TypeError: fetch failed` and
272
+ // keeps the real reason (ECONNRESET, ENOTFOUND, certificate errors) in `cause`.
273
+ // The installer used to print only error.message, which turned every network
274
+ // failure into the same opaque line.
275
+ export function describeFetchError(error) {
276
+ if (!error) return 'unknown error'
277
+ const base = String(error.message || error)
278
+ const cause = error.cause
279
+ if (!cause) return base
280
+ const code = cause.code || cause.errno || ''
281
+ const message = typeof cause.message === 'string' ? cause.message : ''
282
+ if (code && message) return `${base} (${code}: ${message})`
283
+ if (code) return `${base} (${code})`
284
+ if (message) return `${base}: ${message}`
285
+ return base
286
+ }
package/lib/engine.js CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  } from './paths.js'
11
11
  import { getSettings, globalDbPath } from './state.js'
12
12
  import { ensureManagedPython } from './managed-runtime.js'
13
+ import { resolveEngineSources, describeSources, describeFetchError } from './engine-sources.js'
13
14
 
14
15
  const HERE = path.dirname(fileURLToPath(import.meta.url))
15
16
  const LOCK_PATH = path.join(HERE, '..', 'requirements.lock')
@@ -706,16 +707,21 @@ export function engineStatus({ withSize = false } = {}) {
706
707
 
707
708
  export function mirrorCandidates() {
708
709
  // The settings page's pipIndexes list is a real user preference and must be
709
- // honored here; env vars only add transient overrides on top.
710
- const fromSettings = Array.isArray(getSettings().pipIndexes)
711
- ? getSettings().pipIndexes.map((s) => String(s || '').trim()).filter(Boolean)
710
+ // honored here; env vars only add transient overrides on top. The engine
711
+ // download-source preference flips only the built-in defaults, so a mirror
712
+ // pinned by the user still wins.
713
+ const settings = getSettings()
714
+ const fromSettings = Array.isArray(settings.pipIndexes)
715
+ ? settings.pipIndexes.map((s) => String(s || '').trim()).filter(Boolean)
712
716
  : []
713
717
  const configured = String(process.env.DSH_MEMU_PIP_INDEXES || '')
714
718
  .split(',')
715
719
  .map((s) => s.trim())
716
720
  .filter(Boolean)
717
721
  const envIndex = String(process.env.PIP_INDEX_URL || '').trim()
718
- const list = envIndex ? [envIndex, ...fromSettings, ...configured, ...DEFAULT_INDEXES] : [...fromSettings, ...configured, ...DEFAULT_INDEXES]
722
+ const source = String(process.env.DSH_MEMU_ENGINE_SOURCE || settings.engineSource || 'auto').trim().toLowerCase()
723
+ const defaults = source === 'official' ? [...DEFAULT_INDEXES].reverse() : [...DEFAULT_INDEXES]
724
+ const list = envIndex ? [envIndex, ...fromSettings, ...configured, ...defaults] : [...fromSettings, ...configured, ...defaults]
719
725
  return [...new Set(list)]
720
726
  }
721
727
 
@@ -949,7 +955,7 @@ function stateError(error, extra = {}) {
949
955
  status: 'error',
950
956
  version: ENGINE_VERSION,
951
957
  step: 'failed',
952
- error: String(error?.message || error),
958
+ error: describeFetchError(error),
953
959
  startedAt: previous.startedAt || null,
954
960
  finishedAt: stamp(),
955
961
  ...extra,
@@ -989,8 +995,13 @@ export async function installEngine({ force = false, log = null, beforeSwitch =
989
995
  stateInstalling('resolving-python')
990
996
  logLine(`installing MemU engine ${ENGINE_VERSION}`, log)
991
997
 
998
+ const settings = getSettings()
999
+ const sourcePlan = resolveEngineSources({ settings, env: process.env })
1000
+ logLine(`engine sources: ${describeSources(sourcePlan)}`, log)
992
1001
  const candidates = await resolvePythonCandidates()
993
- if (!candidates.some(candidate => candidate.hasPip)) candidates.push(await ensureManagedPython({ run, log: line => logLine(line, log) }))
1002
+ if (!candidates.some(candidate => candidate.hasPip)) {
1003
+ candidates.push(await ensureManagedPython({ run, log: line => logLine(line, log), settings }))
1004
+ }
994
1005
  logLine(`python candidates: ${candidates.map((c) => `${c.cmd} ${c.prefix.join(' ')} (${c.version.raw}${c.hasPip ? '' : ', no-pip'})`).join('; ')}`, log)
995
1006
 
996
1007
  const errors = []
@@ -1065,8 +1076,9 @@ export async function installEngine({ force = false, log = null, beforeSwitch =
1065
1076
  return { ok: true, current, verified }
1066
1077
  } catch (error) {
1067
1078
  await cleanupDir(tmpVenv)
1068
- errors.push(`${base.source}: ${error.message}`)
1069
- logLine(`candidate failed: ${base.source}: ${error.message}`, log)
1079
+ const detail = describeFetchError(error)
1080
+ errors.push(`${base.source}: ${detail}`)
1081
+ logLine(`candidate failed: ${base.source}: ${detail}`, log)
1070
1082
  }
1071
1083
  }
1072
1084
 
@@ -1078,8 +1090,9 @@ export async function installEngine({ force = false, log = null, beforeSwitch =
1078
1090
  } catch (error) {
1079
1091
  stateError(error)
1080
1092
  await cleanupDownloads()
1081
- logLine(`install failed: ${error.message}`, log)
1082
- return { ok: false, status: 'error', error: String(error?.message || error) }
1093
+ const detail = describeFetchError(error)
1094
+ logLine(`install failed: ${detail}`, log)
1095
+ return { ok: false, status: 'error', error: detail }
1083
1096
  } finally {
1084
1097
  releaseLock()
1085
1098
  }
@@ -8,7 +8,7 @@
8
8
  // · attested —— 可证明:窗口片段首尾重叠重建出的更长名字**在正文里真的出现过**,或短名在
9
9
  // 全库正文里**从未**独立于某个更长名字出现过。这类可以自动合并。
10
10
  // · similar —— 只是相似:编辑距离 ≤2 或名字核重合(`顾清欢` 与 `顾清悦` 就是这么撞上的)。
11
- // 这类**绝不自动写**,只在诊断页报数,由人点「需确认」的修复按钮。
11
+ // 这类**绝不自动写**,在图管理中列为候选,由人逐个核对。
12
12
  //
13
13
  // 写入只走 lib/graph.js 的 mergeEntities(别名并集、links 改指、evidence 改指、继承 confirmed、
14
14
  // 清孤儿都在那条级联里),本模块不自建第二条写路径。合并前的全库备份由调用方负责。
@@ -23,8 +23,11 @@ import { listLibraries as defaultListLibraries, loadPrivateIndex as defaultLoadP
23
23
  // 包括本次修复根本没碰的节点。修复不能顺手删东西,所以写入前后各读一次快照,把计划外的
24
24
  // 行原样写回(硬规则 5)。
25
25
  const ENTITIES_FILE = (libraryId) => path.join(indexDir(), `${libraryId}.entities.json`)
26
- // 正文扫描上限:单库超过这个条目数时只取最近的这些,并在结论里标 `partial`。
26
+ // These are work limits, not permission to infer identity from partial evidence.
27
+ export const ENTITY_REPAIR_ENTITY_LIMIT = 256
27
28
  const CORPUS_ENTRY_CAP = 3000
29
+ const REBUILD_MEMBER_CAP = 8
30
+ const REBUILD_STEP_CAP = 4096
28
31
 
29
32
  const normalized = (value) => String(value ?? '').normalize('NFKC').toLowerCase().trim()
30
33
 
@@ -45,16 +48,14 @@ function overlapJoin(left, right) {
45
48
  return null
46
49
  }
47
50
 
48
- /** 全库正文(标题 + 正文,NFKC + 小写)。返回 {texts, partial}。 */
51
+ /** 全库正文;超过证明预算时不把一部分正文当成全库证据。 */
49
52
  function corpusTexts(loadPrivateIndex, libraryId) {
50
53
  const entries = Object.values(loadPrivateIndex(libraryId).entries || {})
51
54
  .filter((entry) => entry && typeof entry === 'object')
52
- const sorted = entries.length > CORPUS_ENTRY_CAP
53
- ? [...entries].sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || ''))).slice(0, CORPUS_ENTRY_CAP)
54
- : entries
55
+ if (entries.length > CORPUS_ENTRY_CAP) return { texts: [], partial: true }
55
56
  return {
56
- texts: sorted.map((entry) => `${entry.title || ''}\n${entry.content || ''}`.normalize('NFKC').toLowerCase()),
57
- partial: entries.length > CORPUS_ENTRY_CAP,
57
+ texts: entries.map((entry) => `${entry.title || ''}\n${entry.content || ''}`.normalize('NFKC').toLowerCase()),
58
+ partial: false,
58
59
  }
59
60
  }
60
61
 
@@ -105,10 +106,26 @@ function unionFind(ids) {
105
106
  * @param {{graph: object, loadPrivateIndex: Function}} deps 注入便于测试与脚本复用
106
107
  */
107
108
  export function planLibraryRepair(libraryId, { graph = defaultGraph, loadPrivateIndex = defaultLoadPrivateIndex } = {}) {
108
- const listed = graph.listEntities({ libraryId }).items
109
- .filter((entity) => entity && entity.id && String(entity.status || 'provisional') !== 'archived')
110
- if (listed.length < 2) return { libraryId, groups: [], ambiguous: [], scanned: listed.length, partial: false }
109
+ // The public linked listing reads every memory to derive `linked`. Repair only
110
+ // needs entity rows; graphExport preserves the same library authorization.
111
+ const rows = (typeof graph.graphExport === 'function'
112
+ ? Object.values(graph.graphExport(libraryId).entities || {})
113
+ : graph.listEntities({ libraryId }).items).filter((entity) => entity && entity.id)
114
+ const totalEntities = rows.length
115
+ const base = { libraryId, groups: [], ambiguous: [], totalEntities, entityLimit: ENTITY_REPAIR_ENTITY_LIMIT }
116
+ const defer = (reason, scanned = 0) => ({ ...base, scanned, partial: true, deferred: true, reason })
117
+ // Count archived rows too: the merge-candidate source includes those rows.
118
+ // No corpus, name normalization, pair scan or reconstruction precedes this gate.
119
+ if (totalEntities > ENTITY_REPAIR_ENTITY_LIMIT) return defer('entity-limit')
120
+ const listed = rows.filter((entity) => String(entity.status || 'provisional') !== 'archived')
121
+ if (listed.length < 2) return { ...base, scanned: listed.length, partial: false, deferred: false, reason: null }
122
+ const suggestions = graph.suggestEntityMerges({ libraryId })
123
+ if (suggestions.scanComplete === false || suggestions.complete === false || suggestions.totalExact === false
124
+ || suggestions.partial === true || suggestions.deferred === true || suggestions.nextCursor
125
+ || suggestions.truncated === true
126
+ || (suggestions.totalExact === true && suggestions.total > suggestions.items.length)) return defer('candidate-scan-incomplete')
111
127
  const { texts, partial } = corpusTexts(loadPrivateIndex, libraryId)
128
+ if (partial) return defer('corpus-limit')
112
129
  const index = new Map(listed.map((entity) => [entity.id, entity]))
113
130
  const { find, union } = unionFind(listed.map((entity) => entity.id))
114
131
  const evidenceOf = new Map()
@@ -122,7 +139,7 @@ export function planLibraryRepair(libraryId, { graph = defaultGraph, loadPrivate
122
139
  union(shorter.id, longer.id)
123
140
  evidenceOf.set(shorter.id + '>' + longer.id, onlyInsideCorpus(key, [normalized(longer.name)], texts) ? 'attested' : 'similar')
124
141
  }
125
- for (const item of graph.suggestEntityMerges({ libraryId }).items) {
142
+ for (const item of suggestions.items) {
126
143
  if (!index.has(item.sourceId) || !index.has(item.targetId)) continue
127
144
  union(item.sourceId, item.targetId)
128
145
  if (!evidenceOf.has(item.sourceId + '>' + item.targetId)) evidenceOf.set(item.sourceId + '>' + item.targetId, 'similar')
@@ -137,6 +154,7 @@ export function planLibraryRepair(libraryId, { graph = defaultGraph, loadPrivate
137
154
 
138
155
  const groups = []
139
156
  const ambiguous = []
157
+ let rebuildSteps = 0
140
158
  for (const members of components.values()) {
141
159
  if (members.length < 2) continue
142
160
  const ordered = [...members].sort((a, b) => normalized(b.name).length - normalized(a.name).length
@@ -162,20 +180,26 @@ export function planLibraryRepair(libraryId, { graph = defaultGraph, loadPrivate
162
180
  // 没有完整名节点:首尾重叠重建一个,并在正文里验到才算 attested。
163
181
  let rebuilt = null
164
182
  if (ordered[0].kind === 'person') {
183
+ if (names.length > REBUILD_MEMBER_CAP) return defer('rebuild-limit', listed.length)
165
184
  let best = null
185
+ let exhausted = false
166
186
  const extend = (used, current) => {
187
+ if (exhausted) return
188
+ if (++rebuildSteps > REBUILD_STEP_CAP) { exhausted = true; return }
167
189
  if (current.length > 16) return
168
190
  if (used.size === names.length) {
169
191
  if (!best || current.length > best.length) best = current
170
192
  return
171
193
  }
172
194
  for (const name of names) {
195
+ if (exhausted) return
173
196
  if (used.has(name)) continue
174
197
  const joined = overlapJoin(current, name)
175
198
  if (joined) { used.add(name); extend(used, joined); used.delete(name) }
176
199
  }
177
200
  }
178
201
  for (const name of names) extend(new Set([name]), name)
202
+ if (exhausted) return defer('rebuild-limit', listed.length)
179
203
  if (best && best.length > Math.max(...names.map((name) => name.length))) {
180
204
  const needle = normalized(best)
181
205
  if (texts.some((text) => text.includes(needle))) rebuilt = best
@@ -197,7 +221,7 @@ export function planLibraryRepair(libraryId, { graph = defaultGraph, loadPrivate
197
221
  evidence: 'similar',
198
222
  })
199
223
  }
200
- return { libraryId, groups, ambiguous, scanned: listed.length, partial }
224
+ return { ...base, groups, ambiguous, scanned: listed.length, partial: false, deferred: false, reason: null }
201
225
  }
202
226
 
203
227
  /** 所有未归档库的规划汇总。 */
@@ -215,6 +239,12 @@ export function planAllRepairs({ graph = defaultGraph, listLibraries = defaultLi
215
239
  return {
216
240
  plans,
217
241
  failures,
242
+ partial: failures.length > 0 || plans.some((plan) => plan.partial),
243
+ deferred: failures.length > 0 || plans.some((plan) => plan.deferred),
244
+ totalEntities: plans.reduce((total, plan) => total + plan.totalEntities, 0),
245
+ totalEntitiesExact: failures.length === 0,
246
+ scanned: plans.reduce((total, plan) => total + plan.scanned, 0),
247
+ entityLimit: ENTITY_REPAIR_ENTITY_LIMIT,
218
248
  attested: plans.reduce((total, plan) => total + plan.groups.length, 0),
219
249
  similar: plans.reduce((total, plan) => total + plan.ambiguous.length, 0),
220
250
  }
@@ -0,0 +1,64 @@
1
+ import { getSettings, listSessionBindings, listLibrariesAll, effectiveScope, setSessionBinding } from './state.js'
2
+ import { suggestEntityMerges } from './graph.js'
3
+ import { requestPrivateConsolidation, archivedSessionIdsOf, isConsolidating } from './private.js'
4
+ import { record } from './activity-log.js'
5
+ import { redactSecrets } from './paths.js'
6
+
7
+ // Reuse the normal executor and the owning session's model. The persisted retry
8
+ // clock also covers interruptions; an idle model that did nothing is not success.
9
+ export async function runEntityReviewPass(ctx, { now = Date.now(), limit = 2, log = () => {}, request = requestPrivateConsolidation } = {}) {
10
+ if (getSettings().sleepConsolidation !== true) return { ran: 0, skipped: 'disabled' }
11
+ const libraries = new Map(listLibrariesAll().filter(lib => !lib.archived).map(lib => [lib.id, lib]))
12
+ const archived = archivedSessionIdsOf(ctx)
13
+ const sessions = listSessionBindings().filter(binding => !binding.consolidationFork && !binding.sessionGone
14
+ && libraries.has(binding.libraryId) && !archived?.has(binding.sessionId) && effectiveScope(binding).useLibrary)
15
+ .sort((a, b) => String(a.entityReviewRetryAt || '').localeCompare(String(b.entityReviewRetryAt || ''))
16
+ || String(b.lastTurnAt || '').localeCompare(String(a.lastTurnAt || '')))
17
+ const claimed = new Set()
18
+ let ran = 0, scanned = 0
19
+ for (const binding of sessions) {
20
+ if (ran >= Math.max(1, Math.min(10, limit)) || scanned >= 20) break
21
+ if (claimed.has(binding.libraryId) || isConsolidating(binding.sessionId)
22
+ || (Date.parse(binding.entityReviewRetryAt || '') || 0) > now) continue
23
+ let agent = null
24
+ try { agent = ctx.get?.('agents')?.get?.(binding.sessionId) } catch {}
25
+ if (agent?.status === 'running') continue
26
+ const activeAt = Math.max(Date.parse(binding.lastTurnAt) || 0, Date.parse(binding.lastInboundAt) || 0,
27
+ Date.parse(binding.lastAgentIdleAt) || 0)
28
+ if (now - activeAt < 60_000 || binding.inbound?.pending?.length && now - activeAt < 15 * 60_000) continue
29
+ scanned++
30
+ const exec = { agent: { session: { header: { id: binding.sessionId } } } }
31
+ try {
32
+ let page
33
+ try { page = suggestEntityMerges({ exec, libraryId: binding.libraryId, reviewState: 'model', cursor: binding.entityReviewCursor }) }
34
+ catch (error) {
35
+ if (error?.code !== 'ENTITY_MERGE_SCAN_STALE') throw error
36
+ page = suggestEntityMerges({ exec, libraryId: binding.libraryId, reviewState: 'model' })
37
+ }
38
+ if (!page.items.length) {
39
+ setSessionBinding(binding.sessionId, { entityReviewCursor: page.nextCursor || null,
40
+ entityReviewRetryAt: new Date(now + (page.nextCursor ? 5 : 15) * 60_000).toISOString() })
41
+ continue
42
+ }
43
+ claimed.add(binding.libraryId)
44
+ ran++
45
+ // Claim before awaiting so another host sweep/restart observes the lease.
46
+ setSessionBinding(binding.sessionId, { entityReviewRetryAt: new Date(now + 12 * 60_000).toISOString() })
47
+ const result = await request(ctx, binding.sessionId, { entityReviewOnly: true,
48
+ entityReviewPairs: page.items.slice(0, 4), trigger: 'entity-review' })
49
+ if (result?.ok !== true || result.settled !== true) throw new Error(result?.error || result?.reasonCode || 'entity review was not verified')
50
+ setSessionBinding(binding.sessionId, { entityReviewCursor: null, entityReviewAttempts: 0, lastEntityReviewError: null,
51
+ lastEntityReviewAt: new Date(now).toISOString(), entityReviewRetryAt: new Date(now + 5 * 60_000).toISOString() })
52
+ } catch (error) {
53
+ const attempts = Math.min(6, Number(binding.entityReviewAttempts || 0) + 1)
54
+ const message = redactSecrets(String(error?.message || error)).slice(0, 1000)
55
+ setSessionBinding(binding.sessionId, { entityReviewCursor: null, entityReviewAttempts: attempts,
56
+ lastEntityReviewError: message, entityReviewRetryAt: new Date(now + Math.min(60, 2 ** attempts) * 60_000).toISOString() })
57
+ log(`entity review failed for ${binding.sessionId}: ${message}`)
58
+ try { ctx.logger?.warn?.(`dsh-memu-memory entity review: ${message}`) } catch {}
59
+ record({ kind: 'consolidate', scope: 'private', libraryId: binding.libraryId, sessionId: binding.sessionId,
60
+ ok: false, level: 'warn', message: '实体自动裁决失败,将退避重试', detail: { phase: 'entity-review', error: message } })
61
+ }
62
+ }
63
+ return { ran, scanned }
64
+ }