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
package/lib/memory.js
CHANGED
|
@@ -6,6 +6,7 @@ import { STORED_VISIBILITIES, LEGACY_SESSION } from './visibility.js'
|
|
|
6
6
|
import {
|
|
7
7
|
ensureSession, getSessionBinding, memoryDbPath, globalDbPath,
|
|
8
8
|
loadPrivateIndex, savePrivateIndex, loadGlobalIndex, saveGlobalIndex,
|
|
9
|
+
readPrivateIndex, readGlobalIndex, indexReadRevision,
|
|
9
10
|
updatePrivateIndex, updateGlobalIndex,
|
|
10
11
|
newMemoryId, getSettings, effectiveVectorRoute, getActiveCue, consumeCue,
|
|
11
12
|
getLibrary, setSessionBinding, setRecallError, effectiveScope, listLibrariesAll,
|
|
@@ -24,12 +25,17 @@ import { normalizeMemoryContext, contextVisible, sameFactContext } from './conte
|
|
|
24
25
|
import { activeEntryStamp, assertGeneration, assertVectorWriteAllowed, captureGeneration, enrollActiveLibrary, hasActiveVectorGeneration, isVectorStateError, readVectorState, withVectorWrite } from './vector-profile.js'
|
|
25
26
|
import { similarTexts, similarityDetail, DUP_DICE, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
|
|
26
27
|
import { applyAbsorbIndexTransaction } from './curator.js'
|
|
28
|
+
import { createBoundedCache } from './bounded-cache.js'
|
|
27
29
|
import { recallCache, recallCacheKey } from './recall-cache.js'
|
|
28
30
|
import { parseAbsoluteDate, parseTemporalExpression, hasTemporalHint, resolveQueryDates, localDateKeyInZone, DEFAULT_TIME_ZONE } from './temporal.js'
|
|
29
31
|
import { validitySignals } from './freshness.js'
|
|
30
32
|
import { commitmentOf, commitmentDueDate, commitmentDueState, isOpenThread, normalizeCommitment, patchCommitment } from './commitment.js'
|
|
31
33
|
import { detectQueryIntent, decomposeQuery, buildCorpus, bm25, longestSharedToken, polarityAt, tokenize } from './text-retrieval.js'
|
|
32
34
|
import { intentTopK } from './budget.js'
|
|
35
|
+
import { feedbackAccessFactor, applyMemoryFeedback } from './feedback.js'
|
|
36
|
+
import { pageIndexSources } from './index-pages.js'
|
|
37
|
+
import { getRtQueryView, noteRtComparison, readRtBody } from './rt-index-service.js'
|
|
38
|
+
import { createQueryView } from './rt-index/reader.js'
|
|
33
39
|
|
|
34
40
|
// Recall-cache failures fail open, but remain observable through a warning.
|
|
35
41
|
recallCache.setErrorHandler((info) => warn('recall cache failed open: ' + (info?.message || info)))
|
|
@@ -225,7 +231,7 @@ function assertCompensationResult(result, operation) {
|
|
|
225
231
|
// interrupt compensation. Never describe an uncertain repair as success.
|
|
226
232
|
async function compensatePrivateCommit(error, { libraryId, id, route, db, expectedEntry }) {
|
|
227
233
|
try {
|
|
228
|
-
const current =
|
|
234
|
+
const current = readPrivateIndex(libraryId).entries[id]
|
|
229
235
|
if (JSON.stringify(current ?? null) !== JSON.stringify(expectedEntry ?? null)) {
|
|
230
236
|
throw new Error('memory changed before backend compensation')
|
|
231
237
|
}
|
|
@@ -237,7 +243,7 @@ async function compensatePrivateCommit(error, { libraryId, id, route, db, expect
|
|
|
237
243
|
resource: [], user: {},
|
|
238
244
|
} }), 'backend compensation restore')
|
|
239
245
|
}
|
|
240
|
-
if (JSON.stringify(
|
|
246
|
+
if (JSON.stringify(readPrivateIndex(libraryId).entries[id]) !== snapshot) {
|
|
241
247
|
throw new Error('memory changed during backend compensation')
|
|
242
248
|
}
|
|
243
249
|
} catch (compensationError) {
|
|
@@ -308,7 +314,7 @@ async function managedRecall({ exec, index, sourceEmpty, query, topK, libraryId,
|
|
|
308
314
|
// Exact-id reads and the global domain-scoped route keep their existing contract.
|
|
309
315
|
const gate = { automatic, sessionId: memorySessionId(exec), binding, disclosureAsked, speakerFilter }
|
|
310
316
|
const filter = libraryId && !byId ? (file) => crossLibraryEligible(file.entry, gate) : undefined
|
|
311
|
-
const local = localRecall(index, query, filter, { cacheKey: libraryId ? `lib:${libraryId}
|
|
317
|
+
const local = localRecall(index, query, filter, { libraryId, cacheKey: `${libraryId ? `lib:${libraryId}` : `global:${domain || 'all'}`}:${gateCacheSuffix(gate)}`, topK })
|
|
312
318
|
try {
|
|
313
319
|
if (intent.error) throw intent.error
|
|
314
320
|
const captured = intent.route === 'managed-local' ? captureGeneration() : null
|
|
@@ -355,11 +361,11 @@ async function managedRecall({ exec, index, sourceEmpty, query, topK, libraryId,
|
|
|
355
361
|
speakerFilter: libraryId ? speakerFilter : detectSpeakerQuery(query), sessionId: memorySessionId(exec), route: 'managed-vector-rrf' })
|
|
356
362
|
return { ...semantic, files: fused.files, recallRoute: 'managed-vector-rrf', fusion: fused.debug, vectorGeneration: captured?.token ?? null }
|
|
357
363
|
})
|
|
358
|
-
clearRecallError(exec)
|
|
359
|
-
return result
|
|
364
|
+
if (!local.errors?.length) clearRecallError(exec)
|
|
365
|
+
return local.errors?.length ? { ...result, errors: [...(result.errors || []), ...local.errors] } : result
|
|
360
366
|
} catch (error) {
|
|
361
367
|
const reason = rememberRecallError(exec, error)
|
|
362
|
-
return { ...local, recallRoute: 'local-fallback', errors: ['semantic recall failed: ' + reason] }
|
|
368
|
+
return { ...local, recallRoute: 'local-fallback', errors: [...(local.errors || []), 'semantic recall failed: ' + reason] }
|
|
363
369
|
}
|
|
364
370
|
}
|
|
365
371
|
|
|
@@ -677,7 +683,8 @@ export function normalizeSalientDate(value) {
|
|
|
677
683
|
if (short) {
|
|
678
684
|
const month = Number(short[1])
|
|
679
685
|
const day = Number(short[2])
|
|
680
|
-
|
|
686
|
+
// A leap-year reference admits 02-29 without admitting impossible month-days.
|
|
687
|
+
if (!(month >= 1 && month <= 12) || !(day >= 1 && day <= daysInMonth(2000, month))) return null
|
|
681
688
|
return `${pad2(month)}-${pad2(day)}`
|
|
682
689
|
}
|
|
683
690
|
// Parse a calendar date as text, never through Date.parse: date-only parsing can
|
|
@@ -800,12 +807,17 @@ function temporalFieldsOf({ title, content, scene, salientDate, absoluteDate, va
|
|
|
800
807
|
const text = `${title || ''}\n${content || ''}`
|
|
801
808
|
const parsed = parseTemporalExpression(text, { now: scene, timeZone: DEFAULT_TIME_ZONE })
|
|
802
809
|
if (parsed) {
|
|
803
|
-
fields.absolute_date = parsed.absoluteDate
|
|
810
|
+
if (parsed.absoluteDate) fields.absolute_date = parsed.absoluteDate
|
|
804
811
|
fields.date_precision = datePrecision || parsed.precision
|
|
805
812
|
fields.date_source = parsed.dateSource
|
|
806
813
|
} else if (hasTemporalHint(text)) {
|
|
807
814
|
fields.date_precision = 'unknown'
|
|
808
815
|
fields.date_source = 'relative'
|
|
816
|
+
// No body/query in diagnostics: failed dates must be visible without leaking
|
|
817
|
+
// private text or pretending an unresolved phrase has a calendar day.
|
|
818
|
+
record({ kind: 'system', level: 'warn', ok: false, message: '日期提示无法解析:保留 unknown 精度,不推断具体日',
|
|
819
|
+
detail: { code: 'TEMPORAL_PARSE_UNRESOLVED', precision: 'unknown' } })
|
|
820
|
+
warn('temporal date parse unresolved; date precision remains unknown')
|
|
809
821
|
}
|
|
810
822
|
}
|
|
811
823
|
const from = dateOnlyField(validFrom, 'valid_from')
|
|
@@ -821,10 +833,12 @@ function temporalFieldsOf({ title, content, scene, salientDate, absoluteDate, va
|
|
|
821
833
|
// How many days ahead today is from a dated memory (0 = due today, negative =
|
|
822
834
|
// already past). An anniversary has no distance: it is true every year.
|
|
823
835
|
export function salientDaysAhead(salientDate, now = new Date()) {
|
|
824
|
-
|
|
825
|
-
|
|
836
|
+
const value = normalizeSalientDate(salientDate)
|
|
837
|
+
if (!isDatedSalientDate(value)) return null
|
|
838
|
+
const parts = value.split('-').map(Number)
|
|
826
839
|
const due = Date.UTC(parts[0], parts[1] - 1, parts[2])
|
|
827
840
|
const today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
|
|
841
|
+
if (!Number.isFinite(today)) return null
|
|
828
842
|
return Math.round((due - today) / 86_400_000)
|
|
829
843
|
}
|
|
830
844
|
|
|
@@ -840,6 +854,7 @@ export function salientDateFires(salientDate, now = new Date()) {
|
|
|
840
854
|
const value = normalizeSalientDate(salientDate)
|
|
841
855
|
if (!value) return false
|
|
842
856
|
if (!isDatedSalientDate(value)) {
|
|
857
|
+
// 02-29 has no substitute in common years; anniversaries have no lead day.
|
|
843
858
|
return value === `${pad2(now.getMonth() + 1)}-${pad2(now.getDate())}`
|
|
844
859
|
}
|
|
845
860
|
const ahead = salientDaysAhead(value, now)
|
|
@@ -872,13 +887,31 @@ export function selfReferenceBias(entry) {
|
|
|
872
887
|
return entry?.owner === 'me' || entry?.owner === 'us' ? 1 + SELF_HALF_LIFE_FACTOR : 1
|
|
873
888
|
}
|
|
874
889
|
|
|
890
|
+
const strengthCache = new WeakMap()
|
|
891
|
+
|
|
875
892
|
export function decayStrength(entry) {
|
|
876
|
-
if (!entry) return 1
|
|
893
|
+
if (!entry || typeof entry !== 'object') return 1
|
|
894
|
+
const now = Date.now()
|
|
895
|
+
const bucket = Math.floor(now / 3_600_000)
|
|
896
|
+
// Frozen entry identity is its revision. Mutable writer snapshots also need a
|
|
897
|
+
// scalar signature so same-timestamp edits cannot reuse an old derived value.
|
|
898
|
+
const revision = Object.isFrozen(entry) ? entry : JSON.stringify([
|
|
899
|
+
entry.updatedAt, entry.createdAt, entry.strength, entry.accessCount, entry.layer,
|
|
900
|
+
entry.owner, entry.moodValence, entry.marginalized, entry.feedback?.confirm, entry.feedback?.deny,
|
|
901
|
+
])
|
|
902
|
+
const cached = strengthCache.get(entry)
|
|
903
|
+
if (cached?.revision === revision && cached.bucket === bucket) return cached.value
|
|
904
|
+
const updated = cached?.revision === revision ? cached.updated : (Date.parse(entry.updatedAt || entry.createdAt || '') || null)
|
|
905
|
+
const value = computeDecayStrength(entry, now, updated ?? now)
|
|
906
|
+
strengthCache.set(entry, { revision, bucket, updated, value })
|
|
907
|
+
return value
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
function computeDecayStrength(entry, now, updated) {
|
|
877
911
|
if (entry.marginalized) return 0.2
|
|
878
912
|
const base = typeof entry.strength === 'number' ? entry.strength : 1
|
|
879
|
-
const
|
|
880
|
-
const
|
|
881
|
-
const access = 1 + Math.min(0.5, (entry.accessCount || 0) * 0.05)
|
|
913
|
+
const days = Math.max(0, (now - updated) / 86_400_000)
|
|
914
|
+
const access = feedbackAccessFactor(entry)
|
|
882
915
|
if (entry.layer === 'must_remember') {
|
|
883
916
|
const decay = Math.pow(0.5, days / MUST_REMEMBER_HALF_LIFE_DAYS)
|
|
884
917
|
return Math.max(MUST_REMEMBER_FLOOR, Math.min(1.5, base * decay * access))
|
|
@@ -915,15 +948,29 @@ export function fadedValence(entry, now = Date.now()) {
|
|
|
915
948
|
* so a memory can be "clearly remembered, possibly wrong" — a state people are
|
|
916
949
|
* in all the time and that a single confidence number cannot express.
|
|
917
950
|
*/
|
|
918
|
-
export function accuracyOf({ peak = false, arousal = 0.35, confidence = 0.8 } = {}) {
|
|
951
|
+
export function accuracyOf({ peak = false, arousal = 0.35, confidence = 0.8, observed = true } = {}) {
|
|
919
952
|
const confRaw = Number(confidence)
|
|
920
953
|
const conf = Math.max(0, Math.min(1, Number.isFinite(confRaw) ? confRaw : 0.8))
|
|
921
954
|
const charge = Math.max(0, Math.min(1, Number(arousal) || 0))
|
|
922
955
|
const heightened = peak === true || charge > 0.7
|
|
923
|
-
if (!heightened) return conf
|
|
956
|
+
if (!heightened) return conf * (observed ? 1 : 0.85)
|
|
924
957
|
// The higher the charge, the wider the gap between "vivid" and "correct".
|
|
925
958
|
const discount = Math.min(0.5, Math.max(0, charge - 0.5) * 1.2)
|
|
926
|
-
return Math.round(Math.max(0.2, conf * (1 - discount)) * 100) / 100
|
|
959
|
+
return Math.round(Math.max(0.2, conf * (1 - discount)) * 100) / 100 * (observed ? 1 : 0.85)
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
function observedFile(file, libraryId) {
|
|
963
|
+
if (!libraryId || !file.entry?.attachments?.length) return file
|
|
964
|
+
const attachments = file.entry.attachments.map(item => {
|
|
965
|
+
try { return { ...item, ...attachmentRefs(libraryId, [{ sha256: item.sha256 }])[0] } }
|
|
966
|
+
catch { return { ...item, missing: true } }
|
|
967
|
+
})
|
|
968
|
+
const observed = attachments.some(item => !item.missing)
|
|
969
|
+
return { ...file, strength: (file.strength ?? decayStrength(file.entry)) * (observed ? 1 : 0.85),
|
|
970
|
+
entry: { ...file.entry, attachments, observed,
|
|
971
|
+
accuracy: accuracyOf({ ...file.entry, observed }),
|
|
972
|
+
},
|
|
973
|
+
}
|
|
927
974
|
}
|
|
928
975
|
|
|
929
976
|
/**
|
|
@@ -1000,7 +1047,7 @@ export function findConflict(entries, candidate) {
|
|
|
1000
1047
|
// equally invisible. A hidden hit must not leak its id (5.1).
|
|
1001
1048
|
function visibleForDedupe(entry, sessionId) {
|
|
1002
1049
|
if (!entry || entry.visibility === 'secret') return false
|
|
1003
|
-
return
|
|
1050
|
+
return visibleToSession(entry, sessionId)
|
|
1004
1051
|
}
|
|
1005
1052
|
|
|
1006
1053
|
// Critical-section re-check for the duplicate gate (5.4): the pre-flight scan
|
|
@@ -1182,51 +1229,27 @@ function byUpdatedDesc(a, b) {
|
|
|
1182
1229
|
.localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || ''))
|
|
1183
1230
|
}
|
|
1184
1231
|
|
|
1185
|
-
//
|
|
1186
|
-
//
|
|
1187
|
-
//
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
const
|
|
1196
|
-
|
|
1197
|
-
const lexicalCorpusCache = new Map()
|
|
1198
|
-
|
|
1199
|
-
function corpusFingerprint(files) {
|
|
1200
|
-
const hash = crypto.createHash('sha1')
|
|
1201
|
-
for (const file of files) {
|
|
1202
|
-
hash.update(String(file.name))
|
|
1203
|
-
hash.update('\u0000')
|
|
1204
|
-
hash.update(String(file.entry?.title || ''))
|
|
1205
|
-
hash.update('\u0000')
|
|
1206
|
-
hash.update(lexicalDocumentText(file.entry))
|
|
1207
|
-
hash.update('\u0000')
|
|
1208
|
-
}
|
|
1209
|
-
return hash.digest('hex')
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
|
-
function lexicalCorpusFor(files, cacheKey) {
|
|
1213
|
-
const now = Date.now()
|
|
1214
|
-
const fingerprint = cacheKey ? corpusFingerprint(files) : null
|
|
1215
|
-
if (cacheKey) {
|
|
1216
|
-
const cached = lexicalCorpusCache.get(cacheKey)
|
|
1217
|
-
if (cached && cached.fingerprint === fingerprint && cached.expiresAt > now) return cached.corpus
|
|
1218
|
-
}
|
|
1232
|
+
// P1: fingerprints are admitted at cold load / successful write in state.js.
|
|
1233
|
+
// Cache scope also carries binding/context/scene qualification; expiry still runs
|
|
1234
|
+
// on every query, and a changed eligible count changes the corpus key immediately.
|
|
1235
|
+
const lexicalCorpusCache = createBoundedCache({ name: 'lexicalCorpus', maxBytes: 96 * 1024 * 1024, maxEntries: 32, ttlMs: 60000 })
|
|
1236
|
+
const derivedIndexRevisions = new WeakMap()
|
|
1237
|
+
const derivedIndexSources = new WeakMap()
|
|
1238
|
+
export function lexicalCacheStats() { return lexicalCorpusCache.stats() }
|
|
1239
|
+
|
|
1240
|
+
function lexicalCorpusFor(files, cacheKey, revision = null) {
|
|
1241
|
+
const key = cacheKey && revision ? JSON.stringify([cacheKey, revision, files.length]) : null
|
|
1242
|
+
const cached = key ? lexicalCorpusCache.get(key) : null
|
|
1243
|
+
if (cached) return cached
|
|
1219
1244
|
const corpus = buildCorpus(files.map((file) => ({
|
|
1220
1245
|
id: file.name,
|
|
1221
1246
|
title: file.entry?.title || '',
|
|
1222
1247
|
content: lexicalDocumentText(file.entry),
|
|
1223
1248
|
})))
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
lexicalCorpusCache.set(cacheKey, { fingerprint, expiresAt: now + LEXICAL_CORPUS_TTL_MS, corpus })
|
|
1229
|
-
}
|
|
1249
|
+
// Recall only consumes tf/len/df and postings. Do not pin a second copy of
|
|
1250
|
+
// bodies or token Sets merely because buildCorpus also serves pair matching.
|
|
1251
|
+
for (const doc of corpus.docs.values()) { delete doc.entry; delete doc.tokens }
|
|
1252
|
+
if (key) lexicalCorpusCache.set(key, corpus)
|
|
1230
1253
|
return corpus
|
|
1231
1254
|
}
|
|
1232
1255
|
|
|
@@ -1241,7 +1264,91 @@ function localIndexFiles(index) {
|
|
|
1241
1264
|
}))
|
|
1242
1265
|
}
|
|
1243
1266
|
|
|
1244
|
-
function localRecall(index, query, filter = () => true, { cacheKey = null, topK = null } = {}) {
|
|
1267
|
+
function localRecall(index, query, filter = () => true, { cacheKey = null, topK = null, libraryId } = {}) {
|
|
1268
|
+
const empty = files => ({ files, segments: [], resources: [], raw: null, parseWarning: null })
|
|
1269
|
+
const fileFor = id => {
|
|
1270
|
+
const entry = index.entries[id]
|
|
1271
|
+
return { name: id, description: entry?.title || '', content: String(entry?.content || ''), entry,
|
|
1272
|
+
strength: decayStrength(entry), createdAtIdentity: entry?.createdAt || null }
|
|
1273
|
+
}
|
|
1274
|
+
if (/^(?:g?mem)[-_][a-z0-9_-]+(?:\.md)?$/i.test(String(query || '').trim())) {
|
|
1275
|
+
const id = resolveEntryId(index, String(query).trim())
|
|
1276
|
+
const entry = index.entries[id]
|
|
1277
|
+
const file = entry ? fileFor(id) : null
|
|
1278
|
+
return empty(file && isActive(entry) && filter(file) ? [{ ...file, lexical: 5 }] : [])
|
|
1279
|
+
}
|
|
1280
|
+
const root = derivedIndexSources.get(index) || index
|
|
1281
|
+
const rt = libraryId === undefined || recallLexicalMode() === 'includes' ? null : getRtQueryView({
|
|
1282
|
+
index: root, libraryId, cacheKey,
|
|
1283
|
+
isVisible: (entry, id) => Object.hasOwn(index.entries, id) && isActive(entry) && filter({ name: id, entry }),
|
|
1284
|
+
})
|
|
1285
|
+
if (!rt?.view || !tokenize(query).length) {
|
|
1286
|
+
const result = localRecallSource(index, query, filter, { cacheKey, topK })
|
|
1287
|
+
if (rt?.fallback) result.errors = [`derived recall fallback: ${rt.fallback}`]
|
|
1288
|
+
return result
|
|
1289
|
+
}
|
|
1290
|
+
const tokens = tokenize(query)
|
|
1291
|
+
const ranked = rt.view.score(tokens)
|
|
1292
|
+
const topic = dominanceQuery(query)
|
|
1293
|
+
const evidence = topic !== String(query || '') ? rt.view.score(tokenize(topic)) : ranked
|
|
1294
|
+
const evidenceById = new Map(evidence.hits.map(hit => [hit.id, hit.score]))
|
|
1295
|
+
const queryDates = String(query || '').match(/\d{4}-\d{2}-\d{2}/g) || []
|
|
1296
|
+
const lexicalById = new Map(ranked.hits.map(hit => [hit.id, hit.score]))
|
|
1297
|
+
const dateIds = new Set(queryDates.flatMap(date => rt.dates.get(date) || []))
|
|
1298
|
+
const best = ranked.hits.reduce((max, hit) => Math.max(max, hit.score), 0)
|
|
1299
|
+
const dateOnly = best > 0 ? best / DATE_ONLY_RATIO : 1
|
|
1300
|
+
const ids = new Set([...lexicalById.keys(), ...dateIds])
|
|
1301
|
+
const ordered = [...ids].map(id => ({ ...fileFor(id), lexicalEvidence: evidenceById.get(id) || 0,
|
|
1302
|
+
lexical: lexicalById.has(id) ? lexicalById.get(id) * (dateIds.has(id) ? DATE_MATCH_FACTOR : 1) : dateOnly }))
|
|
1303
|
+
.sort((a, b) => b.lexical - a.lexical || byUpdatedDesc(a, b))
|
|
1304
|
+
const result = empty(ordered)
|
|
1305
|
+
const fallbackCodes = [...new Set([ranked.fallback, evidence.fallback].filter(Boolean))]
|
|
1306
|
+
if (rt.mode === 'shadow') {
|
|
1307
|
+
const source = localRecallSource(index, query, filter, { cacheKey, topK })
|
|
1308
|
+
const errors = fallbackCodes.map(code => `derived recall fallback: ${code}`)
|
|
1309
|
+
if (!noteRtComparison(source.files, ordered)) errors.push('derived recall RT_SHADOW_MISMATCH; source result retained')
|
|
1310
|
+
if (errors.length) source.errors = errors
|
|
1311
|
+
return source
|
|
1312
|
+
}
|
|
1313
|
+
if (fallbackCodes.length) result.errors = fallbackCodes.map(code => `derived recall fallback: ${code}`)
|
|
1314
|
+
result.rt = { backend: ranked.backend, candidates: ranked.hits.length }
|
|
1315
|
+
return result
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
function localRecallSource(index, query, filter = () => true, { cacheKey = null, topK = null } = {}) {
|
|
1319
|
+
// Keep the source oracle independent of the disposable index without holding
|
|
1320
|
+
// a second large corpus. Its N/df/totalLen still cover every eligible entry.
|
|
1321
|
+
if (recallLexicalMode() !== 'includes' && Object.keys(index.entries || {}).length > 2048 && tokenize(query).length) {
|
|
1322
|
+
const queryDates = String(query || '').match(/\d{4}-\d{2}-\d{2}/g) || []
|
|
1323
|
+
const tokens = tokenize(query)
|
|
1324
|
+
const topic = dominanceQuery(query)
|
|
1325
|
+
const evidenceTokens = topic !== String(query || '') ? tokenize(topic) : tokens
|
|
1326
|
+
const ids = Object.keys(index.entries).filter(id => isActive(index.entries[id]) && filter({ name: id, entry: index.entries[id] }))
|
|
1327
|
+
const source = { index, revision: indexReadRevision(index) || derivedIndexRevisions.get(index) || 'source-oracle' }
|
|
1328
|
+
const view = createQueryView(source, { visibleIds: ids })
|
|
1329
|
+
const data = view.queryPostings([...new Set([...tokens, ...evidenceTokens])])
|
|
1330
|
+
const scored = new Map()
|
|
1331
|
+
let best = 0
|
|
1332
|
+
for (const [id, doc] of data.docs) {
|
|
1333
|
+
const lexical = bm25(tokens, doc, data.corpus)
|
|
1334
|
+
best = Math.max(best, lexical)
|
|
1335
|
+
if (lexical > 0) scored.set(id, { lexical, lexicalEvidence: bm25(evidenceTokens, doc, data.corpus) })
|
|
1336
|
+
}
|
|
1337
|
+
const dateOnly = best > 0 ? best / DATE_ONLY_RATIO : 1
|
|
1338
|
+
const files = []
|
|
1339
|
+
for (const id of ids) {
|
|
1340
|
+
const entry = index.entries[id]
|
|
1341
|
+
const match = scored.get(id)
|
|
1342
|
+
const dateMatch = Boolean(entry.absolute_date && queryDates.includes(entry.absolute_date))
|
|
1343
|
+
if (!match && !dateMatch) continue
|
|
1344
|
+
const evidence = match?.lexicalEvidence ?? (data.docs.has(id) ? bm25(evidenceTokens, data.docs.get(id), data.corpus) : 0)
|
|
1345
|
+
files.push({ name: id, description: entry.title || '', content: String(entry.content || ''), entry,
|
|
1346
|
+
strength: decayStrength(entry), createdAtIdentity: entry.createdAt || null, lexicalEvidence: evidence,
|
|
1347
|
+
lexical: match ? match.lexical * (dateMatch ? DATE_MATCH_FACTOR : 1) : dateOnly })
|
|
1348
|
+
}
|
|
1349
|
+
files.sort((a, b) => b.lexical - a.lexical || byUpdatedDesc(a, b))
|
|
1350
|
+
return { files, segments: [], resources: [], raw: null, parseWarning: null }
|
|
1351
|
+
}
|
|
1245
1352
|
const files = localIndexFiles(index).filter((file) => isActive(file.entry) && filter(file))
|
|
1246
1353
|
if (/^(?:g?mem)[-_][a-z0-9_-]+(?:\.md)?$/i.test(String(query || '').trim())) {
|
|
1247
1354
|
const id = resolveEntryId(index, String(query).trim())
|
|
@@ -1266,7 +1373,7 @@ function localRecall(index, query, filter = () => true, { cacheKey = null, topK
|
|
|
1266
1373
|
if (tokens.length === 0) {
|
|
1267
1374
|
return { files: files.sort(byUpdatedDesc).slice(0, emptyQueryLimit(topK)), segments: [], resources: [], raw: null, parseWarning: null }
|
|
1268
1375
|
}
|
|
1269
|
-
const corpus = lexicalCorpusFor(files, cacheKey)
|
|
1376
|
+
const corpus = lexicalCorpusFor(files, cacheKey, indexReadRevision(index) || derivedIndexRevisions.get(index))
|
|
1270
1377
|
const evidenceTokens = evidenceChanged ? tokenize(topic) : null
|
|
1271
1378
|
// The date boost came over from the includes scorer unchanged (+4), where it shared
|
|
1272
1379
|
// a ruler with "title matches = 4". BM25 has no upper bound and its IDF depends on
|
|
@@ -1307,30 +1414,55 @@ export function hybridCandidateLimit(topK) {
|
|
|
1307
1414
|
return Math.max(HYBRID_CANDIDATE_MIN, Math.min(HYBRID_CANDIDATE_MAX, wanted * 4))
|
|
1308
1415
|
}
|
|
1309
1416
|
|
|
1417
|
+
const conflictBacklinks = new WeakMap()
|
|
1418
|
+
function conflictBacklinksFor(index) {
|
|
1419
|
+
if (!index || typeof index !== 'object') return new Map()
|
|
1420
|
+
const cached = conflictBacklinks.get(index)
|
|
1421
|
+
if (cached) return cached
|
|
1422
|
+
const reverse = new Map()
|
|
1423
|
+
for (const [id, entry] of Object.entries(index.entries || {})) {
|
|
1424
|
+
if (!entry.conflicts_with) continue
|
|
1425
|
+
if (!reverse.has(entry.conflicts_with)) reverse.set(entry.conflicts_with, [])
|
|
1426
|
+
reverse.get(entry.conflicts_with).push(id)
|
|
1427
|
+
}
|
|
1428
|
+
conflictBacklinks.set(index, reverse)
|
|
1429
|
+
return reverse
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1310
1432
|
export function groupConflictCandidates(files, indexesByLibrary, { scope = 'private', canRead = entry => isMemoryEligible(entry, { automatic: true }), maxMembers = 8 } = {}) {
|
|
1311
1433
|
const indexes = indexesByLibrary instanceof Map ? indexesByLibrary : new Map(Object.entries(indexesByLibrary || {}))
|
|
1312
1434
|
const libraryGraphs = new Map()
|
|
1313
1435
|
const graphFor = libraryId => {
|
|
1314
1436
|
if (libraryGraphs.has(libraryId)) return libraryGraphs.get(libraryId)
|
|
1315
1437
|
const index = indexes.get(libraryId) || (indexes.size === 1 ? indexes.values().next().value : null)
|
|
1316
|
-
const
|
|
1317
|
-
const
|
|
1438
|
+
const source = index?.entries || {}
|
|
1439
|
+
const reverse = conflictBacklinksFor(index)
|
|
1440
|
+
const entries = new Map()
|
|
1441
|
+
const roots = new Map()
|
|
1442
|
+
const components = new Map()
|
|
1443
|
+
// Traverse only components touched by actual candidates. The immutable index
|
|
1444
|
+
// shares a reverse-edge directory; permission decisions remain request-local.
|
|
1318
1445
|
const find = id => {
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1446
|
+
if (roots.has(id)) return roots.get(id)
|
|
1447
|
+
const pending = [id]
|
|
1448
|
+
const seen = new Set()
|
|
1449
|
+
const members = []
|
|
1450
|
+
while (pending.length) {
|
|
1451
|
+
const current = pending.pop()
|
|
1452
|
+
if (seen.has(current)) continue
|
|
1453
|
+
seen.add(current)
|
|
1454
|
+
const entry = source[current]
|
|
1455
|
+
if (!entry || !canRead(entry, libraryId)) continue
|
|
1456
|
+
entries.set(current, entry)
|
|
1457
|
+
members.push(current)
|
|
1458
|
+
if (entry.conflicts_with) pending.push(entry.conflicts_with)
|
|
1459
|
+
for (const from of reverse.get(current) || []) pending.push(from)
|
|
1460
|
+
}
|
|
1461
|
+
const root = members.slice().sort()[0] || id
|
|
1462
|
+
for (const member of members) roots.set(member, root)
|
|
1463
|
+
components.set(root, members)
|
|
1322
1464
|
return root
|
|
1323
1465
|
}
|
|
1324
|
-
for (const [id, entry] of entries) {
|
|
1325
|
-
const other = entry.conflicts_with
|
|
1326
|
-
if (other && entries.has(other)) parents.set(find(id), find(other))
|
|
1327
|
-
}
|
|
1328
|
-
const components = new Map()
|
|
1329
|
-
for (const id of entries.keys()) {
|
|
1330
|
-
const root = find(id)
|
|
1331
|
-
if (!components.has(root)) components.set(root, [])
|
|
1332
|
-
components.get(root).push(id)
|
|
1333
|
-
}
|
|
1334
1466
|
const graph = { entries, components, find }
|
|
1335
1467
|
libraryGraphs.set(libraryId, graph)
|
|
1336
1468
|
return graph
|
|
@@ -1339,8 +1471,8 @@ export function groupConflictCandidates(files, indexesByLibrary, { scope = 'priv
|
|
|
1339
1471
|
for (const file of files || []) {
|
|
1340
1472
|
const libraryId = scope === 'global' ? null : file.libraryId ?? indexes.keys().next().value ?? null
|
|
1341
1473
|
const graph = graphFor(libraryId)
|
|
1342
|
-
if (!graph.entries.has(file.name)) continue
|
|
1343
1474
|
const root = graph.find(file.name)
|
|
1475
|
+
if (!graph.entries.has(file.name)) continue
|
|
1344
1476
|
const key = JSON.stringify([libraryId, root])
|
|
1345
1477
|
if (!roots.has(key)) roots.set(key, { libraryId, graph, root, candidates: [] })
|
|
1346
1478
|
roots.get(key).candidates.push(file)
|
|
@@ -1352,8 +1484,8 @@ export function groupConflictCandidates(files, indexesByLibrary, { scope = 'priv
|
|
|
1352
1484
|
const ranked = candidates.slice().sort((a, b) => (Number(b.score) || 0) - (Number(a.score) || 0))
|
|
1353
1485
|
const byId = new Map(ranked.map(file => [file.name, file]))
|
|
1354
1486
|
const groupFiles = ids.slice(0, maxMembers).map(id => {
|
|
1355
|
-
const entry = graph.entries.get(id)
|
|
1356
1487
|
const file = byId.get(id)
|
|
1488
|
+
const entry = file?.entry || graph.entries.get(id)
|
|
1357
1489
|
return { ...(file || {}), name: id, libraryId, entry, description: entry.title || '', content: String(entry.content || ''),
|
|
1358
1490
|
strength: file?.strength ?? decayStrength(entry), createdAtIdentity: entry.createdAt || null }
|
|
1359
1491
|
})
|
|
@@ -1923,6 +2055,8 @@ function mmrSelect(items, max, lambda = MMR_LAMBDA) {
|
|
|
1923
2055
|
*/
|
|
1924
2056
|
export function visibleToSession(entry, sessionId, binding = undefined) {
|
|
1925
2057
|
if (!entry) return true
|
|
2058
|
+
// P0: a session-less port caller has no identity with which to read a secret.
|
|
2059
|
+
if (!sessionId && entry.visibility === 'secret') return false
|
|
1926
2060
|
const scope = binding === undefined ? getSessionBinding(sessionId) : binding
|
|
1927
2061
|
return contextVisible(entry.context, scope?.memoryContext)
|
|
1928
2062
|
}
|
|
@@ -1936,6 +2070,22 @@ function createdAtSpan(files) {
|
|
|
1936
2070
|
return { first: stamps[0] || null, last: stamps[stamps.length - 1] || null }
|
|
1937
2071
|
}
|
|
1938
2072
|
|
|
2073
|
+
const createdSpans = new WeakMap()
|
|
2074
|
+
function indexCreatedSpan(index) {
|
|
2075
|
+
const cached = createdSpans.get(index)
|
|
2076
|
+
if (cached) return cached
|
|
2077
|
+
let first = null, last = null
|
|
2078
|
+
for (const entry of Object.values(index.entries || {})) {
|
|
2079
|
+
const at = entry?.createdAt
|
|
2080
|
+
if (typeof at !== 'string' || !at) continue
|
|
2081
|
+
if (!first || at < first) first = at
|
|
2082
|
+
if (!last || at > last) last = at
|
|
2083
|
+
}
|
|
2084
|
+
const span = { first, last }
|
|
2085
|
+
createdSpans.set(index, span)
|
|
2086
|
+
return span
|
|
2087
|
+
}
|
|
2088
|
+
|
|
1939
2089
|
/**
|
|
1940
2090
|
* Decide what an entry's affect actually is, and which tier answered.
|
|
1941
2091
|
*
|
|
@@ -2636,11 +2786,14 @@ export function crossLibrarySources(binding, domain) {
|
|
|
2636
2786
|
}
|
|
2637
2787
|
|
|
2638
2788
|
function domainScopedIndex(index, domain) {
|
|
2639
|
-
|
|
2789
|
+
const view = {
|
|
2640
2790
|
...index,
|
|
2641
2791
|
entries: Object.fromEntries(Object.entries(index.entries || {})
|
|
2642
2792
|
.filter(([, entry]) => !entry?.domain || entry.domain === domain)),
|
|
2643
2793
|
}
|
|
2794
|
+
derivedIndexRevisions.set(view, indexReadRevision(index) || derivedIndexRevisions.get(index))
|
|
2795
|
+
derivedIndexSources.set(view, derivedIndexSources.get(index) || index)
|
|
2796
|
+
return view
|
|
2644
2797
|
}
|
|
2645
2798
|
|
|
2646
2799
|
// R4:进入统一语料前的资格门,与 privateWeighted 的过滤链同一套谓词。不可见
|
|
@@ -2654,15 +2807,16 @@ function crossLibraryEligible(entry, { automatic, sessionId, binding, disclosure
|
|
|
2654
2807
|
}
|
|
2655
2808
|
|
|
2656
2809
|
// 资格标志进缓存 key:自动/显式的授权语料不同,共用 key 会让交替召回每次指纹失配重建。
|
|
2657
|
-
function gateCacheSuffix({ automatic, disclosureAsked, speakerFilter }) {
|
|
2658
|
-
return
|
|
2810
|
+
function gateCacheSuffix({ automatic, disclosureAsked, speakerFilter, sessionId, binding }) {
|
|
2811
|
+
return JSON.stringify([Boolean(automatic), Boolean(disclosureAsked), speakerFilter ?? null, sessionId ?? null,
|
|
2812
|
+
binding?.memoryContext ?? null, binding?.sceneTime ?? null, binding?.scopeKey ?? null, binding?.domainOverride ?? binding?.domain ?? null])
|
|
2659
2813
|
}
|
|
2660
2814
|
|
|
2661
2815
|
// R4:跨库统一词法评分。文档身份是复合 [libraryId,id] key,两库同 id 是两份
|
|
2662
2816
|
// 文档而不是同一份;语料指纹含复合 id,任一成员库内容变化都会失效共享语料。
|
|
2663
2817
|
// 评分规则与 localRecall 的 BM25 分支一致(日期加成、证据分离、date-only 末位),
|
|
2664
2818
|
// 只是 IDF/avgdl 来自授权集合的统一语料,分数跨库可比。
|
|
2665
|
-
function crossLibraryLexical(files, query, { cacheKey = null, topK = null } = {}) {
|
|
2819
|
+
function crossLibraryLexical(files, query, { cacheKey = null, revision = null, topK = null, rtSources = null } = {}) {
|
|
2666
2820
|
const queryDates = String(query || '').match(/\d{4}-\d{2}-\d{2}/g) || []
|
|
2667
2821
|
const topic = dominanceQuery(query)
|
|
2668
2822
|
const evidenceChanged = topic !== String(query || '')
|
|
@@ -2679,8 +2833,86 @@ function crossLibraryLexical(files, query, { cacheKey = null, topK = null } = {}
|
|
|
2679
2833
|
}
|
|
2680
2834
|
const tokens = tokenize(query)
|
|
2681
2835
|
if (tokens.length === 0) return { files: files.slice().sort(byUpdatedDesc).slice(0, emptyQueryLimit(topK)), mode: 'recency' }
|
|
2836
|
+
if (rtSources) {
|
|
2837
|
+
const rtErrors = new Set()
|
|
2838
|
+
const evidenceTokens = evidenceChanged ? tokenize(topic) : null
|
|
2839
|
+
const needed = [...new Set([...tokens, ...(evidenceTokens || [])])]
|
|
2840
|
+
const collect = useOracle => {
|
|
2841
|
+
const df = new Map()
|
|
2842
|
+
const docs = new Map()
|
|
2843
|
+
const identities = new Map()
|
|
2844
|
+
let size = 0
|
|
2845
|
+
let totalLen = 0
|
|
2846
|
+
for (let sourcePosition = 0; sourcePosition < rtSources.length; sourcePosition++) {
|
|
2847
|
+
const source = rtSources[sourcePosition]
|
|
2848
|
+
const view = useOracle && source.oracle ? source.oracle : source.view
|
|
2849
|
+
const data = view.queryPostings(needed)
|
|
2850
|
+
if (data.fallback) rtErrors.add(`${source.libraryId}: ${data.fallback}`)
|
|
2851
|
+
size += data.corpus.size
|
|
2852
|
+
totalLen += data.totalLen
|
|
2853
|
+
for (const [term, count] of data.corpus.df) df.set(term, (df.get(term) || 0) + count)
|
|
2854
|
+
for (const [id, doc] of data.docs) {
|
|
2855
|
+
const key = JSON.stringify([source.libraryId ?? null, id])
|
|
2856
|
+
docs.set(key, doc)
|
|
2857
|
+
identities.set(key, { id, libraryId: source.libraryId, entry: source.index.entries[id], sourcePosition, order: doc.order })
|
|
2858
|
+
}
|
|
2859
|
+
// Dates are an independent legacy candidate source, including documents
|
|
2860
|
+
// with no query posting. They never alter N/df/avgdl or lexical evidence.
|
|
2861
|
+
for (const date of queryDates) for (const id of source.dates.get(date) || []) {
|
|
2862
|
+
const key = JSON.stringify([source.libraryId ?? null, id])
|
|
2863
|
+
if (!identities.has(key)) identities.set(key, {
|
|
2864
|
+
id, libraryId: source.libraryId, entry: source.index.entries[id], sourcePosition,
|
|
2865
|
+
order: source.orderOf(id),
|
|
2866
|
+
})
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
const corpus = { size, avgdl: size ? totalLen / size : 0, df }
|
|
2870
|
+
const scored = []
|
|
2871
|
+
let best = 0
|
|
2872
|
+
for (const [key, identity] of identities) {
|
|
2873
|
+
const doc = docs.get(key)
|
|
2874
|
+
const lexical = doc ? bm25(tokens, doc, corpus) : 0
|
|
2875
|
+
best = Math.max(best, lexical)
|
|
2876
|
+
scored.push({ ...identity, lexical,
|
|
2877
|
+
lexicalEvidence: evidenceTokens && doc ? bm25(evidenceTokens, doc, corpus) : lexical,
|
|
2878
|
+
dateMatch: Boolean(identity.entry?.absolute_date && queryDates.includes(identity.entry.absolute_date)),
|
|
2879
|
+
})
|
|
2880
|
+
}
|
|
2881
|
+
const dateOnly = best > 0 ? best / DATE_ONLY_RATIO : 1
|
|
2882
|
+
return scored.map(row => ({ ...row, lexical: row.lexical > 0
|
|
2883
|
+
? row.lexical * (row.dateMatch ? DATE_MATCH_FACTOR : 1) : row.dateMatch ? dateOnly : 0 }))
|
|
2884
|
+
.filter(row => row.lexical > 0)
|
|
2885
|
+
.sort((a, b) => b.lexical - a.lexical
|
|
2886
|
+
|| String(b.entry?.updatedAt || b.entry?.createdAt || '').localeCompare(String(a.entry?.updatedAt || a.entry?.createdAt || ''))
|
|
2887
|
+
|| a.sourcePosition - b.sourcePosition || a.order - b.order)
|
|
2888
|
+
.map(row => ({ name: row.id, libraryId: row.libraryId, entry: row.entry, description: row.entry?.title || '',
|
|
2889
|
+
content: String(row.entry?.content || ''), strength: decayStrength(row.entry), createdAtIdentity: row.entry?.createdAt || null,
|
|
2890
|
+
lexical: row.lexical, lexicalEvidence: row.lexicalEvidence }))
|
|
2891
|
+
}
|
|
2892
|
+
const actual = collect(false)
|
|
2893
|
+
const shadow = rtSources.find(source => source.mode === 'shadow' && source.controller)
|
|
2894
|
+
if (shadow) {
|
|
2895
|
+
const expected = collect(true)
|
|
2896
|
+
const comparisonRows = rows => rows.map(row => ({ id: JSON.stringify([row.libraryId ?? null, row.name]), score: row.lexical }))
|
|
2897
|
+
const expectedRows = comparisonRows(expected)
|
|
2898
|
+
const actualRows = comparisonRows(actual)
|
|
2899
|
+
const comparison = shadow.controller.compareFinal(expectedRows, actualRows)
|
|
2900
|
+
// Service counters also use composite identities; two libraries may share
|
|
2901
|
+
// a canonical memory ID without referring to the same fact.
|
|
2902
|
+
noteRtComparison(expectedRows.map(row => ({ name: row.id, lexical: row.score })),
|
|
2903
|
+
actualRows.map(row => ({ name: row.id, lexical: row.score })))
|
|
2904
|
+
const expectedEvidence = new Map(expected.map(row => [JSON.stringify([row.libraryId ?? null, row.name]), row.lexicalEvidence]))
|
|
2905
|
+
if (comparison.agreement !== 1 || comparison.scoreDifferences || !comparison.orderEqual
|
|
2906
|
+
|| actual.some(row => expectedEvidence.get(JSON.stringify([row.libraryId ?? null, row.name])) !== row.lexicalEvidence)) {
|
|
2907
|
+
shadow.controller.invalidate('RT_SHADOW_MISMATCH')
|
|
2908
|
+
rtErrors.add(`${shadow.libraryId}: RT_SHADOW_MISMATCH`)
|
|
2909
|
+
}
|
|
2910
|
+
return { files: expected, mode: 'unified-bm25', errors: [...rtErrors] }
|
|
2911
|
+
}
|
|
2912
|
+
return { files: actual, mode: 'unified-bm25', errors: [...rtErrors] }
|
|
2913
|
+
}
|
|
2682
2914
|
const docId = (file) => JSON.stringify([file.libraryId ?? null, file.name])
|
|
2683
|
-
const corpus = lexicalCorpusFor(files.map((file) => ({ name: docId(file), entry: file.entry })), cacheKey)
|
|
2915
|
+
const corpus = lexicalCorpusFor(files.map((file) => ({ name: docId(file), entry: file.entry })), cacheKey, revision)
|
|
2684
2916
|
const evidenceTokens = evidenceChanged ? tokenize(topic) : null
|
|
2685
2917
|
const scored = files.map((file) => {
|
|
2686
2918
|
const doc = corpus.docs.get(docId(file))
|
|
@@ -2715,8 +2947,38 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
|
|
|
2715
2947
|
const sessionId = memorySessionId(exec)
|
|
2716
2948
|
const gate = { automatic, sessionId, binding, disclosureAsked, speakerFilter }
|
|
2717
2949
|
const rowKey = (libraryId, name) => JSON.stringify([libraryId ?? null, name])
|
|
2950
|
+
let rtSources = null
|
|
2951
|
+
const rtErrors = []
|
|
2952
|
+
if (route === 'lexical' && !byId && recallLexicalMode() !== 'includes' && tokenize(query).length) {
|
|
2953
|
+
const { getRtQueryView, rtMode } = await import('./rt-index-service.js')
|
|
2954
|
+
const candidates = sources.map(source => {
|
|
2955
|
+
const isVisible = entry => (source.primary || !entry?.domain || entry.domain === domain) && crossLibraryEligible(entry, gate)
|
|
2956
|
+
const cacheKey = `cross:${source.primary ? 'primary' : domain || 'all'}:${gateCacheSuffix(gate)}`
|
|
2957
|
+
const context = getRtQueryView({ index: source.index, libraryId: source.libraryId, cacheKey, isVisible })
|
|
2958
|
+
if (context?.fallback) rtErrors.push(`${source.libraryId}: ${context.fallback}`)
|
|
2959
|
+
return { ...source, isVisible, context }
|
|
2960
|
+
})
|
|
2961
|
+
if (candidates.some(source => source.context?.view?.queryPostings)) {
|
|
2962
|
+
const { createQueryView } = await import('./rt-index/reader.js')
|
|
2963
|
+
rtSources = candidates.map(source => {
|
|
2964
|
+
const context = source.context
|
|
2965
|
+
const view = context?.view || createQueryView({ index: source.index, revision: indexReadRevision(source.index) || 'uncached-cross-library' }, { isVisible: source.isVisible })
|
|
2966
|
+
const dates = context?.dates || new Map()
|
|
2967
|
+
if (!context?.dates) for (const id of view.ids) {
|
|
2968
|
+
const date = source.index.entries[id].absolute_date
|
|
2969
|
+
if (date) { if (!dates.has(date)) dates.set(date, []); dates.get(date).push(id) }
|
|
2970
|
+
}
|
|
2971
|
+
return { libraryId: source.libraryId, index: source.index, view, dates, orderOf: view.orderOf,
|
|
2972
|
+
mode: context?.mode || rtMode(), controller: context?.controller || null,
|
|
2973
|
+
oracle: context?.view && context.mode === 'shadow'
|
|
2974
|
+
? createQueryView(context.source, { visibleIds: view.ids }) : null,
|
|
2975
|
+
}
|
|
2976
|
+
})
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2718
2979
|
const lists = []
|
|
2719
2980
|
for (const source of sources) {
|
|
2981
|
+
if (rtSources) { lists.push({ libraryId: source.libraryId, files: [] }); continue }
|
|
2720
2982
|
const scoped = source.primary ? source.index : domainScopedIndex(source.index, domain)
|
|
2721
2983
|
if (route === 'lexical' || byId) {
|
|
2722
2984
|
const files = byId
|
|
@@ -2743,7 +3005,7 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
|
|
|
2743
3005
|
parseWarning: null,
|
|
2744
3006
|
recallRoute: 'cross-library',
|
|
2745
3007
|
libraries: sources.map((source) => source.libraryId),
|
|
2746
|
-
errors: lists.flatMap((list) => (list.errors || []).map((error) => `${list.libraryId}: ${error}`)),
|
|
3008
|
+
errors: [...rtErrors, ...lists.flatMap((list) => (list.errors || []).map((error) => `${list.libraryId}: ${error}`))],
|
|
2747
3009
|
}
|
|
2748
3010
|
const primaryId = sources.find((source) => source.primary)?.libraryId || null
|
|
2749
3011
|
if (byId) {
|
|
@@ -2755,7 +3017,9 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
|
|
|
2755
3017
|
}
|
|
2756
3018
|
if (route === 'lexical') {
|
|
2757
3019
|
const cacheKey = `cross:${sources.map((source) => source.libraryId).join('|')}:${domain || 'all'}:${gateCacheSuffix(gate)}`
|
|
2758
|
-
const
|
|
3020
|
+
const revision = JSON.stringify(sources.map(source => indexReadRevision(source.index)))
|
|
3021
|
+
const unified = crossLibraryLexical(lists.flatMap((list) => list.files), query, { cacheKey, revision, topK, rtSources })
|
|
3022
|
+
if (unified.errors?.length) base.errors.push(...unified.errors)
|
|
2759
3023
|
if (unified.mode === 'recency') {
|
|
2760
3024
|
return { ...base, files: unified.files, fusion: { crossLibraryLexical: 'recency' } }
|
|
2761
3025
|
}
|
|
@@ -2867,7 +3131,7 @@ export function readMemoryByRef({ exec, scope = 'private', id, libraryId = null,
|
|
|
2867
3131
|
if (libraryId !== null && !sources.some(source => source.libraryId === libraryId)) throw memoryReadError('MEMORY_LIBRARY_FORBIDDEN', 'that library is outside this conversation memory scope')
|
|
2868
3132
|
const matches = []
|
|
2869
3133
|
for (const source of sources.filter(source => libraryId === null || source.libraryId === libraryId)) {
|
|
2870
|
-
const index = scope === 'global' ?
|
|
3134
|
+
const index = scope === 'global' ? readGlobalIndex() : readPrivateIndex(source.libraryId)
|
|
2871
3135
|
if (readFailure(path.join(indexDir(), scope === 'global' ? 'global.json' : source.libraryId + '.json'))) throw memoryReadError('MEMORY_STORAGE_UNAVAILABLE', 'the memory index could not be read safely')
|
|
2872
3136
|
let canonical
|
|
2873
3137
|
try { canonical = resolveEntryId(index, String(id).trim()) } catch (error) {
|
|
@@ -2885,7 +3149,7 @@ export function readMemoryByRef({ exec, scope = 'private', id, libraryId = null,
|
|
|
2885
3149
|
&& isDisclosureEligible(candidate, { automatic, asked: false })
|
|
2886
3150
|
&& (scope === 'global' ? appliesToDomain(candidate, binding || { domain: 'general' }) : source.primary || !candidate.domain || candidate.domain === domain)
|
|
2887
3151
|
if (!canRead(entry)) throw memoryReadError('MEMORY_NOT_READABLE', 'that memory is not eligible in this conversation')
|
|
2888
|
-
const body = redactSecrets(
|
|
3152
|
+
const body = redactSecrets(readRtBody({ index, libraryId: source.libraryId, id: canonical }))
|
|
2889
3153
|
const bodyRevision = crypto.createHash('sha256').update(body).digest('hex')
|
|
2890
3154
|
if (revision !== null && revision !== bodyRevision) throw memoryReadError('MEMORY_CHANGED', 'memory changed between pages; read again from offset 0')
|
|
2891
3155
|
const points = Array.from(body)
|
|
@@ -2915,7 +3179,11 @@ export function readMemoryByRef({ exec, scope = 'private', id, libraryId = null,
|
|
|
2915
3179
|
}
|
|
2916
3180
|
}
|
|
2917
3181
|
|
|
2918
|
-
export async function privateRecall(
|
|
3182
|
+
export async function privateRecall(args) {
|
|
3183
|
+
return structuredClone(await privateRecallImpl(args))
|
|
3184
|
+
}
|
|
3185
|
+
|
|
3186
|
+
async function privateRecallImpl({ exec, libraryId: explicitLibraryId, query, topK, relevanceThreshold, purpose = 'explicit', excludedRefs = [], retrieveImpl = retrieve }) {
|
|
2919
3187
|
const binding = peekBinding(exec)
|
|
2920
3188
|
// 绑定是会话级的:没有会话就没有默认库,必须显式给 libraryId。这条口子是给
|
|
2921
3189
|
// 无宿主调用方(MCP server / 脚本 / 移植适配器)留的,宿主内的行为一字不变。
|
|
@@ -2953,7 +3221,7 @@ export async function privateRecall({ exec, libraryId: explicitLibraryId, query,
|
|
|
2953
3221
|
const sources = (binding && settings.crossLibraryRecall === true
|
|
2954
3222
|
? crossLibrarySources(binding, domain)
|
|
2955
3223
|
: [{ libraryId: scope.libraryId, primary: true }])
|
|
2956
|
-
.map((source) => ({ ...source, index:
|
|
3224
|
+
.map((source) => ({ ...source, index: readPrivateIndex(source.libraryId) }))
|
|
2957
3225
|
if (purpose === 'automatic') {
|
|
2958
3226
|
const allowed = new Set(sources.map(source => source.libraryId))
|
|
2959
3227
|
const excludedCount = excludedRefs.filter(ref => ref?.scope === 'private' && allowed.has(ref.libraryId)).length
|
|
@@ -2971,18 +3239,21 @@ export async function privateRecall({ exec, libraryId: explicitLibraryId, query,
|
|
|
2971
3239
|
const retrievalStarted = performance.now()
|
|
2972
3240
|
const result = sources.length === 1
|
|
2973
3241
|
? (route === 'lexical' || byId
|
|
2974
|
-
? { ...localRecall(sources[0].index, searchQuery, byId ? undefined : (file) => crossLibraryEligible(file.entry, gate), { cacheKey: `lib:${sources[0].libraryId}:${gateCacheSuffix(gate)}`, topK: candidateK }), recallRoute: 'local' }
|
|
3242
|
+
? { ...localRecall(sources[0].index, searchQuery, byId ? undefined : (file) => crossLibraryEligible(file.entry, gate), { libraryId: sources[0].libraryId, cacheKey: `lib:${sources[0].libraryId}:${gateCacheSuffix(gate)}`, topK: candidateK }), recallRoute: 'local' }
|
|
2975
3243
|
: await managedRecall({ exec, index: sources[0].index, sourceEmpty: Object.keys(sources[0].index.entries || {}).length === 0,
|
|
2976
3244
|
query: searchQuery, topK: candidateK, libraryId: sources[0].libraryId, ...gate, intent: managedVectorIntent(), retrieveImpl, byId, domain }))
|
|
2977
3245
|
: await recallCrossLibrary({ exec, sources, query: searchQuery, topK: candidateK, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain, binding: gate.binding,
|
|
2978
3246
|
disclosureAsked: recallIntent === 'boundary', speakerFilter: detectSpeakerQuery(query) })
|
|
2979
3247
|
const retrievalMs = performance.now() - retrievalStarted
|
|
3248
|
+
if (binding && result.errors?.some(error => error.includes('RT_'))) {
|
|
3249
|
+
setRecallError(memorySessionId(exec), result.errors.join('; '))
|
|
3250
|
+
}
|
|
2980
3251
|
const current = peekBinding(exec)
|
|
2981
3252
|
// 无会话没有「中途换库」这回事(scope 是调用方给的常量),跳过这轮校验;
|
|
2982
3253
|
// 有会话时保持原来的并发守卫。
|
|
2983
3254
|
if (binding && (!current || current.libraryId !== scope.libraryId || scopeGenerationOf(current) !== generationAtStart)) throw new Error('memory scope changed during recall; retry')
|
|
2984
3255
|
assertScopeEnabled(current)
|
|
2985
|
-
const index =
|
|
3256
|
+
const index = readPrivateIndex(scope.libraryId)
|
|
2986
3257
|
const indexByLibrary = new Map(sources.map((source) => [source.libraryId, source.libraryId === scope.libraryId ? index : domainScopedIndex(source.index, domain)]))
|
|
2987
3258
|
// enrichFiles fills body/strength from one index; doing that against the bound
|
|
2988
3259
|
// library would blank every foreign hit. Cross-library files already carry
|
|
@@ -3002,9 +3273,12 @@ export async function privateRecall({ exec, libraryId: explicitLibraryId, query,
|
|
|
3002
3273
|
if (result?.errors) enriched.errors = result.errors.slice()
|
|
3003
3274
|
if (result?.fusion) enriched.fusion = result.fusion
|
|
3004
3275
|
if (result?.libraries) enriched.libraries = result.libraries.slice()
|
|
3005
|
-
const
|
|
3006
|
-
|
|
3007
|
-
|
|
3276
|
+
const spans = sources.map(source => indexCreatedSpan(source.libraryId === scope.libraryId ? index : source.index))
|
|
3277
|
+
const span = {
|
|
3278
|
+
first: spans.map(item => item.first).filter(Boolean).sort()[0] || null,
|
|
3279
|
+
last: spans.map(item => item.last).filter(Boolean).sort().at(-1) || null,
|
|
3280
|
+
}
|
|
3281
|
+
enriched.files = enriched.files.map(file => observedFile(file, file.libraryId || scope.libraryId))
|
|
3008
3282
|
const mood = moodDecay(scope.mood)
|
|
3009
3283
|
const canRead = entry => isMemoryEligible(entry, { automatic: true }) && visibleToSession(entry, memorySessionId(exec))
|
|
3010
3284
|
&& isDisclosureEligible(entry, { automatic: true, asked: recallIntent === 'boundary' })
|
|
@@ -3179,18 +3453,38 @@ export async function privateRecall({ exec, libraryId: explicitLibraryId, query,
|
|
|
3179
3453
|
if (scored.groups) scored.trace.counts.selectedGroups = scored.groups.length
|
|
3180
3454
|
for (const file of scored.files) file.ref ??= memoryRef({ scope: 'private', libraryId: file.libraryId || scope.libraryId, id: file.name, entry: file.entry })
|
|
3181
3455
|
scored.refs = scored.files.map(file => file.ref)
|
|
3456
|
+
// The lexicon owns separate postings, privacy gates and <=2 slots; memory MMR is unchanged.
|
|
3457
|
+
let lexiconRecall
|
|
3458
|
+
try { lexiconRecall = (await import('./lexicon-scope.js')).recallLexicon } catch (error) {
|
|
3459
|
+
scored.lexiconErrors = [`lexicon unavailable: ${error?.message || error}`]
|
|
3460
|
+
}
|
|
3461
|
+
const lexiconBinding = binding ? peekBinding(exec) : { ...scope, useGlobal: false, useLibrary: true }
|
|
3462
|
+
if (binding && (!lexiconBinding || lexiconBinding.libraryId !== scope.libraryId
|
|
3463
|
+
|| scopeGenerationOf(lexiconBinding) !== generationAtStart)) throw new Error('memory scope changed during recall; retry')
|
|
3464
|
+
scored.lexicon = []
|
|
3465
|
+
if (lexiconRecall) {
|
|
3466
|
+
try {
|
|
3467
|
+
const recalled = lexiconRecall(lexiconBinding, query, { automatic: purpose === 'automatic' || !binding })
|
|
3468
|
+
scored.lexicon = recalled.lexicon
|
|
3469
|
+
if (recalled.errors.length) scored.lexiconErrors = recalled.errors
|
|
3470
|
+
} catch (error) { scored.lexiconErrors = [`lexicon recall failed: ${error?.message || error}`] }
|
|
3471
|
+
}
|
|
3472
|
+
if (scored.lexiconErrors?.length) {
|
|
3473
|
+
warn(`lexicon recall degraded (fail-open): ${scored.lexiconErrors.join('; ')}`)
|
|
3474
|
+
if (binding) setRecallError(memorySessionId(exec), scored.lexiconErrors.join('; '))
|
|
3475
|
+
}
|
|
3182
3476
|
return scored
|
|
3183
3477
|
}
|
|
3184
3478
|
|
|
3185
|
-
async function privateListRaw({ exec, libraryId, preferIndex = false }) {
|
|
3479
|
+
async function privateListRaw({ exec, libraryId, preferIndex = false, restricted = false }) {
|
|
3186
3480
|
const scope = resolveLibrary({ exec, libraryId, readOnly: true })
|
|
3187
3481
|
if (scope.binding) assertScopeEnabled(scope.binding)
|
|
3188
|
-
const index =
|
|
3482
|
+
const index = readPrivateIndex(scope.libraryId)
|
|
3189
3483
|
const viewSessionId = sessionIdOf(exec) ? memorySessionId(exec) : null
|
|
3190
3484
|
// 每条记忆都重查一次 binding 会把跨库列表拖到 250ms(562 条 ≈ 226ms);这里已经
|
|
3191
3485
|
// 从 resolveLibrary 拿到了同一条 binding,直接交给谓词。
|
|
3192
3486
|
const viewBinding = bindingForSession(exec, scope.binding, viewSessionId)
|
|
3193
|
-
const allowed = (entry) =>
|
|
3487
|
+
const allowed = (entry) => (!viewSessionId && !restricted) || (!!entry && isMemoryEligible(entry) && visibleToSession(entry, viewSessionId, viewBinding))
|
|
3194
3488
|
const settings = getSettings()
|
|
3195
3489
|
// The sidebar list follows the same scope as recall when the setting is on.
|
|
3196
3490
|
// An explicit libraryId is the browser's library selector and must stay
|
|
@@ -3206,7 +3500,7 @@ async function privateListRaw({ exec, libraryId, preferIndex = false }) {
|
|
|
3206
3500
|
// 提到来源层查一次。
|
|
3207
3501
|
const domain = domainOf(scope.binding)
|
|
3208
3502
|
for (const source of crossSources) {
|
|
3209
|
-
const sourceIndex = source.libraryId === scope.libraryId ? index :
|
|
3503
|
+
const sourceIndex = source.libraryId === scope.libraryId ? index : readPrivateIndex(source.libraryId)
|
|
3210
3504
|
const scoped = source.primary ? sourceIndex : domainScopedIndex(sourceIndex, domain)
|
|
3211
3505
|
const libraryName = getLibrary(source.libraryId)?.name || source.libraryId
|
|
3212
3506
|
for (const file of localIndexFiles(scoped)) {
|
|
@@ -3274,8 +3568,35 @@ async function privateListRaw({ exec, libraryId, preferIndex = false }) {
|
|
|
3274
3568
|
}
|
|
3275
3569
|
|
|
3276
3570
|
/** 分页只切返回值;不传 limit 保持全量(现有 UI/RPC 调用方行为不变)。 */
|
|
3277
|
-
export async function privateList({ exec, libraryId, preferIndex = false, limit = null, offset = 0 }) {
|
|
3278
|
-
|
|
3571
|
+
export async function privateList({ exec, libraryId, preferIndex = false, limit = null, offset = 0, restricted = false, snapshotRevision = null, status = null, domain = null, query = '' }) {
|
|
3572
|
+
if (preferIndex || engineRoute() === 'lexical') {
|
|
3573
|
+
const scope = resolveLibrary({ exec, libraryId, readOnly: true })
|
|
3574
|
+
if (scope.binding) assertScopeEnabled(scope.binding)
|
|
3575
|
+
const viewSessionId = sessionIdOf(exec) ? memorySessionId(exec) : null
|
|
3576
|
+
const viewBinding = bindingForSession(exec, scope.binding, viewSessionId) ?? getSessionBinding(viewSessionId)
|
|
3577
|
+
const currentDomain = domainOf(scope.binding)
|
|
3578
|
+
const cross = !libraryId && scope.binding && getSettings().crossLibraryRecall === true
|
|
3579
|
+
? crossLibrarySources(scope.binding, currentDomain) : [{ libraryId: scope.libraryId, primary: true }]
|
|
3580
|
+
const sources = cross.map(source => ({ ...source, scope: 'private', index: readPrivateIndex(source.libraryId) }))
|
|
3581
|
+
const page = pageIndexSources({ sources, limit, offset, snapshotRevision, status, domain, query,
|
|
3582
|
+
viewKey: JSON.stringify(['privateList', viewSessionId, viewBinding?.memoryContext, restricted, currentDomain]),
|
|
3583
|
+
filter: (entry, source) => (source.primary || !entry.domain || entry.domain === currentDomain)
|
|
3584
|
+
&& ((!viewSessionId && !restricted) || (isMemoryEligible(entry) && visibleToSession(entry, viewSessionId, viewBinding))),
|
|
3585
|
+
})
|
|
3586
|
+
const names = new Map(sources.map(source => [source.libraryId, getLibrary(source.libraryId)?.name || source.libraryId]))
|
|
3587
|
+
const multi = sources.length > 1
|
|
3588
|
+
return {
|
|
3589
|
+
libraryId: scope.libraryId, source: 'index',
|
|
3590
|
+
warning: !preferIndex && effectiveVectorRoute() !== 'lexical'
|
|
3591
|
+
? '本地向量未激活(只有 requested,尚未建成 active 代际);以下列表来自索引,向量库为空' : null,
|
|
3592
|
+
...(multi ? { libraries: sources.map(source => ({ id: source.libraryId, name: names.get(source.libraryId) })) } : {}),
|
|
3593
|
+
total: page.total, offset: page.offset, snapshotRevision: page.snapshotRevision, domains: page.domains, counts: page.counts,
|
|
3594
|
+
files: structuredClone(page.rows.map(({ id, source, entry }) => ({ name: id, description: entry.title || '', content: String(entry.content || ''), entry,
|
|
3595
|
+
...(multi ? { libraryId: source.libraryId, libraryName: names.get(source.libraryId) } : {}),
|
|
3596
|
+
}))), raw: null, parseWarning: null,
|
|
3597
|
+
}
|
|
3598
|
+
}
|
|
3599
|
+
const result = await privateListRaw({ exec, libraryId, preferIndex, restricted })
|
|
3279
3600
|
const files = Array.isArray(result.files) ? result.files : []
|
|
3280
3601
|
const total = files.length
|
|
3281
3602
|
const start = Math.max(0, Math.floor(Number(offset) || 0))
|
|
@@ -3284,7 +3605,7 @@ export async function privateList({ exec, libraryId, preferIndex = false, limit
|
|
|
3284
3605
|
...result,
|
|
3285
3606
|
total,
|
|
3286
3607
|
offset: start,
|
|
3287
|
-
files: size ? files.slice(start, start + size) : files,
|
|
3608
|
+
files: structuredClone(size ? files.slice(start, start + size) : files),
|
|
3288
3609
|
}
|
|
3289
3610
|
}
|
|
3290
3611
|
|
|
@@ -3379,7 +3700,12 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
|
|
|
3379
3700
|
const allOthers = Object.fromEntries(Object.entries(index.entries).filter(([key]) => key !== id_))
|
|
3380
3701
|
const visibleOthers = Object.fromEntries(Object.entries(allOthers).filter(([, other]) => visibleForDedupe(other, memorySession)))
|
|
3381
3702
|
const conflict = findConflict(visibleOthers, { ...entry, title: nextTitle, content: nextContent ?? entry.content })
|
|
3382
|
-
if (conflict)
|
|
3703
|
+
if (conflict) {
|
|
3704
|
+
const pendingId = await holdRejectedDraft({ libraryId: scope.libraryId, id: id_, index, entry,
|
|
3705
|
+
draft: { ...entry, title: nextTitle, content: nextContent ?? entry.content, context: nextContext }, operation: 'update',
|
|
3706
|
+
duplicateId: conflict.id, reviewReason: 'conflict', exec, scene, expectedScopeGeneration: scopeGenerationOf(getSessionBinding(memorySession)) })
|
|
3707
|
+
throw draftRefusal(`content conflicts with ${conflict.id}; review the preserved draft`, pendingId)
|
|
3708
|
+
}
|
|
3383
3709
|
text = `${nextTitle} ${nextContent ?? entry.content}`
|
|
3384
3710
|
for (const [otherId, other] of Object.entries(allOthers)) {
|
|
3385
3711
|
// 与 remember 的门同一过滤集(isMemoryEligible + sameFactContext),再排除它原本的
|
|
@@ -3401,7 +3727,10 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
|
|
|
3401
3727
|
detail: { id: id_, deduped: true, hidden: true, similarityBand: '0.90+' },
|
|
3402
3728
|
refs: [id_],
|
|
3403
3729
|
})
|
|
3404
|
-
|
|
3730
|
+
const pendingId = await holdRejectedDraft({ libraryId: scope.libraryId, id: id_, index, entry,
|
|
3731
|
+
draft: { ...entry, title: nextTitle, content: nextContent ?? entry.content, context: nextContext }, operation: 'update',
|
|
3732
|
+
exec, scene, expectedScopeGeneration: scopeGenerationOf(getSessionBinding(memorySession)) })
|
|
3733
|
+
throw draftRefusal('update refused: a nearly identical memory exists outside this conversation\'s visible scope; review the preserved draft', pendingId)
|
|
3405
3734
|
}
|
|
3406
3735
|
if (duplicate && duplicate.similarity >= DUP_REJECT_DICE) {
|
|
3407
3736
|
const target = index.entries[duplicate.id]
|
|
@@ -3412,7 +3741,10 @@ async function privateUpdateImpl({ exec, libraryId, id, content, title, tags, st
|
|
|
3412
3741
|
detail: { id: id_, deduped: true, existingId: duplicate.id, similarity: duplicate.similarity },
|
|
3413
3742
|
refs: [id_, duplicate.id],
|
|
3414
3743
|
})
|
|
3415
|
-
|
|
3744
|
+
const pendingId = await holdRejectedDraft({ libraryId: scope.libraryId, id: id_, index, entry,
|
|
3745
|
+
draft: { ...entry, title: nextTitle, content: nextContent ?? entry.content, context: nextContext }, operation: 'update',
|
|
3746
|
+
duplicateId: duplicate.id, exec, scene, expectedScopeGeneration: scopeGenerationOf(getSessionBinding(memorySession)) })
|
|
3747
|
+
throw draftRefusal(`update refused: the rewritten text is nearly identical to ${duplicate.id} (dice ${duplicate.similarity.toFixed(2)}); differences: ${diff || '(none visible)'}; review the preserved draft`, pendingId)
|
|
3416
3748
|
}
|
|
3417
3749
|
}
|
|
3418
3750
|
const route = engineRoute()
|
|
@@ -3709,7 +4041,9 @@ async function resolveMemoryReviewImpl({ libraryId = null, id, action, resolutio
|
|
|
3709
4041
|
detail: { id, deduped: true, hidden: true, similarityBand: '0.90+' },
|
|
3710
4042
|
refs: [id],
|
|
3711
4043
|
})
|
|
3712
|
-
|
|
4044
|
+
const pendingId = await holdRejectedDraft({ libraryId, id, index, entry, draft: next, operation: 'review-accept', sessionId,
|
|
4045
|
+
scene: sceneTimeOf({ binding: sessionId ? getSessionBinding(sessionId) : null, context: next.context }) })
|
|
4046
|
+
throw draftRefusal('review accept refused: a nearly identical memory exists outside the visible scope; review the preserved draft', pendingId)
|
|
3713
4047
|
}
|
|
3714
4048
|
if (duplicate && duplicate.similarity >= DUP_REJECT_DICE) {
|
|
3715
4049
|
const target = index.entries[duplicate.id]
|
|
@@ -3720,7 +4054,9 @@ async function resolveMemoryReviewImpl({ libraryId = null, id, action, resolutio
|
|
|
3720
4054
|
detail: { id, deduped: true, existingId: duplicate.id, similarity: duplicate.similarity },
|
|
3721
4055
|
refs: [id, duplicate.id],
|
|
3722
4056
|
})
|
|
3723
|
-
|
|
4057
|
+
const pendingId = await holdRejectedDraft({ libraryId, id, index, entry, draft: next, operation: 'review-accept', duplicateId: duplicate.id, sessionId,
|
|
4058
|
+
scene: sceneTimeOf({ binding: sessionId ? getSessionBinding(sessionId) : null, context: next.context }) })
|
|
4059
|
+
throw draftRefusal(`review accept refused: the accepted text is nearly identical to ${duplicate.id} (dice ${duplicate.similarity.toFixed(2)}); differences: ${diff || '(none visible)'}; review the preserved draft`, pendingId)
|
|
3724
4060
|
}
|
|
3725
4061
|
if (duplicate && duplicate.similarity >= TOPIC_DICE) next.duplicateOf = duplicate.id
|
|
3726
4062
|
const reviewRoute = engineRoute()
|
|
@@ -3980,7 +4316,7 @@ export function archiveExpiredDrafts({ now = Date.now(), retentionDays = EXPIRED
|
|
|
3980
4316
|
export function overdueOpenCommitments({ libraryId, now = Date.now(), minOverdueDays = 7, limit = 20, maintenance = false, allCandidates = false, excludeIds = [], sessionId = null, timeZone } = {}) {
|
|
3981
4317
|
if (!libraryId) return []
|
|
3982
4318
|
let index = null
|
|
3983
|
-
try { index =
|
|
4319
|
+
try { index = readPrivateIndex(libraryId) } catch { return [] }
|
|
3984
4320
|
const minDays = Math.max(0, Number(minOverdueDays) || 0)
|
|
3985
4321
|
const excluded = new Set(excludeIds || [])
|
|
3986
4322
|
const rows = []
|
|
@@ -4002,7 +4338,36 @@ export function overdueOpenCommitments({ libraryId, now = Date.now(), minOverdue
|
|
|
4002
4338
|
|| String(a.dueAt || '').localeCompare(String(b.dueAt || ''))
|
|
4003
4339
|
|| String(a.entry.updatedAt || a.entry.createdAt || '').localeCompare(String(b.entry.updatedAt || b.entry.createdAt || ''))
|
|
4004
4340
|
|| a.id.localeCompare(b.id))
|
|
4005
|
-
return allCandidates ? rows : rows.slice(0, Math.max(0, Number(limit) || 0))
|
|
4341
|
+
return structuredClone(allCandidates ? rows : rows.slice(0, Math.max(0, Number(limit) || 0)))
|
|
4342
|
+
}
|
|
4343
|
+
|
|
4344
|
+
// Feedback is a bound-library metadata write, never a cross-library or global one.
|
|
4345
|
+
export function privateFeedback({ exec, id, verdict, reason, expectedRevision }) {
|
|
4346
|
+
const binding = peekBinding(exec)
|
|
4347
|
+
if (!binding?.libraryId) throw new Error('no bound session')
|
|
4348
|
+
assertScopeEnabled(binding)
|
|
4349
|
+
const libraryId = binding.libraryId
|
|
4350
|
+
const generation = scopeGenerationOf(binding)
|
|
4351
|
+
const snapshot = loadPrivateIndex(libraryId)
|
|
4352
|
+
const resolvedId = resolveEntryId(snapshot, id)
|
|
4353
|
+
const entry = snapshot.entries[resolvedId]
|
|
4354
|
+
assertEntryAccess(entry, exec)
|
|
4355
|
+
assertMemoryEntryRevision(entry, expectedRevision)
|
|
4356
|
+
const revision = memoryEntryRevision(entry)
|
|
4357
|
+
const at = stamp()
|
|
4358
|
+
const next = structuredClone(entry)
|
|
4359
|
+
applyMemoryFeedback(next, verdict, redactSecrets(reason), at)
|
|
4360
|
+
const updated = updatePrivateIndex(libraryId, fresh => {
|
|
4361
|
+
assertExpectedMemoryScope(exec, libraryId, generation)
|
|
4362
|
+
const current = fresh.entries[resolvedId]
|
|
4363
|
+
assertEntryAccess(current, exec)
|
|
4364
|
+
assertMemoryEntryRevision(current, revision)
|
|
4365
|
+
// Preserve any concurrent observational counters excluded from the content CAS.
|
|
4366
|
+
applyMemoryFeedback(current, verdict, redactSecrets(reason), at)
|
|
4367
|
+
})
|
|
4368
|
+
record({ kind: 'write', scope: 'private', sessionId: sessionIdOf(exec), libraryId,
|
|
4369
|
+
message: '记忆反馈已记录', refs: [resolvedId], detail: { id: resolvedId, verdict } })
|
|
4370
|
+
return { id: resolvedId, entry: updated.entries[resolvedId] }
|
|
4006
4371
|
}
|
|
4007
4372
|
|
|
4008
4373
|
export function privateArchive({ exec, libraryId, id }) {
|
|
@@ -4265,7 +4630,7 @@ export function privateUnpin({ exec, id, reason }) {
|
|
|
4265
4630
|
entry.pinSource = null
|
|
4266
4631
|
entry.sideEventId = null
|
|
4267
4632
|
entry.strength = Math.max(0.05, (entry.strength || 1) * 0.2)
|
|
4268
|
-
entry.recallPenalty
|
|
4633
|
+
delete entry.recallPenalty
|
|
4269
4634
|
entry.unpinnedBy = 'model'
|
|
4270
4635
|
entry.unpinnedAt = stamp()
|
|
4271
4636
|
entry.updatedAt = entry.unpinnedAt
|
|
@@ -4298,6 +4663,50 @@ export async function privateRemember(args) {
|
|
|
4298
4663
|
return result
|
|
4299
4664
|
}
|
|
4300
4665
|
|
|
4666
|
+
async function holdRejectedDraft({ libraryId = null, id, index, entry, draft, operation, duplicateId = null, reviewReason = 'near_duplicate', exec = null, sessionId = null, scene = new Date(), expectedScopeGeneration }) {
|
|
4667
|
+
const pendingId = newMemoryId('mem')
|
|
4668
|
+
const at = stamp()
|
|
4669
|
+
const proposal = { ...structuredClone(draft),
|
|
4670
|
+
title: redactSecrets(draft.title || ''), content: redactSecrets(draft.content || ''),
|
|
4671
|
+
status: 'pending_review', reviewReason, draftOf: id, draftOperation: operation,
|
|
4672
|
+
createdAt: at, updatedAt: at, injected: null, accessCount: 0,
|
|
4673
|
+
}
|
|
4674
|
+
// This is a new, index-only proposal. It must not inherit vector ownership,
|
|
4675
|
+
// supersession effects, feedback, or dates unsupported by its replacement text.
|
|
4676
|
+
for (const key of ['vector', 'links', 'supersedes', 'supersededBy', 'conflictingWith', 'duplicateOf', 'feedback', 'recallPenalty', 'absolute_date', 'date_precision', 'date_source', 'salientDate', 'reviewedAt', 'reviewResolution', 'reviewNote']) delete proposal[key]
|
|
4677
|
+
Object.assign(proposal, temporalFieldsOf({ title: proposal.title, content: proposal.content, scene }))
|
|
4678
|
+
proposal.description = proposal.content.slice(0, 180)
|
|
4679
|
+
if (duplicateId) {
|
|
4680
|
+
proposal.conflictingWith = duplicateId
|
|
4681
|
+
if (reviewReason === 'near_duplicate') proposal.duplicateOf = duplicateId
|
|
4682
|
+
}
|
|
4683
|
+
let heldId = pendingId
|
|
4684
|
+
const mutate = fresh => {
|
|
4685
|
+
if (exec) assertExpectedMemoryScope(exec, libraryId, expectedScopeGeneration)
|
|
4686
|
+
if (operation === 'review-accept') {
|
|
4687
|
+
if (JSON.stringify(fresh.entries[id]) !== JSON.stringify(entry)
|
|
4688
|
+
|| JSON.stringify(fresh.entries[entry.conflictingWith]) !== JSON.stringify(index.entries[entry.conflictingWith])) throw new Error('review changed; reload and retry')
|
|
4689
|
+
} else assertMemoryEntryRevision(fresh.entries[id], memoryEntryRevision(entry))
|
|
4690
|
+
const previous = Object.entries(fresh.entries).find(([, value]) => value.status === 'pending_review'
|
|
4691
|
+
&& value.draftOf === id && value.draftOperation === operation
|
|
4692
|
+
&& value.title === proposal.title && value.content === proposal.content)
|
|
4693
|
+
if (previous) { heldId = previous[0]; return }
|
|
4694
|
+
if (fresh.entries[pendingId]) throw new Error('draft id collision; retry')
|
|
4695
|
+
fresh.entries[pendingId] = proposal
|
|
4696
|
+
}
|
|
4697
|
+
await retryStoreWrite(() => libraryId ? updatePrivateIndex(libraryId, mutate) : updateGlobalIndex(mutate))
|
|
4698
|
+
record({ kind: 'write', scope: libraryId ? 'private' : 'global', libraryId, sessionId: sessionId || sessionIdOf(exec),
|
|
4699
|
+
message: '拒写稿已保留为待复核条目', refs: [heldId, id], detail: { pendingId: heldId, draftOf: id, operation } })
|
|
4700
|
+
return heldId
|
|
4701
|
+
}
|
|
4702
|
+
|
|
4703
|
+
function draftRefusal(message, pendingId) {
|
|
4704
|
+
const error = new Error(`${message}; draft preserved as ${pendingId} (pending_review)`)
|
|
4705
|
+
error.code = 'MEMORY_DRAFT_HELD'
|
|
4706
|
+
error.pendingId = pendingId
|
|
4707
|
+
return error
|
|
4708
|
+
}
|
|
4709
|
+
|
|
4301
4710
|
export async function privateUpdate(args) {
|
|
4302
4711
|
const libraryId = resolveLibrary(args).libraryId
|
|
4303
4712
|
const result = await withManagedPrivateWrite(libraryId, () => privateUpdateImpl({ ...args, libraryId }))
|
|
@@ -4491,7 +4900,11 @@ export function appliesToDomain(entry, binding) {
|
|
|
4491
4900
|
return false
|
|
4492
4901
|
}
|
|
4493
4902
|
|
|
4494
|
-
export async function globalRecall(
|
|
4903
|
+
export async function globalRecall(args) {
|
|
4904
|
+
return structuredClone(await globalRecallImpl(args))
|
|
4905
|
+
}
|
|
4906
|
+
|
|
4907
|
+
async function globalRecallImpl({ exec, query, topK, relevanceThreshold, purpose = 'explicit', excludedRefs = [], retrieveImpl = retrieve }) {
|
|
4495
4908
|
// peek, not ensure: injection has already bound any live session before a tool
|
|
4496
4909
|
// can run, so a missing binding here means a read from an unbound conversation.
|
|
4497
4910
|
// That fallback quietly narrows results to the `general` domain, so it is
|
|
@@ -4514,22 +4927,31 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, purp
|
|
|
4514
4927
|
if (excludedCount) candidateK = Math.min(HYBRID_CANDIDATE_MAX, candidateK + excludedCount)
|
|
4515
4928
|
}
|
|
4516
4929
|
const generationAtStart = scopeGenerationOf(peeked)
|
|
4517
|
-
let index =
|
|
4930
|
+
let index = readGlobalIndex()
|
|
4518
4931
|
const intent = managedVectorIntent()
|
|
4519
|
-
const
|
|
4520
|
-
.filter(([, entry]) => appliesToDomain(entry, binding))) }
|
|
4932
|
+
const globalGate = { automatic: true, sessionId: memorySessionId(exec), binding, disclosureAsked: queryIntent === 'boundary' }
|
|
4521
4933
|
const retrievalStarted = performance.now()
|
|
4522
|
-
|
|
4523
|
-
|
|
4524
|
-
|
|
4525
|
-
|
|
4934
|
+
let result
|
|
4935
|
+
if (effectiveVectorRoute() !== 'lexical') {
|
|
4936
|
+
const domainIndex = { ...index, entries: Object.fromEntries(Object.entries(index.entries || {})
|
|
4937
|
+
.filter(([, entry]) => appliesToDomain(entry, binding) && crossLibraryEligible(entry, globalGate))) }
|
|
4938
|
+
derivedIndexRevisions.set(domainIndex, indexReadRevision(index))
|
|
4939
|
+
derivedIndexSources.set(domainIndex, index)
|
|
4940
|
+
result = await managedRecall({ exec, index: domainIndex, sourceEmpty: Object.keys(index.entries || {}).length === 0,
|
|
4941
|
+
query: searchQuery, topK: candidateK, libraryId: null, ...globalGate, intent, retrieveImpl, domain: domainOf(binding) })
|
|
4942
|
+
} else {
|
|
4943
|
+
result = localRecall(index, searchQuery, file => appliesToDomain(file.entry, binding) && crossLibraryEligible(file.entry, globalGate), {
|
|
4944
|
+
libraryId: null, cacheKey: `global:${domainOf(binding)}:${binding.scopeKey || ''}:${gateCacheSuffix(globalGate)}`, topK: candidateK,
|
|
4945
|
+
})
|
|
4946
|
+
}
|
|
4526
4947
|
const retrievalMs = performance.now() - retrievalStarted
|
|
4948
|
+
if (peeked && result.errors?.some(error => error.includes('RT_'))) setRecallError(memorySessionId(exec), result.errors.join('; '))
|
|
4527
4949
|
if (peeked) {
|
|
4528
4950
|
const current = peekBinding(exec)
|
|
4529
4951
|
if (!current || scopeGenerationOf(current) !== generationAtStart) throw new Error('memory binding changed during recall; retry')
|
|
4530
4952
|
assertScopeEnabled(current, { layer: 'global' })
|
|
4531
4953
|
}
|
|
4532
|
-
index =
|
|
4954
|
+
index = readGlobalIndex()
|
|
4533
4955
|
const enriched = enrichFiles(result, index)
|
|
4534
4956
|
if (result?.recallRoute) enriched.recallRoute = result.recallRoute
|
|
4535
4957
|
if (result?.errors) enriched.errors = result.errors.slice()
|
|
@@ -4612,14 +5034,20 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, purp
|
|
|
4612
5034
|
}
|
|
4613
5035
|
}
|
|
4614
5036
|
|
|
4615
|
-
export async function globalList(
|
|
5037
|
+
export async function globalList(args) {
|
|
5038
|
+
return structuredClone(await globalListImpl(args))
|
|
5039
|
+
}
|
|
5040
|
+
|
|
5041
|
+
async function globalListImpl({ exec, domain, preferIndex = false, restricted = false, limit = null, offset = 0, snapshotRevision = null }) {
|
|
4616
5042
|
const binding = peekBinding(exec)
|
|
4617
5043
|
if (binding) assertScopeEnabled(binding, { layer: 'global' })
|
|
4618
|
-
const index =
|
|
5044
|
+
const index = readGlobalIndex()
|
|
4619
5045
|
// The domain parameter is a filter, not just a label: the tool schema promises
|
|
4620
5046
|
// "Optional domain filter", so a caller asking for one domain must not get all.
|
|
4621
5047
|
const domainFilter = (file) => (!domain || (file.entry?.domain || 'unknown') === domain)
|
|
4622
|
-
&& (!sessionIdOf(exec) || (isMemoryEligible(file.entry)
|
|
5048
|
+
&& ((!sessionIdOf(exec) && !restricted) || (isMemoryEligible(file.entry)
|
|
5049
|
+
&& visibleToSession(file.entry, memorySessionId(exec), binding)
|
|
5050
|
+
&& (!sessionIdOf(exec) || appliesToDomain(file.entry, binding || { domain: 'general' }))))
|
|
4623
5051
|
// 与 privateList 同一条口径:受管路由还没有 active 代际时,引擎必然抛
|
|
4624
5052
|
// "managed local vector profile is not active";列表本身其实能答,就按索引答,
|
|
4625
5053
|
// 并把原因带上。否则全局记忆页会闪一下红字再消失。
|
|
@@ -4628,16 +5056,20 @@ export async function globalList({ exec, domain, preferIndex = false }) {
|
|
|
4628
5056
|
? '本地向量未激活(只有 requested,尚未建成 active 代际);以下列表来自索引,向量库为空'
|
|
4629
5057
|
: null
|
|
4630
5058
|
if (route === 'lexical') {
|
|
4631
|
-
const
|
|
5059
|
+
const page = pageIndexSources({ sources: [{ scope: 'global', libraryId: null, index }], limit, offset, snapshotRevision,
|
|
5060
|
+
viewKey: JSON.stringify(['globalList', sessionIdOf(exec), binding?.memoryContext, domainOf(binding), domain, restricted]),
|
|
5061
|
+
filter: entry => domainFilter({ entry }),
|
|
5062
|
+
})
|
|
4632
5063
|
return {
|
|
4633
5064
|
domain: domain || (binding ? domainOf(binding) : 'general'),
|
|
4634
5065
|
source: 'index',
|
|
4635
5066
|
warning,
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
|
|
4639
|
-
|
|
4640
|
-
|
|
5067
|
+
total: page.total, offset: page.offset, snapshotRevision: page.snapshotRevision,
|
|
5068
|
+
files: page.rows.map(({ id, entry }) => ({
|
|
5069
|
+
name: id,
|
|
5070
|
+
description: entry.title || '',
|
|
5071
|
+
content: String(entry.content || ''),
|
|
5072
|
+
entry,
|
|
4641
5073
|
})),
|
|
4642
5074
|
raw: null,
|
|
4643
5075
|
parseWarning: null,
|
|
@@ -4932,7 +5364,7 @@ export function dueOpenLoops({
|
|
|
4932
5364
|
remindDays = 0, remindedAt = {}, includeOverdueDated = false, excludeIds = [], sessionId = null, timeZone, allCandidates = false,
|
|
4933
5365
|
}) {
|
|
4934
5366
|
if (!libraryId) return []
|
|
4935
|
-
const index =
|
|
5367
|
+
const index = readPrivateIndex(libraryId)
|
|
4936
5368
|
const skip = new Set(skipIds || [])
|
|
4937
5369
|
const excluded = new Set(excludeIds || [])
|
|
4938
5370
|
// Filtered before the limit, not after: otherwise an entry this conversation may
|
|
@@ -4958,7 +5390,7 @@ export function dueOpenLoops({
|
|
|
4958
5390
|
// is a commitment, the other one is just unfinished.
|
|
4959
5391
|
const seen = new Set()
|
|
4960
5392
|
const candidates = [...overdue, ...regular].filter(({ id }) => !seen.has(id) && seen.add(id))
|
|
4961
|
-
return allCandidates ? candidates : candidates.slice(0, Math.max(0, Number(limit) || 0))
|
|
5393
|
+
return structuredClone(allCandidates ? candidates : candidates.slice(0, Math.max(0, Number(limit) || 0)))
|
|
4962
5394
|
}
|
|
4963
5395
|
|
|
4964
5396
|
/**
|
|
@@ -4969,7 +5401,7 @@ export function dueOpenLoops({
|
|
|
4969
5401
|
*/
|
|
4970
5402
|
export function dueCommitments({ libraryId, now = Date.now(), sessionId = null, limit = 3, skipIds = [], excludeIds = [], allCandidates = false, timeZone } = {}) {
|
|
4971
5403
|
if (!libraryId) return []
|
|
4972
|
-
const index =
|
|
5404
|
+
const index = readPrivateIndex(libraryId)
|
|
4973
5405
|
const skip = new Set([...(skipIds || []), ...(excludeIds || [])])
|
|
4974
5406
|
const reminders = []
|
|
4975
5407
|
for (const [id, entry] of Object.entries(index.entries || {})) {
|
|
@@ -4986,7 +5418,7 @@ export function dueCommitments({ libraryId, now = Date.now(), sessionId = null,
|
|
|
4986
5418
|
reminders.sort((a, b) => String(a.dueAt).localeCompare(String(b.dueAt))
|
|
4987
5419
|
|| String(a.entry.updatedAt || a.entry.createdAt || '').localeCompare(String(b.entry.updatedAt || b.entry.createdAt || ''))
|
|
4988
5420
|
|| a.id.localeCompare(b.id))
|
|
4989
|
-
return allCandidates ? reminders : reminders.slice(0, Math.max(0, Number(limit) || 0))
|
|
5421
|
+
return structuredClone(allCandidates ? reminders : reminders.slice(0, Math.max(0, Number(limit) || 0)))
|
|
4990
5422
|
}
|
|
4991
5423
|
|
|
4992
5424
|
/**
|
|
@@ -5005,7 +5437,7 @@ export function dueCommitments({ libraryId, now = Date.now(), sessionId = null,
|
|
|
5005
5437
|
*/
|
|
5006
5438
|
export function cueCandidates({ libraryId, sessionId = null, now = Date.now(), minAgeHours = 12, skipIds = [], limit = 8 }) {
|
|
5007
5439
|
if (!libraryId) return []
|
|
5008
|
-
const index =
|
|
5440
|
+
const index = readPrivateIndex(libraryId)
|
|
5009
5441
|
const skip = new Set(skipIds || [])
|
|
5010
5442
|
const minAgeMs = Math.max(0, Number(minAgeHours) || 0) * 3_600_000
|
|
5011
5443
|
return Object.entries(index.entries || {})
|
|
@@ -5032,4 +5464,5 @@ export function cueCandidates({ libraryId, sessionId = null, now = Date.now(), m
|
|
|
5032
5464
|
.sort((a, b) => a.weight - b.weight || String(b.entry.updatedAt || b.entry.createdAt || '')
|
|
5033
5465
|
.localeCompare(String(a.entry.updatedAt || a.entry.createdAt || '')))
|
|
5034
5466
|
.slice(0, Math.max(0, Number(limit) || 0))
|
|
5467
|
+
.map(row => ({ ...row, entry: structuredClone(row.entry) }))
|
|
5035
5468
|
}
|