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.
- package/AGENTS.md +3 -1
- package/CHANGELOG.md +15 -0
- package/README.md +34 -15
- package/README.zh.md +35 -13
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/preset-mount.js +13 -7
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +38 -7
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +97 -13
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/preset-mount.test.mjs +12 -4
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
- package/tests/worker-lifecycle.test.mjs +2 -1
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { buildCorpus, bm25, tokenize } from '../text-retrieval.js'
|
|
4
|
+
import { createBoundedCache } from '../bounded-cache.js'
|
|
5
|
+
import {
|
|
6
|
+
HEADER_BYTES, HEAD_BYTES, POSTING_BYTES, TERM_BLOCK_ROWS, fileDigest, fileStamp, validateBinary, validateBinaryHeader,
|
|
7
|
+
decodeHead, headFromEntry, invariant, rtError, readRange,
|
|
8
|
+
} from './format.js'
|
|
9
|
+
import {
|
|
10
|
+
indexLocation, sourceInfo, readPublished, readJsonLimited, memoryDocumentText, failureCode,
|
|
11
|
+
validGeneration, validSegmentId,
|
|
12
|
+
} from './manifest.js'
|
|
13
|
+
import { rebuildRtIndex, updateRtIndex } from './builder.js'
|
|
14
|
+
|
|
15
|
+
// Only compact derived data enter this process-wide LRU, never source indexes,
|
|
16
|
+
// entries, bodies or permission predicates. Limits cover all controller instances.
|
|
17
|
+
const snapshots = createBoundedCache({ name: 'rtIndex', maxBytes: 96 * 1024 * 1024, maxEntries: 16, ttlMs: 60000 })
|
|
18
|
+
const termBlocks = createBoundedCache({ name: 'rtTermBlocks', maxBytes: 8 * 1024 * 1024, maxEntries: 512, ttlMs: 60000 })
|
|
19
|
+
const io = { admittedBytes: 0, postingBytes: 0, dictionaryBytes: 0 }
|
|
20
|
+
export const rtIndexCacheStats = () => ({ ...snapshots.stats(), termBlocks: termBlocks.stats(), io: { ...io } })
|
|
21
|
+
export const clearRtIndexCaches = () => { snapshots.clear(); termBlocks.clear() }
|
|
22
|
+
|
|
23
|
+
function termSpan(segment, term) {
|
|
24
|
+
const { anchors, bytes, postings, count } = segment.terms
|
|
25
|
+
let lo = 0
|
|
26
|
+
let hi = anchors.length - 1
|
|
27
|
+
let block = -1
|
|
28
|
+
while (lo <= hi) {
|
|
29
|
+
const mid = (lo + hi) >>> 1
|
|
30
|
+
if (anchors[mid][0] <= term) { block = mid; lo = mid + 1 } else hi = mid - 1
|
|
31
|
+
}
|
|
32
|
+
if (block < 0) return null
|
|
33
|
+
const key = `${segment.directory}:${segment.descriptor.files['terms.bin'].sha256}:${block}`
|
|
34
|
+
let rows = termBlocks.get(key)
|
|
35
|
+
if (!rows) {
|
|
36
|
+
const offset = anchors[block][1]
|
|
37
|
+
const end = anchors[block + 1]?.[1] ?? bytes
|
|
38
|
+
const length = end - offset
|
|
39
|
+
invariant(length > 0 && length <= 16 * 1024 * 1024)
|
|
40
|
+
const data = readRange(path.join(segment.directory, 'terms.bin'), offset, length)
|
|
41
|
+
const file = path.join(segment.directory, 'terms.bin')
|
|
42
|
+
invariant(fileStamp(file) === segment.stamps.find(row => row[0] === file)?.[1], 'RT_CHANGED_DURING_READ')
|
|
43
|
+
io.dictionaryBytes += length
|
|
44
|
+
invariant(data[data.length - 1] === 10)
|
|
45
|
+
try { rows = data.toString('utf8').trimEnd().split('\n').map(row => JSON.parse(row)) } catch { throw rtError('RT_CORRUPT') }
|
|
46
|
+
invariant(rows.length === Math.min(TERM_BLOCK_ROWS, count - block * TERM_BLOCK_ROWS))
|
|
47
|
+
let cursor = anchors[block][2]
|
|
48
|
+
let previous = null
|
|
49
|
+
for (const row of rows) {
|
|
50
|
+
invariant(Array.isArray(row) && row.length === 3)
|
|
51
|
+
invariant(typeof row[0] === 'string' && (previous === null || previous < row[0]))
|
|
52
|
+
invariant(row[1] === cursor && Number.isSafeInteger(row[2]) && row[2] > 0)
|
|
53
|
+
cursor += row[2]
|
|
54
|
+
previous = row[0]
|
|
55
|
+
}
|
|
56
|
+
invariant(rows[0][0] === anchors[block][0] && cursor === (anchors[block + 1]?.[2] ?? postings))
|
|
57
|
+
invariant(block + 1 === anchors.length || previous < anchors[block + 1][0])
|
|
58
|
+
termBlocks.set(key, rows)
|
|
59
|
+
}
|
|
60
|
+
lo = 0
|
|
61
|
+
hi = rows.length - 1
|
|
62
|
+
while (lo <= hi) {
|
|
63
|
+
const mid = (lo + hi) >>> 1
|
|
64
|
+
if (rows[mid][0] === term) return rows[mid].slice(1)
|
|
65
|
+
if (rows[mid][0] < term) lo = mid + 1
|
|
66
|
+
else hi = mid - 1
|
|
67
|
+
}
|
|
68
|
+
return null
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function loadSegment(root, descriptor) {
|
|
72
|
+
const directory = path.join(root, 'segments', descriptor.id)
|
|
73
|
+
invariant(!fs.lstatSync(path.join(root, 'segments')).isSymbolicLink())
|
|
74
|
+
invariant(!fs.lstatSync(directory).isSymbolicLink())
|
|
75
|
+
const stamps = []
|
|
76
|
+
for (const [name, expected] of Object.entries(descriptor.files)) {
|
|
77
|
+
const file = path.join(directory, name)
|
|
78
|
+
if (name.startsWith('bodies/')) invariant(!fs.lstatSync(path.join(directory, 'bodies')).isSymbolicLink())
|
|
79
|
+
const before = fileStamp(file)
|
|
80
|
+
const actual = fileDigest(file)
|
|
81
|
+
io.admittedBytes += actual.size
|
|
82
|
+
invariant(actual.size === expected.size && actual.sha256 === expected.sha256)
|
|
83
|
+
invariant(fileStamp(file) === before, 'RT_CHANGED_DURING_READ')
|
|
84
|
+
stamps.push([file, before])
|
|
85
|
+
}
|
|
86
|
+
const metadata = readJsonLimited(path.join(directory, 'metadata.json'))
|
|
87
|
+
invariant(Array.isArray(metadata?.ids) && metadata.ids.length === descriptor.count)
|
|
88
|
+
const segmentIds = new Set(metadata.ids)
|
|
89
|
+
invariant(metadata.ids.every(id => typeof id === 'string') && segmentIds.size === metadata.ids.length)
|
|
90
|
+
for (const key of ['domains', 'layers', 'statuses', 'visibilities']) {
|
|
91
|
+
invariant(Array.isArray(metadata[key]) && metadata[key].every(value => typeof value === 'string'))
|
|
92
|
+
}
|
|
93
|
+
const heads = fs.readFileSync(path.join(directory, 'heads.bin'))
|
|
94
|
+
validateBinary(heads, 'DMRH', HEAD_BYTES, descriptor.count)
|
|
95
|
+
const totalPostings = validateBinaryHeader(readRange(path.join(directory, 'postings.bin'), 0, HEADER_BYTES), descriptor.files['postings.bin'].size, 'DMRP', POSTING_BYTES)
|
|
96
|
+
const terms = readJsonLimited(path.join(directory, 'terms.json'))
|
|
97
|
+
const removed = readJsonLimited(path.join(directory, 'removed.json'))
|
|
98
|
+
invariant(Array.isArray(removed) && removed.every(id => typeof id === 'string') && new Set(removed).size === removed.length)
|
|
99
|
+
invariant(!removed.some(id => segmentIds.has(id)))
|
|
100
|
+
invariant(Number.isSafeInteger(terms?.count) && terms.count >= 0)
|
|
101
|
+
invariant(terms.bytes === descriptor.files['terms.bin'].size && terms.postings === totalPostings)
|
|
102
|
+
invariant(Array.isArray(terms.anchors) && terms.anchors.length === Math.ceil(terms.count / TERM_BLOCK_ROWS))
|
|
103
|
+
let byteCursor = -1
|
|
104
|
+
let postingCursor = -1
|
|
105
|
+
let previous = null
|
|
106
|
+
for (const row of terms.anchors) {
|
|
107
|
+
invariant(Array.isArray(row) && row.length === 3)
|
|
108
|
+
const [term, offset, cursor] = row
|
|
109
|
+
invariant(typeof term === 'string' && (previous === null || previous < term))
|
|
110
|
+
invariant(Number.isSafeInteger(offset) && offset > byteCursor && offset < terms.bytes)
|
|
111
|
+
invariant(Number.isSafeInteger(cursor) && cursor > postingCursor && cursor < totalPostings)
|
|
112
|
+
if (previous === null) invariant(offset === 0 && cursor === 0)
|
|
113
|
+
byteCursor = offset
|
|
114
|
+
postingCursor = cursor
|
|
115
|
+
previous = term
|
|
116
|
+
}
|
|
117
|
+
if (!terms.count) invariant(terms.bytes === 0 && totalPostings === 0)
|
|
118
|
+
// Validate body ranges before exposing even a head; truncated shards are not
|
|
119
|
+
// interpreted as absent/empty source memories.
|
|
120
|
+
for (let slot = 0; slot < descriptor.count; slot++) {
|
|
121
|
+
const head = decodeHead(heads, metadata, slot)
|
|
122
|
+
const body = descriptor.files[`bodies/${String(head.bodyShard).padStart(8, '0')}.bin`]
|
|
123
|
+
invariant(body && head.bodyOffset + head.bodyLength <= body.size)
|
|
124
|
+
}
|
|
125
|
+
for (const [file, stamp] of stamps) invariant(fileStamp(file) === stamp, 'RT_CHANGED_DURING_READ')
|
|
126
|
+
return { directory, descriptor, metadata, heads, terms, removed, stamps }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** IO boundary. The returned snapshot is read-only by contract and contains no source entries. */
|
|
130
|
+
export function openRtIndex(options, source) {
|
|
131
|
+
const location = indexLocation(options)
|
|
132
|
+
const documentVersion = options.documentVersion ?? 'memory-title-body-tags-captions-v1'
|
|
133
|
+
const { manifest, checksum } = readPublished(location, documentVersion, sourceInfo(source))
|
|
134
|
+
const key = `${location.root}:${checksum}`
|
|
135
|
+
let snapshot = snapshots.get(key)
|
|
136
|
+
if (snapshot) {
|
|
137
|
+
try {
|
|
138
|
+
for (const segment of snapshot.segments) for (const [file, stamp] of segment.stamps) {
|
|
139
|
+
invariant(fileStamp(file) === stamp, 'RT_ARTIFACT_CHANGED')
|
|
140
|
+
}
|
|
141
|
+
return snapshot
|
|
142
|
+
} catch (error) { snapshots.delete(key); throw error }
|
|
143
|
+
}
|
|
144
|
+
// Refuse pathological cold working sets before allocating heads/JSON/maps.
|
|
145
|
+
// An LRU rejection alone would happen too late to protect admission memory.
|
|
146
|
+
const admissionBytes = manifest.segments.reduce((sum, segment) => sum + segment.files['heads.bin'].size
|
|
147
|
+
+ (segment.files['metadata.json'].size + segment.files['terms.json'].size) * 6
|
|
148
|
+
+ segment.files['removed.json'].size * 4 + segment.count * 320, 0)
|
|
149
|
+
invariant(Number.isSafeInteger(admissionBytes) && admissionBytes <= 128 * 1024 * 1024, 'RT_READ_LIMIT')
|
|
150
|
+
const segments = manifest.segments.map(segment => loadSegment(location.root, segment))
|
|
151
|
+
const active = new Map()
|
|
152
|
+
for (const segment of segments) {
|
|
153
|
+
for (const id of segment.removed) active.delete(id)
|
|
154
|
+
segment.metadata.ids.forEach((id, slot) => {
|
|
155
|
+
active.set(id, { segment, slot, len: segment.heads.readUInt32LE(HEADER_BYTES + slot * HEAD_BYTES) })
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
invariant(active.size === manifest.source.count, 'RT_COUNT_MISMATCH')
|
|
159
|
+
snapshot = { manifest, segments, active }
|
|
160
|
+
snapshots.set(key, snapshot)
|
|
161
|
+
return snapshot
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function visibleSelection(source, { visibleIds, isVisible } = {}) {
|
|
165
|
+
invariant(visibleIds !== undefined || typeof isVisible === 'function', 'RT_VISIBILITY_REQUIRED')
|
|
166
|
+
invariant(isVisible === undefined || typeof isVisible === 'function', 'RT_VISIBILITY_INVALID')
|
|
167
|
+
invariant(visibleIds === undefined || (typeof visibleIds !== 'string' && typeof visibleIds?.[Symbol.iterator] === 'function'), 'RT_VISIBILITY_INVALID')
|
|
168
|
+
const ids = []
|
|
169
|
+
const seen = new Set()
|
|
170
|
+
const entries = source.index.entries
|
|
171
|
+
const input = visibleIds ?? Object.keys(entries)
|
|
172
|
+
for (const id of input) {
|
|
173
|
+
invariant(typeof id === 'string', 'RT_VISIBILITY_INVALID')
|
|
174
|
+
if (seen.has(id)) continue
|
|
175
|
+
seen.add(id)
|
|
176
|
+
if (!Object.hasOwn(entries, id)) continue
|
|
177
|
+
if (!isVisible || isVisible(entries[id], id)) ids.push(id)
|
|
178
|
+
}
|
|
179
|
+
return ids
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function normalizeTokens(tokens) {
|
|
183
|
+
const result = typeof tokens === 'string' ? tokenize(tokens) : tokens
|
|
184
|
+
invariant(Array.isArray(result) && result.every(token => typeof token === 'string'), 'RT_QUERY_INVALID')
|
|
185
|
+
return result
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function applyLimit(rows, limit = Infinity, offset = 0) {
|
|
189
|
+
invariant((limit === Infinity || (Number.isSafeInteger(limit) && limit >= 0)) && Number.isSafeInteger(offset) && offset >= 0, 'RT_QUERY_INVALID')
|
|
190
|
+
return rows.slice(offset, limit === Infinity ? undefined : offset + limit)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function sortHits(hits, entries) {
|
|
194
|
+
return hits.sort((a, b) => b.score - a.score
|
|
195
|
+
|| String(entries[b.id]?.updatedAt || entries[b.id]?.createdAt || '').localeCompare(String(entries[a.id]?.updatedAt || entries[a.id]?.createdAt || '')))
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const HEAD_FIELDS = new Set(['id', 'tokenCount', 'bodyShard', 'bodyOffset', 'bodyLength', 'attachmentMissing', 'layer', 'status', 'visibility', 'domain', 'createdAt', 'updatedAt', 'strengthBase', 'strengthAt'])
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Pure in-memory query view. isVisible(entry, id) runs once, before N/df/avgdl.
|
|
202
|
+
* snapshot is optional: without it the same API is the source-truth oracle.
|
|
203
|
+
* Views are caller-scoped and must not survive a source revision or permission change.
|
|
204
|
+
*/
|
|
205
|
+
export function createQueryView(source, { snapshot = null, documentText = memoryDocumentText, ...visibility } = {}) {
|
|
206
|
+
const info = sourceInfo(source)
|
|
207
|
+
if (snapshot) {
|
|
208
|
+
invariant(snapshot.manifest.source.revision === info.revision, 'RT_REVISION_MISMATCH')
|
|
209
|
+
invariant(snapshot.manifest.source.fingerprint === info.fingerprint, 'RT_FINGERPRINT_MISMATCH')
|
|
210
|
+
invariant(snapshot.manifest.source.count === info.count, 'RT_COUNT_MISMATCH')
|
|
211
|
+
}
|
|
212
|
+
const ids = visibleSelection(source, visibility)
|
|
213
|
+
const order = new Map(ids.map((id, index) => [id, index]))
|
|
214
|
+
const entries = source.index.entries
|
|
215
|
+
const selected = new Map()
|
|
216
|
+
let totalLen = 0
|
|
217
|
+
if (snapshot) for (const id of ids) {
|
|
218
|
+
const ref = snapshot.active.get(id)
|
|
219
|
+
invariant(ref, 'RT_SOURCE_ID_MISMATCH')
|
|
220
|
+
selected.set(id, ref)
|
|
221
|
+
totalLen += ref.len
|
|
222
|
+
}
|
|
223
|
+
function postingsFor(queryTokens, scoreOnly = false) {
|
|
224
|
+
const df = new Map()
|
|
225
|
+
const docs = new Map()
|
|
226
|
+
const union = scoreOnly ? new Uint8Array(Math.ceil(ids.length / 8)) : null
|
|
227
|
+
let candidateCount = 0
|
|
228
|
+
let visited = 0
|
|
229
|
+
const touched = new Set()
|
|
230
|
+
for (const term of new Set(queryTokens)) {
|
|
231
|
+
const spans = []
|
|
232
|
+
let upperBound = 0
|
|
233
|
+
for (const segment of snapshot.segments) {
|
|
234
|
+
const span = termSpan(segment, term)
|
|
235
|
+
if (!span) continue
|
|
236
|
+
touched.add(segment)
|
|
237
|
+
spans.push({ segment, offset: span[0], count: span[1] })
|
|
238
|
+
upperBound += span[1]
|
|
239
|
+
}
|
|
240
|
+
// Use the shared scorer as the gate oracle; no duplicated df thresholds
|
|
241
|
+
// or query-term policy. Raw df only decides whether to count first.
|
|
242
|
+
const canScore = frequency => bm25([term], { len: 1, tf: new Map([[term, 1]]) },
|
|
243
|
+
{ size: ids.length, avgdl: ids.length ? totalLen / ids.length : 0, df: new Map([[term, frequency]]) }) > 0
|
|
244
|
+
const countFirst = scoreOnly && upperBound > 0 && !canScore(upperBound)
|
|
245
|
+
function scan(materialize, countUnion) {
|
|
246
|
+
let frequency = 0
|
|
247
|
+
for (const { segment, offset, count } of spans) {
|
|
248
|
+
// No posting buffers or file descriptors survive this bounded scan.
|
|
249
|
+
let previousSlot = -1
|
|
250
|
+
for (let start = 0; start < count; start += 8192) {
|
|
251
|
+
const length = Math.min(8192, count - start) * POSTING_BYTES
|
|
252
|
+
const postings = readRange(path.join(segment.directory, 'postings.bin'), HEADER_BYTES + (offset + start) * POSTING_BYTES, length)
|
|
253
|
+
io.postingBytes += length
|
|
254
|
+
for (let at = 0; at < length; at += POSTING_BYTES) {
|
|
255
|
+
visited++
|
|
256
|
+
const slot = postings.readUInt32LE(at)
|
|
257
|
+
const tf = postings.readUInt16LE(at + 4)
|
|
258
|
+
invariant(slot > previousSlot && slot < segment.descriptor.count && tf > 0)
|
|
259
|
+
previousSlot = slot
|
|
260
|
+
const id = segment.metadata.ids[slot]
|
|
261
|
+
const ref = selected.get(id)
|
|
262
|
+
if (!ref || ref.segment !== segment || ref.slot !== slot) continue
|
|
263
|
+
frequency++
|
|
264
|
+
if (scoreOnly && countUnion) {
|
|
265
|
+
const position = order.get(id)
|
|
266
|
+
const byte = position >>> 3
|
|
267
|
+
const mask = 1 << (position & 7)
|
|
268
|
+
if (!(union[byte] & mask)) { union[byte] |= mask; candidateCount++ }
|
|
269
|
+
}
|
|
270
|
+
if (!materialize) continue
|
|
271
|
+
let doc = docs.get(id)
|
|
272
|
+
if (!doc) {
|
|
273
|
+
doc = { id, len: ref.len, tf: new Map(), shared: 0, order: order.get(id) }
|
|
274
|
+
docs.set(id, doc)
|
|
275
|
+
}
|
|
276
|
+
doc.tf.set(term, tf)
|
|
277
|
+
doc.shared++
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return frequency
|
|
282
|
+
}
|
|
283
|
+
const frequency = scan(!countFirst, true)
|
|
284
|
+
if (frequency) df.set(term, frequency)
|
|
285
|
+
// Permissions and superseded segments can lower df beneath the gate.
|
|
286
|
+
// Re-read only those potentially gated terms that actually contribute.
|
|
287
|
+
if (countFirst && frequency && canScore(frequency)) invariant(scan(true, false) === frequency, 'RT_CHANGED_DURING_READ')
|
|
288
|
+
}
|
|
289
|
+
for (const segment of touched) for (const [file, stamp] of segment.stamps) {
|
|
290
|
+
if (file.endsWith('postings.bin') || file.endsWith('terms.bin')) invariant(fileStamp(file) === stamp, 'RT_CHANGED_DURING_READ')
|
|
291
|
+
}
|
|
292
|
+
return { corpus: { size: ids.length, avgdl: ids.length ? totalLen / ids.length : 0, df }, totalLen, docs, visited,
|
|
293
|
+
...(scoreOnly ? { candidateCount } : {}) }
|
|
294
|
+
}
|
|
295
|
+
function queryPostings(tokens) {
|
|
296
|
+
const queryTokens = normalizeTokens(tokens)
|
|
297
|
+
if (snapshot) return postingsFor(queryTokens)
|
|
298
|
+
const wanted = new Set(queryTokens)
|
|
299
|
+
const df = new Map()
|
|
300
|
+
const docs = new Map()
|
|
301
|
+
let length = 0
|
|
302
|
+
// A source fallback never materializes or retains a second whole corpus.
|
|
303
|
+
// Tokenize one source document at a time; keep only requested-term candidates.
|
|
304
|
+
for (const id of ids) {
|
|
305
|
+
const doc = buildCorpus([{ id, title: entries[id].title || '', content: documentText(entries[id]) }]).docs.get(id)
|
|
306
|
+
length += doc.len
|
|
307
|
+
const tf = new Map()
|
|
308
|
+
for (const term of wanted) if (doc.tf.has(term)) {
|
|
309
|
+
tf.set(term, doc.tf.get(term))
|
|
310
|
+
df.set(term, (df.get(term) || 0) + 1)
|
|
311
|
+
}
|
|
312
|
+
if (tf.size) docs.set(id, { id, len: doc.len, tf, order: order.get(id) })
|
|
313
|
+
}
|
|
314
|
+
return { corpus: { size: ids.length, avgdl: ids.length ? length / ids.length : 0, df }, totalLen: length, docs, visited: 0 }
|
|
315
|
+
}
|
|
316
|
+
function candidates(tokens, { dfCap = Infinity, minShared = 1 } = {}) {
|
|
317
|
+
const queryTokens = normalizeTokens(tokens)
|
|
318
|
+
invariant(typeof dfCap === 'number' && dfCap >= 0 && Number.isSafeInteger(minShared) && minShared >= 1, 'RT_QUERY_INVALID')
|
|
319
|
+
const data = queryPostings(queryTokens)
|
|
320
|
+
const wanted = new Set(queryTokens.filter(term => (data.corpus.df.get(term) || 0) <= dfCap))
|
|
321
|
+
const matches = []
|
|
322
|
+
for (const [id, doc] of data.docs) {
|
|
323
|
+
let shared = 0
|
|
324
|
+
for (const term of wanted) if (doc.tf.has(term)) shared++
|
|
325
|
+
if (shared >= minShared) matches.push(id)
|
|
326
|
+
}
|
|
327
|
+
return matches.sort((a, b) => order.get(a) - order.get(b))
|
|
328
|
+
}
|
|
329
|
+
function score(tokens, { limit = Infinity } = {}) {
|
|
330
|
+
const queryTokens = normalizeTokens(tokens)
|
|
331
|
+
const data = snapshot ? postingsFor(queryTokens, true) : queryPostings(queryTokens)
|
|
332
|
+
// Count every matching posting; only the shared BM25 gate may avoid maps.
|
|
333
|
+
// Iterate source selection order so complete score/date ties retain parity.
|
|
334
|
+
const hits = []
|
|
335
|
+
for (const [id, doc] of data.docs) {
|
|
336
|
+
const value = bm25(queryTokens, doc, data.corpus)
|
|
337
|
+
if (value > 0) hits.push({ id, score: value })
|
|
338
|
+
}
|
|
339
|
+
// Posting order differs from source order after incremental replacements.
|
|
340
|
+
// Stable sorting below must start in the source's original tie order.
|
|
341
|
+
hits.sort((a, b) => order.get(a.id) - order.get(b.id))
|
|
342
|
+
const df = new Map()
|
|
343
|
+
for (const token of new Set(queryTokens)) if (data.corpus.df.has(token)) df.set(token, data.corpus.df.get(token))
|
|
344
|
+
return {
|
|
345
|
+
hits: applyLimit(sortHits(hits, entries), limit),
|
|
346
|
+
corpus: { size: data.corpus.size, avgdl: data.corpus.avgdl, df },
|
|
347
|
+
stats: { candidates: data.candidateCount ?? data.docs.size, materialized: data.docs.size, postingsVisited: data.visited },
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function getSortedHeads({ sortBy = 'updatedAt', descending = true, offset = 0, limit = Infinity, fields = ['id', 'updatedAt', 'createdAt'] } = {}) {
|
|
351
|
+
invariant(['updatedAt', 'createdAt', 'id', 'strengthBase'].includes(sortBy) && typeof descending === 'boolean', 'RT_QUERY_INVALID')
|
|
352
|
+
invariant(Array.isArray(fields) && fields.every(field => HEAD_FIELDS.has(field)), 'RT_QUERY_INVALID')
|
|
353
|
+
const rows = ids.map(id => {
|
|
354
|
+
let value = id
|
|
355
|
+
if (sortBy !== 'id') {
|
|
356
|
+
if (snapshot) {
|
|
357
|
+
const ref = selected.get(id)
|
|
358
|
+
const offset = HEADER_BYTES + ref.slot * HEAD_BYTES
|
|
359
|
+
value = ref.segment.heads.readDoubleLE(offset + (sortBy === 'updatedAt' ? 40 : sortBy === 'createdAt' ? 32 : 48))
|
|
360
|
+
if (sortBy === 'updatedAt' && !value) value = ref.segment.heads.readDoubleLE(offset + 32)
|
|
361
|
+
} else {
|
|
362
|
+
value = sortBy === 'strengthBase' ? Number(entries[id].strengthBase) || 0
|
|
363
|
+
: Date.parse(sortBy === 'updatedAt' ? entries[id].updatedAt || entries[id].createdAt : entries[id].createdAt) || 0
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return { id, value }
|
|
367
|
+
})
|
|
368
|
+
rows.sort((a, b) => {
|
|
369
|
+
const av = a.value
|
|
370
|
+
const bv = b.value
|
|
371
|
+
const order = typeof av === 'string' ? av.localeCompare(bv) : av - bv
|
|
372
|
+
return (descending ? -order : order) || a.id.localeCompare(b.id)
|
|
373
|
+
})
|
|
374
|
+
return {
|
|
375
|
+
heads: applyLimit(rows, limit, offset).map(({ id }) => {
|
|
376
|
+
const ref = selected.get(id)
|
|
377
|
+
const head = snapshot ? decodeHead(ref.segment.heads, ref.segment.metadata, ref.slot) : headFromEntry(id, entries[id])
|
|
378
|
+
if (!snapshot) {
|
|
379
|
+
if (fields.includes('tokenCount')) head.tokenCount = buildCorpus([{ id, title: entries[id].title || '', content: documentText(entries[id]) }]).docs.get(id).len
|
|
380
|
+
for (const field of ['bodyShard', 'bodyOffset', 'bodyLength']) head[field] = null
|
|
381
|
+
}
|
|
382
|
+
return Object.fromEntries(fields.map(field => [field, head[field]]))
|
|
383
|
+
}),
|
|
384
|
+
total: rows.length, snapshotRevision: info.revision,
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return { ids: ids.slice(), size: ids.length, orderOf: id => order.get(id), backend: snapshot ? 'rt' : 'source', score, queryPostings, candidates, getSortedHeads }
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Optional blocking parameters never affect the default recall union. */
|
|
391
|
+
export function candidatesFromPostings(view, tokens, options = {}) {
|
|
392
|
+
return view.candidates(tokens, options)
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function compareScores(expected, actual) {
|
|
396
|
+
const oldIds = new Set(expected.hits.map(hit => hit.id))
|
|
397
|
+
const newIds = new Set(actual.hits.map(hit => hit.id))
|
|
398
|
+
let shared = 0
|
|
399
|
+
let scoreDifferences = 0
|
|
400
|
+
const byId = new Map(actual.hits.map(hit => [hit.id, hit.score]))
|
|
401
|
+
for (const hit of expected.hits) {
|
|
402
|
+
if (newIds.has(hit.id)) shared++
|
|
403
|
+
if (byId.has(hit.id) && byId.get(hit.id) !== hit.score) scoreDifferences++
|
|
404
|
+
}
|
|
405
|
+
const union = oldIds.size + newIds.size - shared
|
|
406
|
+
return {
|
|
407
|
+
expected: oldIds.size, actual: newIds.size, missing: oldIds.size - shared, extra: newIds.size - shared,
|
|
408
|
+
agreement: union ? shared / union : 1, scoreDifferences,
|
|
409
|
+
orderEqual: expected.hits.length === actual.hits.length && expected.hits.every((hit, index) => hit.id === actual.hits[index].id),
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export function createRtIndex(options) {
|
|
414
|
+
const location = indexLocation(options)
|
|
415
|
+
const mode = options.mode ?? process.env.DSH_MEMU_RT_INDEX ?? 'shadow'
|
|
416
|
+
invariant(['off', 'shadow', 'on'].includes(mode), 'RT_MODE_INVALID')
|
|
417
|
+
const logger = options.logger ?? console
|
|
418
|
+
const documentText = options.documentText ?? memoryDocumentText
|
|
419
|
+
const counters = { queries: 0, validations: 0, fallbacks: 0, builds: 0, deltas: 0, shadowQueries: 0, shadowMismatches: 0, lastError: null }
|
|
420
|
+
let quarantinedGeneration = null
|
|
421
|
+
const warn = code => {
|
|
422
|
+
try { logger.warn?.(`[rt-index] ${code}; source fallback required`) } catch { console.warn(`[rt-index] ${code}`) }
|
|
423
|
+
}
|
|
424
|
+
function signal(error, operation) {
|
|
425
|
+
const code = failureCode(error)
|
|
426
|
+
counters.lastError = code
|
|
427
|
+
warn(code)
|
|
428
|
+
try { options.onSignal?.({ code, operation, fallback: true, rebuildRequired: true, action: 'schedule-rebuild' }) } catch { warn('RT_SIGNAL_FAILED') }
|
|
429
|
+
return code
|
|
430
|
+
}
|
|
431
|
+
function checkedSnapshot(source) {
|
|
432
|
+
counters.validations++
|
|
433
|
+
const snapshot = openRtIndex(options, source)
|
|
434
|
+
invariant(quarantinedGeneration !== snapshot.manifest.generation, 'RT_QUARANTINED')
|
|
435
|
+
return snapshot
|
|
436
|
+
}
|
|
437
|
+
function validate(source) {
|
|
438
|
+
if (mode === 'off') return { ok: false, disabled: true }
|
|
439
|
+
try {
|
|
440
|
+
const snapshot = checkedSnapshot(source)
|
|
441
|
+
return { ok: true, generation: snapshot.manifest.generation, revision: snapshot.manifest.source.revision }
|
|
442
|
+
} catch (error) { return { ok: false, code: signal(error, 'validate') } }
|
|
443
|
+
}
|
|
444
|
+
function invalidate(code = 'RT_INVALIDATED') {
|
|
445
|
+
for (const key of [...snapshots.keys()]) if (key.startsWith(`${location.root}:`)) snapshots.delete(key)
|
|
446
|
+
for (const key of [...termBlocks.keys()]) if (key.startsWith(`${location.root}${path.sep}`)) termBlocks.delete(key)
|
|
447
|
+
// Logical quarantine only: no source or derived directory is moved/deleted.
|
|
448
|
+
try { quarantinedGeneration = readPublished(location, options.documentVersion ?? 'memory-title-body-tags-captions-v1').manifest.generation } catch { quarantinedGeneration = null }
|
|
449
|
+
return { ok: true, code: signal(rtError(code), 'invalidate'), quarantined: quarantinedGeneration !== null }
|
|
450
|
+
}
|
|
451
|
+
function createView(source, visibility) {
|
|
452
|
+
counters.queries++
|
|
453
|
+
sourceInfo(source)
|
|
454
|
+
// Freeze the caller's eligibility decision once; shadow/fallback reuse IDs
|
|
455
|
+
// without re-running predicates or constructing rich file objects.
|
|
456
|
+
let currentSource = source
|
|
457
|
+
let ids = visibleSelection(source, visibility)
|
|
458
|
+
let order = new Map(ids.map((id, position) => [id, position]))
|
|
459
|
+
const selected = () => ({ visibleIds: ids, documentText })
|
|
460
|
+
// The bounded process cache owns binary snapshots. Cached controller views
|
|
461
|
+
// retain only WeakRefs, so evicting a snapshot can actually release it.
|
|
462
|
+
let derivedRef = null
|
|
463
|
+
let snapshotRef = null
|
|
464
|
+
let fallback = null
|
|
465
|
+
let oracle = null
|
|
466
|
+
const sourceView = () => oracle ??= createQueryView(currentSource, selected())
|
|
467
|
+
function validateView(freshSource = currentSource) {
|
|
468
|
+
const before = sourceInfo(currentSource)
|
|
469
|
+
const after = sourceInfo(freshSource)
|
|
470
|
+
if (freshSource !== currentSource) {
|
|
471
|
+
currentSource = freshSource
|
|
472
|
+
oracle = null
|
|
473
|
+
derivedRef = null
|
|
474
|
+
if (before.revision !== after.revision || before.fingerprint !== after.fingerprint || before.count !== after.count) {
|
|
475
|
+
ids = visibleSelection(freshSource, visibility)
|
|
476
|
+
order = new Map(ids.map((id, position) => [id, position]))
|
|
477
|
+
snapshotRef = null
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (mode === 'off') return { ok: false, disabled: true, backend: 'source' }
|
|
481
|
+
try {
|
|
482
|
+
const snapshot = checkedSnapshot(currentSource)
|
|
483
|
+
if (!derivedRef?.deref() || snapshotRef?.deref() !== snapshot) {
|
|
484
|
+
snapshotRef = new WeakRef(snapshot)
|
|
485
|
+
derivedRef = new WeakRef(createQueryView(currentSource, { ...selected(), snapshot }))
|
|
486
|
+
}
|
|
487
|
+
fallback = null
|
|
488
|
+
return { ok: true, backend: mode === 'on' ? 'rt' : 'source', generation: snapshot.manifest.generation }
|
|
489
|
+
} catch (error) {
|
|
490
|
+
derivedRef = null
|
|
491
|
+
snapshotRef = null
|
|
492
|
+
fallback = signal(error, 'validate-view')
|
|
493
|
+
counters.fallbacks++
|
|
494
|
+
return { ok: false, backend: 'source', code: fallback }
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return {
|
|
498
|
+
get ids() { return ids.slice() },
|
|
499
|
+
get size() { return ids.length },
|
|
500
|
+
orderOf: id => order.get(id),
|
|
501
|
+
get backend() { return mode === 'on' && derivedRef?.deref() ? 'rt' : 'source' },
|
|
502
|
+
get fallback() { return fallback },
|
|
503
|
+
mode,
|
|
504
|
+
validate: validateView,
|
|
505
|
+
candidates(tokens, settings) {
|
|
506
|
+
validateView()
|
|
507
|
+
const derived = derivedRef?.deref()
|
|
508
|
+
if (mode === 'on' && derived) try { return derived.candidates(tokens, settings) } catch (error) {
|
|
509
|
+
fallback = signal(error, 'candidates')
|
|
510
|
+
counters.fallbacks++
|
|
511
|
+
derivedRef = null
|
|
512
|
+
}
|
|
513
|
+
return sourceView().candidates(tokens, settings)
|
|
514
|
+
},
|
|
515
|
+
getSortedHeads(settings) {
|
|
516
|
+
validateView()
|
|
517
|
+
const derived = derivedRef?.deref()
|
|
518
|
+
return (mode === 'on' && derived ? derived : sourceView()).getSortedHeads(settings)
|
|
519
|
+
},
|
|
520
|
+
queryPostings(tokens) {
|
|
521
|
+
validateView()
|
|
522
|
+
const derived = derivedRef?.deref()
|
|
523
|
+
let actual = null
|
|
524
|
+
if (derived) try { actual = derived.queryPostings(tokens) } catch (error) {
|
|
525
|
+
fallback = signal(error, 'query-postings')
|
|
526
|
+
counters.fallbacks++
|
|
527
|
+
derivedRef = null
|
|
528
|
+
}
|
|
529
|
+
const data = mode === 'on' && actual ? actual : sourceView().queryPostings(tokens)
|
|
530
|
+
return { ...data, backend: mode === 'on' && actual ? 'rt' : 'source', mode, fallback, shadow: mode === 'shadow' ? actual : null }
|
|
531
|
+
},
|
|
532
|
+
score(tokens, settings) {
|
|
533
|
+
validateView()
|
|
534
|
+
const derived = derivedRef?.deref()
|
|
535
|
+
let actual = null
|
|
536
|
+
if (derived) {
|
|
537
|
+
try { actual = derived.score(tokens, settings) } catch (error) {
|
|
538
|
+
fallback = signal(error, 'score')
|
|
539
|
+
counters.fallbacks++
|
|
540
|
+
derivedRef = null
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
const result = mode === 'on' && actual ? actual : sourceView().score(tokens, settings)
|
|
544
|
+
let comparison = null
|
|
545
|
+
if (mode === 'shadow' && actual) {
|
|
546
|
+
counters.shadowQueries++
|
|
547
|
+
comparison = compareScores(result, actual)
|
|
548
|
+
if (comparison.agreement !== 1 || comparison.scoreDifferences || !comparison.orderEqual) {
|
|
549
|
+
counters.shadowMismatches++
|
|
550
|
+
signal(rtError('RT_SHADOW_MISMATCH'), 'shadow')
|
|
551
|
+
}
|
|
552
|
+
try { options.onCompare?.({ ...comparison }) } catch { warn('RT_COMPARE_FAILED') }
|
|
553
|
+
}
|
|
554
|
+
return { ...result, mode, backend: mode === 'on' && actual ? 'rt' : 'source', fallback, comparison }
|
|
555
|
+
},
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return {
|
|
559
|
+
mode,
|
|
560
|
+
createView,
|
|
561
|
+
validate,
|
|
562
|
+
invalidate,
|
|
563
|
+
quarantine: invalidate,
|
|
564
|
+
compareFinal(expectedHits, actualHits) {
|
|
565
|
+
const comparison = compareScores({ hits: expectedHits }, { hits: actualHits })
|
|
566
|
+
counters.shadowQueries++
|
|
567
|
+
if (comparison.agreement !== 1 || comparison.scoreDifferences || !comparison.orderEqual) {
|
|
568
|
+
counters.shadowMismatches++
|
|
569
|
+
signal(rtError('RT_SHADOW_MISMATCH'), 'shadow-final')
|
|
570
|
+
}
|
|
571
|
+
try { options.onCompare?.({ ...comparison }) } catch { warn('RT_COMPARE_FAILED') }
|
|
572
|
+
return comparison
|
|
573
|
+
},
|
|
574
|
+
open(source) {
|
|
575
|
+
if (mode === 'off') return { ok: false, disabled: true, snapshot: null, validate: () => validate(source) }
|
|
576
|
+
try { return { ok: true, snapshot: checkedSnapshot(source), validate: () => validate(source) } } catch (error) {
|
|
577
|
+
return { ok: false, snapshot: null, code: signal(error, 'open'), validate: () => validate(source) }
|
|
578
|
+
}
|
|
579
|
+
},
|
|
580
|
+
search: (source, query, settings = {}) => createView(source, settings).score(query, settings),
|
|
581
|
+
getSortedHeads(source, settings = {}) {
|
|
582
|
+
const view = createView(source, settings)
|
|
583
|
+
return { ...view.getSortedHeads(settings), backend: view.backend, fallback: view.fallback }
|
|
584
|
+
},
|
|
585
|
+
readBody(source, id, visibility) {
|
|
586
|
+
// This is a body lookup: callers should pass visibleIds:[id] + isVisible,
|
|
587
|
+
// or a prequalified visible set. Denied IDs never reach derived IO.
|
|
588
|
+
const ids = visibleSelection(source, visibility)
|
|
589
|
+
if (!ids.includes(id)) return { body: null, backend: 'source', fallback: null }
|
|
590
|
+
if (mode !== 'off') try {
|
|
591
|
+
const snapshot = checkedSnapshot(source)
|
|
592
|
+
const ref = snapshot.active.get(id)
|
|
593
|
+
invariant(ref, 'RT_SOURCE_ID_MISMATCH')
|
|
594
|
+
const head = decodeHead(ref.segment.heads, ref.segment.metadata, ref.slot)
|
|
595
|
+
const file = path.join(ref.segment.directory, 'bodies', `${String(head.bodyShard).padStart(8, '0')}.bin`)
|
|
596
|
+
// File checksums are revalidated at the IO boundary above; only this
|
|
597
|
+
// body's range is allocated, and no body cache is retained.
|
|
598
|
+
const bytes = Buffer.alloc(head.bodyLength)
|
|
599
|
+
const before = fileStamp(file)
|
|
600
|
+
invariant(before === ref.segment.stamps.find(row => row[0] === file)?.[1], 'RT_CHANGED_DURING_READ')
|
|
601
|
+
const fd = fs.openSync(file, 'r')
|
|
602
|
+
try {
|
|
603
|
+
let read = 0
|
|
604
|
+
while (read < bytes.length) {
|
|
605
|
+
const got = fs.readSync(fd, bytes, read, bytes.length - read, head.bodyOffset + read)
|
|
606
|
+
invariant(got > 0)
|
|
607
|
+
read += got
|
|
608
|
+
}
|
|
609
|
+
} finally { fs.closeSync(fd) }
|
|
610
|
+
invariant(fileStamp(file) === before, 'RT_CHANGED_DURING_READ')
|
|
611
|
+
if (mode === 'on') return { body: bytes.toString('utf8'), backend: 'rt', fallback: null }
|
|
612
|
+
invariant(bytes.toString('utf8') === String(source.index.entries[id].content || ''), 'RT_SHADOW_MISMATCH')
|
|
613
|
+
} catch (error) {
|
|
614
|
+
counters.fallbacks++
|
|
615
|
+
return { body: String(source.index.entries[id].content || ''), backend: 'source', fallback: signal(error, 'body') }
|
|
616
|
+
}
|
|
617
|
+
return { body: String(source.index.entries[id].content || ''), backend: 'source', fallback: null }
|
|
618
|
+
},
|
|
619
|
+
rebuild(source) {
|
|
620
|
+
if (mode === 'off') return { ok: false, disabled: true }
|
|
621
|
+
try { const result = rebuildRtIndex(options, source); counters.builds++; quarantinedGeneration = null; return result } catch (error) {
|
|
622
|
+
return { ok: false, code: signal(error, 'rebuild'), needsRebuild: true }
|
|
623
|
+
}
|
|
624
|
+
},
|
|
625
|
+
afterCommit(delta) {
|
|
626
|
+
if (mode === 'off') return { ok: false, disabled: true }
|
|
627
|
+
try { const result = updateRtIndex(options, delta); counters.deltas++; return result } catch (error) {
|
|
628
|
+
return { ok: false, code: signal(error, 'afterCommit'), needsRebuild: true }
|
|
629
|
+
}
|
|
630
|
+
},
|
|
631
|
+
listArtifacts: () => listArtifacts(options),
|
|
632
|
+
diagnostics: () => ({ ...counters, cache: rtIndexCacheStats() }),
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** Read-only retention inventory. referenced:null means deletion cannot be inferred. */
|
|
637
|
+
export function listArtifacts(options) {
|
|
638
|
+
const location = indexLocation(options)
|
|
639
|
+
if (!fs.existsSync(location.root)) return { identity: location.identity, root: location.root, state: 'missing', artifacts: [] }
|
|
640
|
+
const rootStat = fs.lstatSync(location.root)
|
|
641
|
+
if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) return { identity: location.identity, root: location.root, state: 'RT_UNSAFE_PATH', artifacts: [] }
|
|
642
|
+
let manifest = null
|
|
643
|
+
let state = 'ready'
|
|
644
|
+
try { manifest = readPublished(location, options.documentVersion ?? 'memory-title-body-tags-captions-v1').manifest } catch (error) { state = failureCode(error) }
|
|
645
|
+
const activeSegments = new Set(manifest?.segments.map(segment => segment.id))
|
|
646
|
+
const artifacts = []
|
|
647
|
+
const append = (kind, file, name, referenced) => {
|
|
648
|
+
let stat
|
|
649
|
+
try { stat = fs.lstatSync(file) } catch (error) { if (error.code === 'ENOENT') return; throw error }
|
|
650
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) return
|
|
651
|
+
artifacts.push({ kind, name, path: file, referenced, mtimeMs: stat.mtimeMs })
|
|
652
|
+
}
|
|
653
|
+
for (const name of fs.readdirSync(location.root)) if (validGeneration(name)) {
|
|
654
|
+
append('generation', path.join(location.root, name), name, manifest ? manifest.generation === name : null)
|
|
655
|
+
}
|
|
656
|
+
const segmentRoot = path.join(location.root, 'segments')
|
|
657
|
+
if (fs.existsSync(segmentRoot)) {
|
|
658
|
+
const stat = fs.lstatSync(segmentRoot)
|
|
659
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
|
660
|
+
state = 'RT_UNSAFE_PATH'
|
|
661
|
+
for (const artifact of artifacts) artifact.referenced = null
|
|
662
|
+
} else for (const name of fs.readdirSync(segmentRoot)) if (validSegmentId(name)) {
|
|
663
|
+
append('segment', path.join(segmentRoot, name), name, manifest ? activeSegments.has(name) : null)
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return {
|
|
667
|
+
identity: location.identity, root: location.root, state,
|
|
668
|
+
generation: manifest?.generation ?? null, source: manifest ? { ...manifest.source } : null,
|
|
669
|
+
artifacts,
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
export { memoryDocumentText, indexLocation } from './manifest.js'
|