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,151 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { dataDir, indexDir, readFailure, withFileLock } from './paths.js'
4
+ import { listLibrariesAll } from './state.js'
5
+ import { listArtifacts, indexLocation } from './rt-index/reader.js'
6
+ import { readJsonLimited, readPublished, validGeneration, validSegmentId } from './rt-index/manifest.js'
7
+ import { LEXICON_DOCUMENT_VERSION } from './lexicon-rt-source.js'
8
+
9
+ const DAY = 86400000
10
+ const isDirectory = file => {
11
+ try { const stat = fs.lstatSync(file); return stat.isDirectory() && !stat.isSymbolicLink() } catch { return false }
12
+ }
13
+
14
+ function statOrNull(file) {
15
+ try { return fs.lstatSync(file) } catch (error) { if (error.code === 'ENOENT') return null; throw error }
16
+ }
17
+
18
+ function ordinaryTree(file) {
19
+ const stat = statOrNull(file)
20
+ if (!stat || stat.isSymbolicLink()) return false
21
+ if (stat.isFile()) return true
22
+ return stat.isDirectory() && fs.readdirSync(file).every(name => ordinaryTree(path.join(file, name)))
23
+ }
24
+
25
+ function safeArtifacts(root) {
26
+ for (const name of fs.readdirSync(root).filter(validGeneration)) {
27
+ const file = path.join(root, name)
28
+ if (!isDirectory(file) || !ordinaryTree(file)) return false
29
+ }
30
+ const segments = path.join(root, 'segments')
31
+ if (!statOrNull(segments)) return true
32
+ return isDirectory(segments) && fs.readdirSync(segments).filter(validSegmentId).every(name => {
33
+ const file = path.join(segments, name)
34
+ return isDirectory(file) && ordinaryTree(file)
35
+ })
36
+ }
37
+
38
+ function truthMissing({ libraryId, namespace }) {
39
+ const directory = namespace === 'lexicon' ? path.join(dataDir(), 'lexicon') : indexDir()
40
+ const stat = statOrNull(directory)
41
+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) return false
42
+ // A dangling link or unreadable path is not proof that source truth is absent.
43
+ return statOrNull(path.join(directory, `${libraryId}.json`)) === null
44
+ }
45
+
46
+ function removeEmptyDirectory(directory) {
47
+ if (!isDirectory(directory)) return
48
+ try { fs.rmdirSync(directory) } catch (error) {
49
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST', 'EBUSY'].includes(error.code)) throw error
50
+ }
51
+ }
52
+
53
+ function reliableLibraries() {
54
+ const libraries = listLibrariesAll()
55
+ if (readFailure(path.join(dataDir(), 'state.json')) || !Array.isArray(libraries)) {
56
+ throw new Error('library registry could not be read reliably')
57
+ }
58
+ return libraries
59
+ }
60
+
61
+ /** Disposable artifacts only. Unknown/corrupt identities and live references fail safe. */
62
+ export function pruneRtArtifacts({ now = Date.now(), olderThanDays = 7, dryRun = true } = {}) {
63
+ if (!Number.isFinite(now) || !Number.isFinite(olderThanDays) || olderThanDays < 0) throw new Error('invalid rt retention time')
64
+ const directory = path.join(dataDir(), 'rt')
65
+ const result = { dryRun, olderThanDays, candidates: [], removed: [], kept: [] }
66
+ if (!isDirectory(directory)) return result
67
+ const libraries = reliableLibraries()
68
+ const known = new Map(['memory', 'lexicon'].flatMap(namespace => [namespace === 'memory' ? null : 'global', ...libraries.map(library => library.id)].map(libraryId => {
69
+ const location = indexLocation({ directory, libraryId, namespace })
70
+ return [location.identity, { libraryId, namespace }]
71
+ })))
72
+ const cutoff = now - olderThanDays * DAY
73
+ for (const identity of fs.readdirSync(directory)) {
74
+ if (!/^[a-f0-9]{64}$/.test(identity)) continue
75
+ const root = path.join(directory, identity)
76
+ if (!isDirectory(root)) { result.kept.push({ identity, reason: 'not-regular-directory' }); continue }
77
+ const lock = statOrNull(path.join(root, 'current.json.lock'))
78
+ if (lock && (!lock.isFile() || lock.isSymbolicLink())) {
79
+ result.kept.push({ identity, reason: 'unsafe-publication-lock' }); continue
80
+ }
81
+ let cleanedOrphan = false
82
+ withFileLock(path.join(root, 'current.json'), () => {
83
+ if (!isDirectory(directory) || !isDirectory(root)) {
84
+ result.kept.push({ identity, reason: 'not-regular-directory' }); return
85
+ }
86
+ let manifest, options, inventory
87
+ try {
88
+ const pointer = readJsonLimited(path.join(root, 'current.json'), 4096)
89
+ if (!validGeneration(pointer?.generation) || !/^[a-f0-9]{64}$/.test(pointer.sha256)) throw new Error('unsafe pointer')
90
+ if (!isDirectory(path.join(root, pointer.generation))) throw new Error('unsafe generation')
91
+ const owner = readJsonLimited(path.join(root, pointer.generation, 'manifest.json'), 1024 * 1024, pointer.sha256)
92
+ const libraryId = owner?.libraryId
93
+ const namespace = owner?.namespace
94
+ if (!['memory', 'lexicon'].includes(namespace) || (libraryId === null ? namespace !== 'memory'
95
+ : (typeof libraryId !== 'string' || !/^[a-z0-9_-]+$/i.test(libraryId)))) throw new Error('unknown identity')
96
+ options = { directory, libraryId, namespace,
97
+ documentVersion: namespace === 'lexicon' ? LEXICON_DOCUMENT_VERSION : 'memory-title-body-tags-captions-v1' }
98
+ const location = indexLocation(options)
99
+ if (location.identity !== identity) throw new Error('unknown identity')
100
+ manifest = readPublished(location, options.documentVersion).manifest
101
+ inventory = listArtifacts(options)
102
+ if (inventory.state !== 'ready' || inventory.generation !== manifest.generation
103
+ || inventory.artifacts.filter(item => item.referenced).length !== manifest.segments.length + 1) throw new Error('unreadable references')
104
+ } catch {
105
+ result.kept.push({ identity, reason: known.has(identity) ? 'references-unreadable' : 'identity-unknown' }); return
106
+ }
107
+ if (!safeArtifacts(root)) { result.kept.push({ identity, reason: 'unsafe-artifact-tree' }); return }
108
+ // Registry includes archived libraries. Recheck it only after acquiring the
109
+ // same publication lock used by the builder; historical inventories do not
110
+ // establish orphanhood, and global artifacts are never orphan candidates.
111
+ const registered = (options.namespace === 'memory' ? options.libraryId === null : options.libraryId === 'global')
112
+ || reliableLibraries().some(item => item.id === options.libraryId)
113
+ const orphan = !registered && truthMissing(options)
114
+ if (!registered && !orphan) {
115
+ result.kept.push({ identity, reason: 'unregistered-truth-present' }); return
116
+ }
117
+ const pointer = path.join(root, 'current.json')
118
+ // Keep the ownership pointer until every known artifact can retire; a
119
+ // newer unpublished artifact must not become an unidentifiable leftover.
120
+ const retireCurrent = orphan && statOrNull(pointer)?.mtimeMs < cutoff
121
+ && inventory.artifacts.every(item => item.mtimeMs < cutoff)
122
+ const candidates = inventory.artifacts.filter(item => item.mtimeMs < cutoff
123
+ && (item.referenced === false || retireCurrent))
124
+ if (retireCurrent) candidates.push({ kind: 'pointer', name: 'current.json', path: pointer })
125
+ for (const artifact of candidates) {
126
+ const label = { identity, kind: artifact.kind, name: artifact.name }
127
+ result.candidates.push(label)
128
+ if (dryRun) continue
129
+ const target = path.resolve(artifact.path)
130
+ if (path.dirname(target) !== path.resolve(root)
131
+ && path.dirname(target) !== path.join(path.resolve(root), 'segments')) throw new Error('unsafe rt artifact target')
132
+ if (!isDirectory(directory) || !isDirectory(root) || !ordinaryTree(target)
133
+ || (artifact.kind !== 'pointer' && !isDirectory(target))
134
+ || (artifact.kind === 'segment' && !isDirectory(path.join(root, 'segments')))) {
135
+ throw new Error('rt artifact changed to an unsafe path')
136
+ }
137
+ if (artifact.kind === 'pointer') fs.unlinkSync(target)
138
+ else fs.rmSync(target, { recursive: true, force: true })
139
+ result.removed.push(label)
140
+ }
141
+ cleanedOrphan = retireCurrent && !dryRun
142
+ })
143
+ // Never recursively remove the lock's parent. A concurrent builder/unknown
144
+ // file keeps these directories nonempty, so an unlocked rmdir leaves it alone.
145
+ if (cleanedOrphan && isDirectory(directory) && isDirectory(root)) {
146
+ removeEmptyDirectory(path.join(root, 'segments'))
147
+ removeEmptyDirectory(root)
148
+ }
149
+ }
150
+ return result
151
+ }
@@ -0,0 +1,283 @@
1
+ import path from 'node:path'
2
+ import { Worker } from 'node:worker_threads'
3
+ import { createRtIndex, indexLocation } from './rt-index/reader.js'
4
+ import { createBoundedCache } from './bounded-cache.js'
5
+ import { dataDir, warn } from './paths.js'
6
+ import { indexDataRevision, indexReadRevision, onIndexCommit, readPrivateIndex, readGlobalIndex, listLibrariesAll } from './state.js'
7
+ import { record } from './activity-log.js'
8
+ import { childEnvironment } from './local-embedding-manager.js'
9
+
10
+ const controllers = new Map()
11
+ const sources = new WeakMap()
12
+ let viewsByIndex = new WeakMap()
13
+ const views = createBoundedCache({
14
+ name: 'rtQueryViews', maxBytes: 32 * 1024 * 1024, maxEntries: 32, ttlMs: 60000,
15
+ sizeOf: value => value.bytes,
16
+ onEvict(key, value) {
17
+ const index = value.index.deref()
18
+ if (index) viewsByIndex.get(index)?.delete(key)
19
+ },
20
+ })
21
+ const pending = new Map()
22
+ const counters = { builds: 0, failedBuilds: 0, staleBuilds: 0, deltas: 0, fallbacks: 0, shadowQueries: 0, shadowMismatches: 0, shadowBodies: 0, shadowBodyMismatches: 0 }
23
+ let active = null
24
+ let timer = null
25
+ let closed = false
26
+ let unsubscribe = null
27
+
28
+ export const rtMode = () => ['off', 'shadow', 'on'].includes(process.env.DSH_MEMU_RT_INDEX) ? process.env.DSH_MEMU_RT_INDEX : 'shadow'
29
+ export const rtDirectory = () => path.join(dataDir(), 'rt')
30
+ const minEntries = () => Math.max(0, Number(process.env.DSH_MEMU_RT_MIN_ENTRIES) || 256)
31
+ const load = libraryId => libraryId === null ? readGlobalIndex() : readPrivateIndex(libraryId)
32
+ export const rtSource = index => {
33
+ const revision = indexDataRevision(index)
34
+ if (!revision) return null
35
+ let source = sources.get(index)
36
+ if (!source || source.revision !== revision) {
37
+ source = { index, revision, count: Object.keys(index.entries).length }
38
+ sources.set(index, source)
39
+ }
40
+ return source
41
+ }
42
+
43
+ function safeSignal(controller, info) {
44
+ const now = Date.now()
45
+ if (controller.lastCode !== info.code || now - controller.lastAt >= 60000) {
46
+ controller.lastCode = info.code
47
+ controller.lastAt = now
48
+ warn(`derived recall ${info.code}; using source index`)
49
+ try { record({ kind: 'system', level: 'warn', message: `derived recall fallback: ${info.code}`, detail: { component: 'rt' } }) } catch {}
50
+ }
51
+ controller.lastFailure = info.code
52
+ }
53
+
54
+ function controllerFor(libraryId) {
55
+ const key = JSON.stringify([rtDirectory(), libraryId])
56
+ let state = controllers.get(key)
57
+ if (state) { controllers.delete(key); controllers.set(key, state); return state }
58
+ state = { libraryId, lastAt: 0, lastCode: null, lastFailure: null }
59
+ state.controller = createRtIndex({
60
+ directory: rtDirectory(), libraryId, mode: 'on',
61
+ logger: { warn() {} }, onSignal: info => safeSignal(state, info),
62
+ })
63
+ controllers.set(key, state)
64
+ while (controllers.size > 32) controllers.delete(controllers.keys().next().value)
65
+ return state
66
+ }
67
+
68
+ function schedule() {
69
+ if (closed || timer || active || !pending.size) return
70
+ timer = setTimeout(() => { timer = null; launchNext() }, 50)
71
+ timer.unref?.()
72
+ }
73
+
74
+ function launchNext() {
75
+ if (closed || active || !pending.size) return
76
+ const [key, job] = pending.entries().next().value
77
+ pending.delete(key)
78
+ let worker
79
+ try {
80
+ worker = new Worker(new URL('./rt-index-worker.js', import.meta.url), {
81
+ workerData: job, env: childEnvironment(),
82
+ resourceLimits: { maxOldGenerationSizeMb: 768 },
83
+ })
84
+ } catch {
85
+ counters.failedBuilds++
86
+ const state = controllerFor(job.libraryId)
87
+ state.nextBuildAt = Date.now() + 30000
88
+ safeSignal(state, { code: 'RT_WORKER_START_FAILED' })
89
+ schedule(); return
90
+ }
91
+ active = worker
92
+ let replied = false
93
+ const finish = result => {
94
+ if (replied) return
95
+ replied = true
96
+ if (closed) return
97
+ if (result?.ok) {
98
+ if (result.skipped) return
99
+ counters.builds++
100
+ const current = rtSource(load(job.libraryId))
101
+ if (current && current.revision !== result.revision) {
102
+ counters.staleBuilds++
103
+ enqueue(job.libraryId, current)
104
+ }
105
+ } else if (result?.code === 'RT_SOURCE_CHANGED') {
106
+ counters.staleBuilds++
107
+ const current = rtSource(load(job.libraryId))
108
+ if (current) enqueue(job.libraryId, current)
109
+ } else {
110
+ counters.failedBuilds++
111
+ const state = controllerFor(job.libraryId)
112
+ state.nextBuildAt = Date.now() + 30000
113
+ safeSignal(state, { code: result?.code || 'RT_BUILD_FAILED' })
114
+ }
115
+ }
116
+ const settle = result => {
117
+ try { finish(result) } catch {
118
+ counters.failedBuilds++
119
+ safeSignal(controllerFor(job.libraryId), { code: 'RT_BUILD_COMPLETION_FAILED' })
120
+ }
121
+ }
122
+ worker.on('message', settle)
123
+ worker.on('error', () => settle({ ok: false, code: 'RT_BUILD_FAILED' }))
124
+ worker.on('exit', () => {
125
+ try { if (!replied) settle({ ok: false }) } finally {
126
+ if (active === worker) active = null
127
+ schedule()
128
+ }
129
+ })
130
+ worker.unref()
131
+ }
132
+
133
+ function enqueue(libraryId, source) {
134
+ if (closed || rtMode() === 'off' || !source) return
135
+ const key = JSON.stringify([rtDirectory(), libraryId])
136
+ if (Date.now() < (controllers.get(key)?.nextBuildAt || 0)) return
137
+ pending.set(key, { directory: rtDirectory(), home: dataDir(), libraryId, revision: source.revision,
138
+ minimum: minEntries(), onlyIfNeeded: source.revision === null })
139
+ while (pending.size > 64) pending.delete(pending.keys().next().value)
140
+ schedule()
141
+ }
142
+
143
+ function listen() {
144
+ if (unsubscribe) return
145
+ closed = false
146
+ unsubscribe = onIndexCommit(({ libraryId, before, after }) => {
147
+ if (rtMode() === 'off') return
148
+ const source = rtSource(after)
149
+ const previousRevision = indexDataRevision(before)
150
+ if (!source || source.revision === previousRevision) return
151
+ const state = controllerFor(libraryId)
152
+ // Do not create a tiny index merely because an unrelated write occurred.
153
+ if (source.count < minEntries()) return
154
+ const changedIds = []
155
+ const removedIds = []
156
+ for (const [id, entry] of Object.entries(after.entries)) {
157
+ if (JSON.stringify(entry) !== JSON.stringify(before.entries[id])) changedIds.push(id)
158
+ }
159
+ for (const id of Object.keys(before.entries)) if (!Object.hasOwn(after.entries, id)) removedIds.push(id)
160
+ const result = state.controller.afterCommit({ source, previousRevision, changedIds, removedIds })
161
+ if (result.ok) counters.deltas++
162
+ else enqueue(libraryId, source)
163
+ })
164
+ }
165
+
166
+ /** Eligibility belongs to the caller and is evaluated before corpus statistics. */
167
+ export function getRtQueryView({ index, libraryId, cacheKey, isVisible }) {
168
+ if (rtMode() === 'off' || !cacheKey || typeof isVisible !== 'function') return null
169
+ const source = rtSource(index)
170
+ if (!source) return null
171
+ listen()
172
+ let scoped = viewsByIndex.get(index)
173
+ if (!scoped) { scoped = new Map(); viewsByIndex.set(index, scoped) }
174
+ const key = JSON.stringify([rtDirectory(), libraryId, indexReadRevision(index), cacheKey, rtMode()])
175
+ const hit = views.get(key)
176
+ const cached = hit?.ref.deref()
177
+ if (cached) {
178
+ const valid = cached.view.validate(source)
179
+ if (valid.ok) { cached.source = source; return cached }
180
+ views.delete(key)
181
+ scoped.delete(key)
182
+ counters.fallbacks++
183
+ enqueue(libraryId, source)
184
+ return { view: null, mode: rtMode(), fallback: valid.code }
185
+ }
186
+ if (source.count < minEntries()) return null
187
+ const state = controllerFor(libraryId)
188
+ state.lastFailure = null
189
+ const validity = state.controller.validate(source)
190
+ if (!validity.ok) {
191
+ counters.fallbacks++
192
+ enqueue(libraryId, source)
193
+ return { view: null, mode: rtMode(), fallback: validity.code }
194
+ }
195
+ const eligible = Object.keys(index.entries).filter(id => isVisible(index.entries[id], id))
196
+ const dates = new Map()
197
+ for (const id of eligible) {
198
+ const date = index.entries[id].absolute_date
199
+ if (date) { if (!dates.has(date)) dates.set(date, []); dates.get(date).push(id) }
200
+ }
201
+ const value = { source, controller: state.controller, mode: rtMode(), dates,
202
+ view: state.controller.createView(source, { visibleIds: eligible }), fallback: null }
203
+ scoped.set(key, value)
204
+ const record = { ref: new WeakRef(value), index: new WeakRef(index), bytes: eligible.length * 192 + dates.size * 96 + 1024 }
205
+ views.set(key, record)
206
+ // Oversized views remain valid for this call, but cannot pin a second corpus.
207
+ if (![...views.keys()].includes(key)) scoped.delete(key)
208
+ return value
209
+ }
210
+
211
+ export function noteRtComparison(expected, actual) {
212
+ counters.shadowQueries++
213
+ const rows = new Map(actual.map(file => [file.name, file.lexical]))
214
+ const equal = expected.length === actual.length && expected.every((file, i) => file.name === actual[i]?.name && rows.get(file.name) === file.lexical)
215
+ if (!equal) {
216
+ counters.shadowMismatches++
217
+ warn('derived recall RT_SHADOW_MISMATCH; source result retained')
218
+ }
219
+ return equal
220
+ }
221
+
222
+ export function readRtBody({ index, libraryId, id }) {
223
+ const body = String(index.entries[id]?.content || '')
224
+ const source = rtSource(index)
225
+ if (!source || rtMode() === 'off' || source.count < minEntries()) return body
226
+ listen()
227
+ const state = controllerFor(libraryId)
228
+ const result = state.controller.readBody(source, id, { visibleIds: [id] })
229
+ if (result.fallback) enqueue(libraryId, source)
230
+ if (rtMode() === 'shadow') {
231
+ counters.shadowBodies++
232
+ if (result.body !== body) {
233
+ counters.shadowBodyMismatches++
234
+ safeSignal(state, { code: 'RT_SHADOW_BODY_MISMATCH' })
235
+ state.controller.invalidate('RT_SHADOW_BODY_MISMATCH')
236
+ enqueue(libraryId, source)
237
+ }
238
+ return body
239
+ }
240
+ return result.body
241
+ }
242
+
243
+ export function rebuildRt(libraryId) {
244
+ const source = rtSource(load(libraryId))
245
+ if (!source) throw new Error('RT_SOURCE_INVALID')
246
+ return controllerFor(libraryId).controller.rebuild(source)
247
+ }
248
+
249
+ export function startRtIndexService() {
250
+ listen()
251
+ const startup = setTimeout(() => {
252
+ if (closed || rtMode() === 'off') return
253
+ try {
254
+ for (const library of listLibrariesAll().slice(0, 64)) {
255
+ enqueue(library.id, { revision: null })
256
+ }
257
+ enqueue(null, { revision: null })
258
+ } catch { safeSignal(controllerFor(null), { code: 'RT_STARTUP_SCAN_FAILED' }) }
259
+ }, 6000)
260
+ startup.unref?.()
261
+ return () => { clearTimeout(startup); return closeRtIndexService() }
262
+ }
263
+
264
+ export async function closeRtIndexService() {
265
+ closed = true
266
+ if (timer) clearTimeout(timer)
267
+ timer = null
268
+ pending.clear()
269
+ unsubscribe?.()
270
+ unsubscribe = null
271
+ views.clear()
272
+ viewsByIndex = new WeakMap()
273
+ controllers.clear()
274
+ const worker = active
275
+ active = null
276
+ if (worker) await worker.terminate()
277
+ }
278
+
279
+ export function rtServiceDiagnostics() {
280
+ return { mode: rtMode(), ...counters, pending: pending.size, active: Boolean(active), views: views.stats() }
281
+ }
282
+
283
+ export { indexLocation }
@@ -0,0 +1,21 @@
1
+ import { parentPort, workerData } from 'node:worker_threads'
2
+ import { createRtIndex } from './rt-index/reader.js'
3
+
4
+ process.env.DSH_MEMU_HOME = workerData.home
5
+ process.env.DSH_MEMU_MEMORY_HOME = workerData.home
6
+ const { readPrivateIndex, readGlobalIndex, indexDataRevision } = await import('./state.js')
7
+ try {
8
+ const index = workerData.libraryId === null ? readGlobalIndex() : readPrivateIndex(workerData.libraryId)
9
+ const revision = indexDataRevision(index)
10
+ if (workerData.revision !== null && revision !== workerData.revision) parentPort.postMessage({ ok: false, code: 'RT_SOURCE_CHANGED' })
11
+ else {
12
+ const controller = createRtIndex({ directory: workerData.directory, libraryId: workerData.libraryId, mode: 'on', logger: { warn() {} } })
13
+ const source = { index, revision, count: Object.keys(index.entries).length }
14
+ if (source.count < workerData.minimum || (workerData.onlyIfNeeded && controller.validate(source).ok)) {
15
+ parentPort.postMessage({ ok: true, skipped: true, revision })
16
+ } else {
17
+ const result = controller.rebuild(source)
18
+ parentPort.postMessage({ ok: result.ok, code: result.code, revision })
19
+ }
20
+ }
21
+ } catch { parentPort.postMessage({ ok: false, code: 'RT_BUILD_FAILED' }) }
@@ -221,6 +221,55 @@ function byTitleIndex(items) {
221
221
  return map
222
222
  }
223
223
 
224
+ const MAX_SCHEDULE_PAGES = 100
225
+
226
+ function incompleteSchedulePage(message, cause) {
227
+ const error = new Error(message, cause ? { cause } : undefined)
228
+ error.paginationIncomplete = true
229
+ return error
230
+ }
231
+
232
+ /** Read the full task set without waking target sessions; never treat a partial page as complete. */
233
+ async function listAllScheduleItems(schedule) {
234
+ if (typeof schedule?.catalog === 'function') {
235
+ const items = await schedule.catalog()
236
+ if (!Array.isArray(items)) throw new Error('schedule.catalog returned a non-array result')
237
+ return { items, source: 'catalog' }
238
+ }
239
+
240
+ const items = []
241
+ const ids = new Set()
242
+ let expectedTotal = null
243
+ let offset = 0
244
+ for (let pageNumber = 0; pageNumber < MAX_SCHEDULE_PAGES; pageNumber += 1) {
245
+ let page
246
+ try {
247
+ page = await schedule.list({ limit: LIST_LIMIT, offset })
248
+ } catch (error) {
249
+ if (offset > 0) throw incompleteSchedulePage(`schedule.list failed at offset ${offset}`, error)
250
+ throw error
251
+ }
252
+ if (!Array.isArray(page?.items)) throw incompleteSchedulePage('schedule.list returned no items array')
253
+ if (!Number.isSafeInteger(page.total) || page.total < 0) throw incompleteSchedulePage('schedule.list returned no valid total')
254
+ if (!Number.isSafeInteger(page.offset) || page.offset !== offset) throw incompleteSchedulePage(`schedule.list did not honor offset ${offset}`)
255
+ if (page.items.length > LIST_LIMIT || (page.shown !== undefined && page.shown !== page.items.length)) {
256
+ throw incompleteSchedulePage(`schedule.list returned an inconsistent page at offset ${offset}`)
257
+ }
258
+ if (expectedTotal === null) expectedTotal = page.total
259
+ else if (page.total !== expectedTotal) throw incompleteSchedulePage('schedule list changed while paging')
260
+ if (page.items.length === 0 && offset < expectedTotal) throw incompleteSchedulePage(`schedule.list stopped before total at offset ${offset}`)
261
+ for (const item of page.items) {
262
+ if (!item || typeof item.id !== 'string' || !item.id) throw incompleteSchedulePage('schedule.list returned an item without an id')
263
+ if (ids.has(item.id)) throw incompleteSchedulePage(`schedule.list repeated task id ${item.id}`)
264
+ ids.add(item.id)
265
+ }
266
+ items.push(...page.items)
267
+ if (items.length === expectedTotal) return { items, source: 'offset' }
268
+ offset += page.items.length
269
+ }
270
+ throw incompleteSchedulePage(`schedule list exceeded ${MAX_SCHEDULE_PAGES} pages`)
271
+ }
272
+
224
273
  /**
225
274
  * One sweep of the salient-date wake pass.
226
275
  *
@@ -327,8 +376,8 @@ export async function runSalientWakePass(ctx, { now = new Date(), log = () => {}
327
376
 
328
377
  let items = []
329
378
  try {
330
- const page = await schedule.list({ limit: LIST_LIMIT })
331
- items = Array.isArray(page?.items) ? page.items : []
379
+ const catalog = await listAllScheduleItems(schedule)
380
+ items = catalog.items
332
381
  } catch (error) {
333
382
  const message = String(error?.message || error)
334
383
  stats.errors += 1
@@ -336,9 +385,11 @@ export async function runSalientWakePass(ctx, { now = new Date(), log = () => {}
336
385
  record({
337
386
  kind: 'wake', level: 'warn', ok: false,
338
387
  message: '日期唤醒:读取定时任务失败:' + message,
339
- detail: { trigger: 'wake', stage: 'list', code: scheduleErrorCode(error) || null },
388
+ detail: { trigger: 'wake', stage: 'list', code: scheduleErrorCode(error) || null, paginationIncomplete: error?.paginationIncomplete === true },
340
389
  })
341
- return stats
390
+ // A partial catalog is not evidence that a task is absent; do not create or
391
+ // clean tasks until the entire Host catalog has been read successfully.
392
+ return error?.paginationIncomplete === true ? { ...stats, paginationIncomplete: true } : stats
342
393
  }
343
394
  const byTitle = byTitleIndex(items)
344
395