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/inject.js
CHANGED
|
@@ -21,6 +21,8 @@ import { readMood } from './mood.js'
|
|
|
21
21
|
import { jaccard } from './text-similarity.js'
|
|
22
22
|
import { loadPromptForDomain } from './prompts.js'
|
|
23
23
|
import { estTokens, packToBudget, truncateToTokens } from './budget.js'
|
|
24
|
+
import { createTurnTokenLedger } from './token-measurement.js'
|
|
25
|
+
import { recordDiagnostic, recordErrorDiagnostic } from './diagnostics.js'
|
|
24
26
|
import { freshnessSignals } from './freshness.js'
|
|
25
27
|
import { hasTemporalHint } from './temporal.js'
|
|
26
28
|
import { conflictCard } from './snippet.js'
|
|
@@ -29,13 +31,13 @@ import { redactSecrets, warn, memoryRef } from './paths.js'
|
|
|
29
31
|
import {
|
|
30
32
|
INBOUND_TYPE, ingestInboundBatch, observeInboundEvent, hasPendingInbound, pendingInbound,
|
|
31
33
|
noteNativeUserMessages, finishInbound, nextMemoryClock, advanceMemoryClock, releaseInboundSession,
|
|
32
|
-
nativeInboundMessage, inboundUserTexts,
|
|
34
|
+
nativeInboundMessage, inboundUserTexts, selectRecallableInbound,
|
|
33
35
|
} from './inbound.js'
|
|
34
36
|
import {
|
|
35
37
|
lexiconAnchorLines, cooldownAndBudget, lexiconRecordHits, lexiconMarkInjected,
|
|
36
38
|
lexiconTurnLine,
|
|
37
39
|
} from './lexicon.js'
|
|
38
|
-
import { lexiconHitLibraryId,
|
|
40
|
+
import { lexiconHitLibraryId, recallLexicon, lexiconScopeAllowed, lexiconVisibleTerms } from './lexicon-scope.js'
|
|
39
41
|
|
|
40
42
|
const ANCHOR_SENTINEL = '__anchor__'
|
|
41
43
|
const PLUGIN = 'dsh-memu-memory'
|
|
@@ -692,9 +694,9 @@ export function buildAnchor(binding, settings = getSettings(), sessionId = null)
|
|
|
692
694
|
}
|
|
693
695
|
|
|
694
696
|
// ── lexicon(P1,docs/memory-semantics.md §8.13)──────────────────────────────────
|
|
695
|
-
// 词典是锚点里的一节紧凑摘要 +
|
|
697
|
+
// 词典是锚点里的一节紧凑摘要 + 用户消息词面/概念命中时的一小段 B 通道,两者都服从既有的
|
|
696
698
|
// totalRoom()/injectionTotalTokens 预算,异常一律 fail-open(logger.warn +
|
|
697
|
-
// binding.lastRecallError
|
|
699
|
+
// binding.lastRecallError),绝不影响记忆召回本身。概念腿独立于记忆 corpus/MMR。
|
|
698
700
|
const LEXICON_ANCHOR_TOKEN_CAP = 300
|
|
699
701
|
|
|
700
702
|
/**
|
|
@@ -740,7 +742,7 @@ export function buildLexiconAnchor(binding, sessionId = null, cap = LEXICON_ANCH
|
|
|
740
742
|
}
|
|
741
743
|
|
|
742
744
|
/**
|
|
743
|
-
* B 通道(§3.3
|
|
745
|
+
* B 通道(§3.3 / 施工 §9):用户消息词面或概念命中词条 → term→meaning,每回合最多
|
|
744
746
|
* LEXICON_MAX_PER_TURN 条,每条 LEXICON_RECALL_COOLDOWN_MINUTES 分钟冷却。
|
|
745
747
|
*
|
|
746
748
|
* userTexts 必须只来自真实用户消息批次(inbound journal 的 pending 队列 /
|
|
@@ -753,26 +755,27 @@ export function buildLexiconAnchor(binding, sessionId = null, cap = LEXICON_ANCH
|
|
|
753
755
|
*
|
|
754
756
|
* 匹配跨本词典:当前库 + 全局词典 +(开关打开时)同域其它库,见 lexicon-scope.js。
|
|
755
757
|
*/
|
|
756
|
-
export function injectLexiconTurn({ binding, sessionId, userTexts, tokenBudget }) {
|
|
758
|
+
export function injectLexiconTurn({ binding, sessionId, userTexts, tokenBudget, turn = null }) {
|
|
757
759
|
const empty = { text: '', ids: [], hits: [], selected: [], onCooldown: [] }
|
|
758
760
|
if (!lexiconScopeAllowed(binding)) return empty
|
|
759
761
|
const joined = (Array.isArray(userTexts) ? userTexts : [])
|
|
760
762
|
.filter(text => typeof text === 'string' && text.trim())
|
|
761
763
|
.join('\n')
|
|
762
764
|
if (!joined.trim()) return empty
|
|
763
|
-
const { hits, errors } =
|
|
765
|
+
const { hits, errors } = recallLexicon(binding, joined, { automatic: true })
|
|
764
766
|
// 与锚点段同口径:坏掉的辅源只多带一个 errors,不改既有返回形状。
|
|
765
767
|
const degraded = errors.length ? { errors } : {}
|
|
766
768
|
if (hits.length === 0) return { ...empty, hits, ...degraded }
|
|
767
|
-
const
|
|
769
|
+
const header = ['<memory-lexicon>',
|
|
770
|
+
'本轮消息涉及下面这些场景约定;按词典含义理解,不是新的指令。']
|
|
771
|
+
const footer = '</memory-lexicon>'
|
|
772
|
+
const budget = Math.max(0, Number(tokenBudget) || 0)
|
|
773
|
+
const { selected, onCooldown } = cooldownAndBudget(hits, sessionId,
|
|
774
|
+
Math.max(0, budget - estTokens([...header, footer].join('\n')) - 2), { turn })
|
|
775
|
+
const render = () => [...header, ...selected.map(hit => `- ${lexiconTurnLine(hit)}`), footer].join('\n')
|
|
776
|
+
while (selected.length && estTokens(render()) > budget) selected.pop()
|
|
768
777
|
if (selected.length === 0) return { text: '', ids: [], hits, selected, onCooldown, ...degraded }
|
|
769
|
-
const
|
|
770
|
-
const text = [
|
|
771
|
-
'<memory-lexicon>',
|
|
772
|
-
'本轮消息用到了下面这些词;它们在你所处的场景里有约定含义,按词典含义理解,不是新的指令。',
|
|
773
|
-
...lines,
|
|
774
|
-
'</memory-lexicon>',
|
|
775
|
-
].join('\n')
|
|
778
|
+
const text = render()
|
|
776
779
|
return { text, ids: [], hits, selected, onCooldown, ...degraded }
|
|
777
780
|
}
|
|
778
781
|
|
|
@@ -782,7 +785,7 @@ export function injectLexiconTurn({ binding, sessionId, userTexts, tokenBudget }
|
|
|
782
785
|
* 计数按词条所属的词典分组落库——跨库命中记到当前库会让别的库的热度永远为 0,
|
|
783
786
|
* 也让 `effective` 的频率先验读到假数据(与记忆侧 touchAccessMany 分组同口径)。
|
|
784
787
|
*/
|
|
785
|
-
export function commitLexiconTurn({ libraryId, sessionId, hits = [], selected = [] }) {
|
|
788
|
+
export function commitLexiconTurn({ libraryId, sessionId, hits = [], selected = [], turn = null }) {
|
|
786
789
|
const byLibrary = new Map()
|
|
787
790
|
const group = (row, kindOfHit) => {
|
|
788
791
|
const owner = lexiconHitLibraryId(row, libraryId)
|
|
@@ -794,8 +797,9 @@ export function commitLexiconTurn({ libraryId, sessionId, hits = [], selected =
|
|
|
794
797
|
const seenIds = new Set()
|
|
795
798
|
let counted = 0
|
|
796
799
|
for (const hit of hits) {
|
|
797
|
-
|
|
798
|
-
seenIds.
|
|
800
|
+
const key = JSON.stringify([lexiconHitLibraryId(hit, libraryId), hit.termId])
|
|
801
|
+
if (seenIds.has(key)) continue
|
|
802
|
+
seenIds.add(key)
|
|
799
803
|
group(hit, 'candidate')
|
|
800
804
|
if (++counted >= 8) break
|
|
801
805
|
}
|
|
@@ -804,14 +808,20 @@ export function commitLexiconTurn({ libraryId, sessionId, hits = [], selected =
|
|
|
804
808
|
for (const [owner, sets] of byLibrary) {
|
|
805
809
|
const candidateIds = [...sets.candidate]
|
|
806
810
|
if (candidateIds.length) {
|
|
807
|
-
try { lexiconRecordHits(owner, candidateIds, 'candidate') } catch {
|
|
811
|
+
try { lexiconRecordHits(owner, candidateIds, 'candidate') } catch (error) {
|
|
812
|
+
warn(`lexicon candidate accounting failed: ${error?.message || error}`)
|
|
813
|
+
if (sessionId) setRecallError(sessionId, 'lexicon candidate accounting failed')
|
|
814
|
+
}
|
|
808
815
|
}
|
|
809
816
|
if (!sets.injection.size) continue
|
|
810
817
|
const injectionIds = [...sets.injection]
|
|
811
|
-
try { lexiconRecordHits(owner, injectionIds, 'injection') } catch {
|
|
818
|
+
try { lexiconRecordHits(owner, injectionIds, 'injection') } catch (error) {
|
|
819
|
+
warn(`lexicon injection accounting failed: ${error?.message || error}`)
|
|
820
|
+
if (sessionId) setRecallError(sessionId, 'lexicon injection accounting failed')
|
|
821
|
+
}
|
|
812
822
|
}
|
|
813
823
|
// 冷却按会话记,与词条属于哪本库无关。
|
|
814
|
-
if (selected.length) lexiconMarkInjected(sessionId, selected.map(hit => hit.termId))
|
|
824
|
+
if (selected.length) lexiconMarkInjected(sessionId, selected.map(hit => hit.termId), Date.now(), { turn })
|
|
815
825
|
}
|
|
816
826
|
|
|
817
827
|
// ── compaction replay ─────────────────────────────────────────────────────────
|
|
@@ -1244,6 +1254,14 @@ export function createMemoryMessage(text) {
|
|
|
1244
1254
|
// 和第二个锚点;没实证(配置无效、额度、取消发生在投放之前)才该把记账还回去。
|
|
1245
1255
|
// 证据只留在内存:进程重启后宁可什么都不做,也不要误投。
|
|
1246
1256
|
const injectionAdmissions = new Map()
|
|
1257
|
+
// Shared across first-step, inbound, guide and mid-turn proposals. Scope changes
|
|
1258
|
+
// and compaction do not replenish a turn's already reserved/accepted allowance.
|
|
1259
|
+
const turnTokenLedger = createTurnTokenLedger()
|
|
1260
|
+
const turnTokenLimit = () => Math.max(0, Number(getSettings().injectionTotalTokens ?? 2000))
|
|
1261
|
+
const turnTokenRoom = (sessionId, turn) => turnTokenLedger.room(sessionId, turn, turnTokenLimit())
|
|
1262
|
+
export function injectionTokenDiagnostics(sessionId, turn) {
|
|
1263
|
+
return turnTokenLedger.snapshot(sessionId, turn, turnTokenLimit())
|
|
1264
|
+
}
|
|
1247
1265
|
// 会话级「本进程已经投过锚点」的兜底。不落盘:重启后再发一次是可接受的代价,
|
|
1248
1266
|
// 比因为接纳回调不生效而每步重发要好得多。压缩时清空(与 reinjectPending 同步)。
|
|
1249
1267
|
const anchorSeen = new Set()
|
|
@@ -1320,7 +1338,9 @@ function liteInjectionActions(actions = {}) {
|
|
|
1320
1338
|
|
|
1321
1339
|
function proposeInjection(sessionId, hostTurn, message, refs, memoryClock, actions, key, projection = [], beforeUserId = null) {
|
|
1322
1340
|
const binding = getSessionBinding(sessionId)
|
|
1323
|
-
if (!binding || !message?.id) return
|
|
1341
|
+
if (!binding || !message?.id) return false
|
|
1342
|
+
// Final synchronous reservation closes races between independently awaited blocks.
|
|
1343
|
+
if (!turnTokenLedger.reserve(sessionId, hostTurn, message.id, messageText(message), turnTokenLimit())) return false
|
|
1324
1344
|
const map = injectionAdmissions.get(sessionId) || new Map()
|
|
1325
1345
|
const copiedActions = structuredClone(actions || {})
|
|
1326
1346
|
if (copiedActions.lexicon) for (const kind of ['hits', 'selected']) {
|
|
@@ -1344,11 +1364,14 @@ function proposeInjection(sessionId, hostTurn, message, refs, memoryClock, actio
|
|
|
1344
1364
|
turn: stored.turn, clock: memoryClock, generation: stored.generation, epoch: stored.epoch,
|
|
1345
1365
|
refs: stored.refs, actions: liteInjectionActions(copiedActions) })
|
|
1346
1366
|
} catch {}
|
|
1367
|
+
return true
|
|
1347
1368
|
}
|
|
1348
1369
|
|
|
1349
1370
|
function reuseProposal(decision, proposal, hostTurn = null) {
|
|
1350
1371
|
if (!proposal) return decision
|
|
1351
|
-
|
|
1372
|
+
const nextTurn = hostTurn !== null && Number.isFinite(Number(hostTurn)) ? Math.max(proposal.turn, Number(hostTurn)) : proposal.turn
|
|
1373
|
+
if (!turnTokenLedger.reserve(proposal.sessionId, nextTurn, proposal.message.id, messageText(proposal.message), turnTokenLimit())) return decision
|
|
1374
|
+
proposal.turn = nextTurn
|
|
1352
1375
|
const binding = getSessionBinding(proposal.sessionId)
|
|
1353
1376
|
const messages = [...decision.messages]
|
|
1354
1377
|
const ids = new Set(messages.map(message => message.id))
|
|
@@ -1451,6 +1474,7 @@ function observeInjectionMessage(sessionId, message, log) {
|
|
|
1451
1474
|
})
|
|
1452
1475
|
if (!accepted) return noteInjectionReject(sessionId, 'commit-refused')
|
|
1453
1476
|
proposal.status = 'admitted'
|
|
1477
|
+
turnTokenLedger.admit(sessionId, proposal.turn, message.id)
|
|
1454
1478
|
// 跨进程补认成功后把提案放回内存:同一消息再被观察(宿主重放、事件回环)
|
|
1455
1479
|
// 走 admitted→true,而不是凭据已删后的 proposal-missing 误报警。
|
|
1456
1480
|
if (proposal.fromStore) {
|
|
@@ -1471,12 +1495,21 @@ function observeInjectionMessage(sessionId, message, log) {
|
|
|
1471
1495
|
for (const [libraryId, ids] of libraries) noteInjected({ libraryId, ids: [...ids] })
|
|
1472
1496
|
noteGlobalInjected({ ids: [...new Set(accepted.refs.filter(ref => ref.scope === 'global').map(ref => ref.id))] })
|
|
1473
1497
|
if (actions.lexicon && (!actions.lexicon.selected?.length || accepted.effects.lexiconInjectionClock)) {
|
|
1474
|
-
commitLexiconTurn({ libraryId: proposal.snapshot.libraryId, sessionId, ...actions.lexicon })
|
|
1498
|
+
commitLexiconTurn({ libraryId: proposal.snapshot.libraryId, sessionId, ...actions.lexicon, turn: proposal.turn })
|
|
1475
1499
|
}
|
|
1476
1500
|
} catch (error) { log?.(`accepted injection accounting failed: ${error?.message || error}`) }
|
|
1477
1501
|
if (actions.inbound) {
|
|
1478
|
-
finishInbound(sessionId, actions.inbound.keys, proposal.memoryClock, { ...actions.inbound.outcome, admitted: true })
|
|
1479
|
-
|
|
1502
|
+
const finished = finishInbound(sessionId, actions.inbound.keys, proposal.memoryClock, { ...actions.inbound.outcome, admitted: true })
|
|
1503
|
+
const done = new Set(finished || [])
|
|
1504
|
+
// finishInbound only clears items the host has proven are native-admitted. For the rest
|
|
1505
|
+
// we KEEP the process-local served mark (adding it when this path never set one): dropping
|
|
1506
|
+
// it left the same batch eligible on the next step, which is how one human turn ended up
|
|
1507
|
+
// with two memory blocks recalled from two different queries.
|
|
1508
|
+
for (const key of actions.inbound.keys) {
|
|
1509
|
+
const mark = proposal.turn + '|' + key
|
|
1510
|
+
if (done.has(key)) servedInbound.get(sessionId)?.delete(mark)
|
|
1511
|
+
else servedSet(servedInbound, sessionId).add(mark)
|
|
1512
|
+
}
|
|
1480
1513
|
}
|
|
1481
1514
|
record({ kind: 'system', scope: 'private', sessionId, libraryId: proposal.snapshot.libraryId, ok: true,
|
|
1482
1515
|
message: '记忆消息已进入宿主历史(不代表模型已收到)', detail: { messageId: message.id, turn: proposal.turn, status: 'admitted', refs: accepted.refs.length } })
|
|
@@ -1490,6 +1523,7 @@ function finishInjectionTurn(sessionId, hostTurn, kind, log) {
|
|
|
1490
1523
|
turnClosures.set(sessionId, closures)
|
|
1491
1524
|
while (turnClosures.size > 128) turnClosures.delete(turnClosures.keys().next().value)
|
|
1492
1525
|
const map = injectionAdmissions.get(sessionId)
|
|
1526
|
+
turnTokenLedger.finish(sessionId, hostTurn)
|
|
1493
1527
|
if (!map) return
|
|
1494
1528
|
let discarded = 0
|
|
1495
1529
|
const abandoned = []
|
|
@@ -1688,6 +1722,8 @@ function resetSessionOneShots(sessionId, stamp, reason) {
|
|
|
1688
1722
|
lastInjectedUserMessageId: undefined,
|
|
1689
1723
|
})
|
|
1690
1724
|
clearInjectionSeen(sessionId)
|
|
1725
|
+
turnTokenLedger.clear(sessionId)
|
|
1726
|
+
midTurnMarks.delete(sessionId)
|
|
1691
1727
|
record({
|
|
1692
1728
|
kind: 'system',
|
|
1693
1729
|
scope: 'private',
|
|
@@ -1820,9 +1856,9 @@ function ensureUnifiedGuide(ctx, payload, decision) {
|
|
|
1820
1856
|
const hostMessage = memoryBlock || humanMessage(next)
|
|
1821
1857
|
const guideAt = hostMessage ? next.indexOf(hostMessage) + 1 : next.length
|
|
1822
1858
|
next.splice(guideAt, 0, guideMessage)
|
|
1823
|
-
proposeInjection(sessionId, payload?.turn, guideMessage, [], Number(binding.inbound?.clock || payload?.turn || 0), {
|
|
1859
|
+
if (!proposeInjection(sessionId, payload?.turn, guideMessage, [], Number(binding.inbound?.clock || payload?.turn || 0), {
|
|
1824
1860
|
patch: { guideRulesKey: guide.key, guideMessageAt: new Date().toISOString(), guideLost: false },
|
|
1825
|
-
}, proposalKey, next)
|
|
1861
|
+
}, proposalKey, next)) return decision
|
|
1826
1862
|
record({
|
|
1827
1863
|
kind: 'system',
|
|
1828
1864
|
scope: 'private',
|
|
@@ -1836,6 +1872,8 @@ function ensureUnifiedGuide(ctx, payload, decision) {
|
|
|
1836
1872
|
return { ...decision, messages: next }
|
|
1837
1873
|
} catch (error) {
|
|
1838
1874
|
try { ctx.logger?.warn?.(`dsh-memu-memory: guide message skipped: ${error?.message || error}`) } catch {}
|
|
1875
|
+
recordErrorDiagnostic(error, { code: 'INJECTION_GUIDE_FAILED', source: 'pre-step', operation: 'guide', alert: false,
|
|
1876
|
+
context: { sessionId: payload?.agent?.session?.header?.id, turn: payload?.turn, step: payload?.step } })
|
|
1839
1877
|
return decision
|
|
1840
1878
|
}
|
|
1841
1879
|
}
|
|
@@ -1859,7 +1897,8 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1859
1897
|
// 进程内批次键去重:同一批外部输入在本次进程里只投一次。宿主接纳回调不来时,
|
|
1860
1898
|
// Delayed admission callbacks leave pending state uncleared, so process-local guards prevent repetition.
|
|
1861
1899
|
const servedKey = (key) => `${turn}|${key}`
|
|
1862
|
-
const
|
|
1900
|
+
const recallableKeys = new Set(selectRecallableInbound(getSessionBinding(sessionId), decision.messages).map(item => item.key))
|
|
1901
|
+
const batch = waiting.filter(item => recallableKeys.has(item.key) && !proposedKeys.has(item.key)
|
|
1863
1902
|
&& servedInbound.get(sessionId)?.has(servedKey(item.key)) !== true)
|
|
1864
1903
|
if (signal?.aborted) return decision
|
|
1865
1904
|
// 空批不等于没事可做:这一步可能带着一条人类消息,而锚点/规则是一次性的。旧代码
|
|
@@ -1901,8 +1940,9 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1901
1940
|
finishInbound(sessionId, keys, clock, { reason: 'scope', injectedCount: 0 })
|
|
1902
1941
|
return decision
|
|
1903
1942
|
}
|
|
1904
|
-
const
|
|
1905
|
-
const
|
|
1943
|
+
const recallBatch = admissible.filter(item => !item.memoryAdmission)
|
|
1944
|
+
const images = recallBatch.flatMap(item => imageTurn(item).images)
|
|
1945
|
+
const query = truncateToTokens(recallBatch.map(item => {
|
|
1906
1946
|
const text = imageTurn(item).query
|
|
1907
1947
|
return [item.context.channelId, item.context.speakerId, text].filter(Boolean).join(' ')
|
|
1908
1948
|
}).join('\n'), 300)
|
|
@@ -1931,7 +1971,7 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1931
1971
|
if (guideAdmission(getSessionBinding(sessionId), decision?.messages, guide.key) === 'replace'
|
|
1932
1972
|
&& guide.tokens <= totalBudget) guideReserve = guide.tokens
|
|
1933
1973
|
} catch {}
|
|
1934
|
-
const effectiveTotalBudget = Math.max(0, totalBudget - guideReserve)
|
|
1974
|
+
const effectiveTotalBudget = Math.max(0, Math.min(totalBudget, turnTokenRoom(sessionId, turn)) - guideReserve)
|
|
1935
1975
|
const totalRoom = () => Math.max(0, effectiveTotalBudget - estTokens(parts.join('\n\n')) - (parts.length ? 2 : 0))
|
|
1936
1976
|
const appendBounded = (text, candidateIds = [], candidateRefs = []) => {
|
|
1937
1977
|
if (!text || estTokens(text) > totalRoom()) return false
|
|
@@ -1965,7 +2005,7 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1965
2005
|
if (appendBounded(formatted.text)) representedMediaIds = formatted.occurrenceIds
|
|
1966
2006
|
}
|
|
1967
2007
|
// B 通道文本源:本批 admissible 的真实用户消息(已过 scope/context 准入)。
|
|
1968
|
-
const lexiconUserTexts =
|
|
2008
|
+
const lexiconUserTexts = recallBatch.map(item => imageTurn(item).query).filter(Boolean)
|
|
1969
2009
|
let outcome = 'anchor-only'
|
|
1970
2010
|
let errors = []
|
|
1971
2011
|
const minInboundChars = Math.max(1, Math.min(Number(settings.minUserChars ?? 6), 2))
|
|
@@ -1993,7 +2033,7 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1993
2033
|
// 不会被发出去的文本记 injection/冷却。
|
|
1994
2034
|
if (settings.autoInject !== 'anchor-only' && lexiconScopeAllowed(effective)) {
|
|
1995
2035
|
try {
|
|
1996
|
-
const lexTurn = injectLexiconTurn({ binding: effective, sessionId, userTexts: lexiconUserTexts, tokenBudget: totalRoom() })
|
|
2036
|
+
const lexTurn = injectLexiconTurn({ binding: effective, sessionId, userTexts: lexiconUserTexts, tokenBudget: totalRoom(), turn })
|
|
1997
2037
|
if (lexTurn.errors?.length) lexiconError = [lexiconError, `degraded lexicon sources: ${lexTurn.errors.join('; ')}`].filter(Boolean).join('; ')
|
|
1998
2038
|
if (lexTurn.text && estTokens(lexTurn.text) <= totalRoom()) {
|
|
1999
2039
|
parts.push(lexTurn.text)
|
|
@@ -2022,12 +2062,12 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
2022
2062
|
if (text) {
|
|
2023
2063
|
inboundMessage = createMemoryMessage(text)
|
|
2024
2064
|
const anchorPushed = anchorNeeded && Boolean(parts[0]?.startsWith('===== memory anchor'))
|
|
2025
|
-
if (
|
|
2026
|
-
proposeInjection(sessionId, turn, inboundMessage, refs, clock, {
|
|
2065
|
+
if (!proposeInjection(sessionId, turn, inboundMessage, refs, clock, {
|
|
2027
2066
|
anchor: anchorPushed, lexicon: lexiconTurnCommit,
|
|
2028
2067
|
media: { scope: mediaScope, occurrenceIds: representedMediaIds },
|
|
2029
2068
|
inbound: { keys, outcome: { reason: outcome, injectedCount: refs.length } },
|
|
2030
|
-
}, proposalKey, decision.messages)
|
|
2069
|
+
}, proposalKey, decision.messages)) return decision
|
|
2070
|
+
if (anchorPushed) anchorSeen.add(sessionId)
|
|
2031
2071
|
setSessionBinding(sessionId, { lastInboundOutcome: { reason: outcome, status: 'proposed', injectedCount: 0, proposedCount: refs.length, count: keys.length, at: new Date().toISOString() } })
|
|
2032
2072
|
} else {
|
|
2033
2073
|
advanceMemoryClock(sessionId, clock)
|
|
@@ -2117,16 +2157,18 @@ async function maybeMidTurnRecall({ agent, decision, turn, step, ctx, log = null
|
|
|
2117
2157
|
const clock = nextMemoryClock(binding, turn)
|
|
2118
2158
|
const note = `[回合中途补充 · 这不是用户新说的话 · 本回合已跑 ${currentStep} 步]`
|
|
2119
2159
|
const full = state.units >= policy.fullUnits && state.chars >= policy.fullChars
|
|
2160
|
+
const remaining = turnTokenRoom(sessionId, turn)
|
|
2161
|
+
const recallBudget = Math.max(0, Math.min(policy.tokens, remaining - estTokens(note + '\n') - 2))
|
|
2120
2162
|
let text = null
|
|
2121
2163
|
let refs = []
|
|
2122
|
-
if (full) {
|
|
2164
|
+
if (full && recallBudget >= 120) {
|
|
2123
2165
|
const query = truncateToTokens(evidence.text, 300)
|
|
2124
2166
|
if (!query) return decision
|
|
2125
2167
|
try {
|
|
2126
2168
|
const recall = await buildRecall(effective, query, clock,
|
|
2127
|
-
{ ...settings, turnTokens:
|
|
2169
|
+
{ ...settings, turnTokens: recallBudget }, { agent }, sessionId, {})
|
|
2128
2170
|
if (recall.errors?.length) setRecallError(sessionId, recall.errors.join('; '))
|
|
2129
|
-
if (recall.text && estTokens(recall.text) <=
|
|
2171
|
+
if (recall.text && estTokens(recall.text) <= recallBudget) {
|
|
2130
2172
|
text = [note, recall.text].join('\n')
|
|
2131
2173
|
refs = recall.refs || []
|
|
2132
2174
|
}
|
|
@@ -2139,9 +2181,10 @@ async function maybeMidTurnRecall({ agent, decision, turn, step, ctx, log = null
|
|
|
2139
2181
|
text = [note, '如果你需要更早的上下文,可以调用 memu_private_recall 按关键词查。'].join('\n')
|
|
2140
2182
|
}
|
|
2141
2183
|
if (!injectionSnapshotIsCurrent(sessionId, snapshot, settings.autoInject)) return decision
|
|
2142
|
-
|
|
2184
|
+
// A hint is still a complete plugin message; never slice its semantic markers.
|
|
2185
|
+
if (estTokens(text) > turnTokenRoom(sessionId, turn)) return decision
|
|
2143
2186
|
const message = createMemoryMessage(text)
|
|
2144
|
-
proposeInjection(sessionId, turn, message, refs, clock, { patch: {} }, `mid:${turn}:${currentStep}`, decision.messages)
|
|
2187
|
+
if (!proposeInjection(sessionId, turn, message, refs, clock, { patch: {} }, `mid:${turn}:${currentStep}`, decision.messages)) return decision
|
|
2145
2188
|
state.injections += 1
|
|
2146
2189
|
state.lastStep = currentStep
|
|
2147
2190
|
state.lastAt = Date.now()
|
|
@@ -2207,7 +2250,7 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
2207
2250
|
// noteNativeUserMessages 把原生消息摘出 pending 之前取;插件消息的 source.kind
|
|
2208
2251
|
// 是 `plugin:dsh-memu-memory`,工具结果/assistant 自言自语根本不是 user 角色,
|
|
2209
2252
|
// 所以这个并集里没有可供误命中的非用户文本。
|
|
2210
|
-
const lexiconUserTexts = [...new Set([...inboundUserTexts(binding),
|
|
2253
|
+
const lexiconUserTexts = [...new Set([...inboundUserTexts(binding, decision.messages),
|
|
2211
2254
|
...decision.messages.filter(message => message?.role === 'user' && message?.source?.kind === 'user')
|
|
2212
2255
|
.map(message => messageText(message)).filter(Boolean)])]
|
|
2213
2256
|
const native = decision.messages.filter(message => message?.role === 'user' && message.source?.kind === 'user' && message.id)
|
|
@@ -2274,7 +2317,7 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
2274
2317
|
if (guideAdmission(getSessionBinding(sessionId), decision?.messages, guide.key) === 'replace'
|
|
2275
2318
|
&& guide.tokens <= totalInjectionBudget) guideReserve = guide.tokens
|
|
2276
2319
|
} catch {}
|
|
2277
|
-
const injectionBudget = Math.max(0, totalInjectionBudget - guideReserve)
|
|
2320
|
+
const injectionBudget = Math.max(0, Math.min(totalInjectionBudget, turnTokenRoom(sessionId, turn)) - guideReserve)
|
|
2278
2321
|
const totalRoom = () => Math.max(0, injectionBudget - estTokens(parts.join('\n\n')) - (parts.length ? 2 : 0))
|
|
2279
2322
|
// Proposals reserve represented IDs; persistent consumption waits for host admission.
|
|
2280
2323
|
if (imageCount && effective.useLibrary) {
|
|
@@ -2403,13 +2446,13 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
2403
2446
|
// B 通道(§3.3):用户消息命中词条 → term→meaning,最多 LEXICON_MAX_PER_TURN 条,
|
|
2404
2447
|
// 每条过冷却。刻意不受 tooShort 门控——"糖刀"这类两个字的词面命中恰恰是词典
|
|
2405
2448
|
// 的主场景,minUserChars 挡的是向量召回的成本,不是确定性词面检索。
|
|
2406
|
-
// fail-open:
|
|
2449
|
+
// fail-open:recallLexicon 抛错(含词典损坏的 typed error)只记 lexiconError。
|
|
2407
2450
|
// 记账(candidate/injection/冷却)推迟到 snapshot 复检通过之后:回合中途换了
|
|
2408
2451
|
// 库/上下文时整条消息都会被丢弃,不能给一段没发出去的文本记冷却。
|
|
2409
2452
|
let lexiconTurnCommit = null
|
|
2410
2453
|
if (!reinject && settings.autoInject !== 'anchor-only' && lexiconScopeAllowed(effective)) {
|
|
2411
2454
|
try {
|
|
2412
|
-
const lexTurn = injectLexiconTurn({ binding: effective, sessionId, userTexts: lexiconUserTexts, tokenBudget: totalRoom() })
|
|
2455
|
+
const lexTurn = injectLexiconTurn({ binding: effective, sessionId, userTexts: lexiconUserTexts, tokenBudget: totalRoom(), turn })
|
|
2413
2456
|
if (lexTurn.errors?.length) lexiconError = [lexiconError, `degraded lexicon sources: ${lexTurn.errors.join('; ')}`].filter(Boolean).join('; ')
|
|
2414
2457
|
if (lexTurn.text && estTokens(lexTurn.text) <= totalRoom()) {
|
|
2415
2458
|
parts.push(lexTurn.text)
|
|
@@ -2479,12 +2522,12 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
2479
2522
|
// 只改变这一批内部的顺序。
|
|
2480
2523
|
rewritten.splice(index + 1, 0, message)
|
|
2481
2524
|
deferredActions.anchor = ids.includes(ANCHOR_SENTINEL)
|
|
2482
|
-
if (deferredActions.anchor) anchorSeen.add(sessionId)
|
|
2483
2525
|
deferredActions.nudgeIds = recurringNudgeIds
|
|
2484
2526
|
deferredActions.lexicon = lexiconTurnCommit
|
|
2485
2527
|
deferredActions.patch.lastInjectedUserMessageId = lastUser.id
|
|
2486
2528
|
if (inboundKeys.length) deferredActions.inbound = { keys: inboundKeys, outcome: { reason: 'memory', injectedCount: refs.length } }
|
|
2487
|
-
proposeInjection(sessionId, turn, message, refs, memoryClock, deferredActions, proposalKey, rewritten, lastUser.id)
|
|
2529
|
+
if (!proposeInjection(sessionId, turn, message, refs, memoryClock, deferredActions, proposalKey, rewritten, lastUser.id)) return decision
|
|
2530
|
+
if (deferredActions.anchor) anchorSeen.add(sessionId)
|
|
2488
2531
|
// 进程内先记「已投」:接纳回调不来时,这就是唯一的幂等依据。
|
|
2489
2532
|
markHumanServed(sessionId, lastUser.id)
|
|
2490
2533
|
return { ...decision, messages: rewritten }
|
|
@@ -2528,6 +2571,8 @@ export function registerInjection(ctx) {
|
|
|
2528
2571
|
} catch (error) {
|
|
2529
2572
|
try { setRecallError(payload?.agent?.session?.header?.id, `injection failed: ${error?.message || error}`) } catch {}
|
|
2530
2573
|
try { ctx.logger?.warn?.(`dsh-memu-memory: pre-step injection failed (fail-open): ${error?.stack || error}`) } catch {}
|
|
2574
|
+
recordErrorDiagnostic(error, { code: 'INJECTION_PRE_STEP_FAILED', source: 'pre-step', operation: 'pre-step', alert: false,
|
|
2575
|
+
context: { sessionId: stepSessionId, libraryId: stepBinding?.libraryId, turn: payload?.turn, step: payload?.step } })
|
|
2531
2576
|
// 召回/入站故障不该把规则消息一起带走:guide 是独立 plugin 消息,照常尝试。
|
|
2532
2577
|
// 但回合已被关闭/替换时不能给旧回合提新提案,闭包判据与成功路径一致。
|
|
2533
2578
|
if (turnClosure(stepSessionId, payload?.turn) !== closure) return decision
|
|
@@ -2535,7 +2580,10 @@ export function registerInjection(ctx) {
|
|
|
2535
2580
|
}
|
|
2536
2581
|
if (turnClosure(stepSessionId, payload?.turn) !== closure) {
|
|
2537
2582
|
for (const [id, proposal] of injectionAdmissions.get(stepSessionId) || []) {
|
|
2538
|
-
if (proposal.turn === Number(payload?.turn) && proposal.status === 'proposed')
|
|
2583
|
+
if (proposal.turn === Number(payload?.turn) && proposal.status === 'proposed') {
|
|
2584
|
+
turnTokenLedger.release(stepSessionId, proposal.turn, id)
|
|
2585
|
+
injectionAdmissions.get(stepSessionId).delete(id)
|
|
2586
|
+
}
|
|
2539
2587
|
}
|
|
2540
2588
|
return decision
|
|
2541
2589
|
}
|
|
@@ -2565,12 +2613,27 @@ export function registerInjection(ctx) {
|
|
|
2565
2613
|
// Memory precedes the human in first-step projection. Both have to arrive.
|
|
2566
2614
|
noteNativeUserMessages(eventSessionId, [event.data], { admitted: true })
|
|
2567
2615
|
for (const proposal of injectionAdmissions.get(eventSessionId)?.values() || []) {
|
|
2568
|
-
if (proposal.status
|
|
2616
|
+
if (proposal.status !== 'admitted' || !proposal.actions?.inbound) continue
|
|
2617
|
+
// The host just proved these human messages reached history; now the batch can
|
|
2618
|
+
// leave pending and its process-local served mark can be dropped.
|
|
2619
|
+
const finished = finishInbound(eventSessionId,
|
|
2569
2620
|
proposal.actions.inbound.keys, proposal.memoryClock, { ...proposal.actions.inbound.outcome, admitted: true })
|
|
2621
|
+
for (const key of finished || []) servedInbound.get(eventSessionId)?.delete(proposal.turn + '|' + key)
|
|
2570
2622
|
}
|
|
2571
2623
|
}
|
|
2572
2624
|
}
|
|
2625
|
+
if (event?.type === 'assistant/message' && Number.isFinite(Number(event.data?.turn))) {
|
|
2626
|
+
turnTokenLedger.observeUsage(eventSessionId, event.data.turn, event)
|
|
2627
|
+
}
|
|
2573
2628
|
if (event?.type === 'turn/end') {
|
|
2629
|
+
const metrics = injectionTokenDiagnostics(eventSessionId, event.data?.turn)
|
|
2630
|
+
if (metrics.messages || metrics.requestUsage.requests) {
|
|
2631
|
+
const detail = { sessionId: eventSessionId, ...metrics }
|
|
2632
|
+
record({ kind: 'system', scope: 'private', sessionId: eventSessionId, ok: true,
|
|
2633
|
+
message: '记忆 token 预算观测 · actual=unverified', detail })
|
|
2634
|
+
recordDiagnostic({ level: 'info', scope: 'token-budget', code: 'MEMU_TOKEN_BUDGET', alert: false,
|
|
2635
|
+
message: 'Memory token budget observation', detail, source: 'injection-turn' })
|
|
2636
|
+
}
|
|
2574
2637
|
const failedSessionId = eventSessionId
|
|
2575
2638
|
const turnNumber = event?.data?.turn
|
|
2576
2639
|
const kind = event?.data?.reason?.kind
|
|
@@ -2585,6 +2648,8 @@ export function registerInjection(ctx) {
|
|
|
2585
2648
|
}
|
|
2586
2649
|
} catch (error) {
|
|
2587
2650
|
try { ctx.logger?.warn?.(`dsh-memu-memory: injection rollback check failed (fail-open): ${error?.message || error}`) } catch {}
|
|
2651
|
+
recordErrorDiagnostic(error, { code: 'INJECTION_ACCOUNTING_FAILED', source: 'injection-turn', operation: 'accounting', alert: false,
|
|
2652
|
+
context: { sessionId: session?.header?.id, kind: event?.type, turn: event?.data?.turn } })
|
|
2588
2653
|
}
|
|
2589
2654
|
try {
|
|
2590
2655
|
observeInboundEvent(ctx, session, event)
|
|
@@ -2612,12 +2677,16 @@ export function registerInjection(ctx) {
|
|
|
2612
2677
|
} catch (error) {
|
|
2613
2678
|
try { if (getSessionBinding(session?.header?.id)) setSessionBinding(session.header.id, { lastInboundError: redactSecrets(error?.message || error) }) } catch {}
|
|
2614
2679
|
try { ctx.logger?.warn?.(`dsh-memu-memory: session memory listener failed: ${redactSecrets(error?.message || error)}`) } catch {}
|
|
2680
|
+
recordErrorDiagnostic(error, { code: 'INJECTION_LISTENER_FAILED', source: 'session-event', operation: 'inbound', alert: false,
|
|
2681
|
+
context: { sessionId: session?.header?.id, kind: event?.type } })
|
|
2615
2682
|
}
|
|
2616
2683
|
})
|
|
2617
2684
|
disposers.push(offSession)
|
|
2618
2685
|
disposers.push(ctx.on('session/disposed', session => {
|
|
2619
2686
|
const id = session?.header?.id
|
|
2620
2687
|
injectionAdmissions.delete(id)
|
|
2688
|
+
turnTokenLedger.clear(id)
|
|
2689
|
+
midTurnMarks.delete(id)
|
|
2621
2690
|
nativeAdmissions.delete(id)
|
|
2622
2691
|
turnClosures.delete(id)
|
|
2623
2692
|
releaseInboundSession(id)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import crypto from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
export const LEXICON_DOCUMENT_VERSION = 'lexicon-term-alias-meaning-usage-examples-v1'
|
|
4
|
+
|
|
5
|
+
// Wrapping avoids interpreting an unrelated legacy entry.title as lexicon text.
|
|
6
|
+
export function lexiconDocumentText(document) {
|
|
7
|
+
const entry = document.lexicon
|
|
8
|
+
const title = [entry.term, ...(entry.aliases || [])].join(' ')
|
|
9
|
+
const body = [entry.meaning, entry.usage, ...(entry.examples || [])].filter(Boolean).join('\n')
|
|
10
|
+
return `${title} ${body}`
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Called with a newly admitted canonical snapshot, never per warm query. */
|
|
14
|
+
export function createLexiconRtSource(data) {
|
|
15
|
+
const entries = Object.create(null)
|
|
16
|
+
const digest = crypto.createHash('sha256').update(LEXICON_DOCUMENT_VERSION)
|
|
17
|
+
for (const [id, entry] of Object.entries(data.terms)) {
|
|
18
|
+
const document = { lexicon: entry }
|
|
19
|
+
entries[id] = document
|
|
20
|
+
// Counters, context and visibility are not document text. Fresh caller-side
|
|
21
|
+
// eligibility is reapplied even when this semantic revision stays unchanged.
|
|
22
|
+
digest.update(JSON.stringify([id, lexiconDocumentText(document)])).update('\n')
|
|
23
|
+
}
|
|
24
|
+
return { index: { entries }, revision: digest.digest('hex'), count: Object.keys(entries).length }
|
|
25
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { parentPort, workerData } from 'node:worker_threads'
|
|
2
|
+
import { createRtIndex } from './rt-index/reader.js'
|
|
3
|
+
import { LEXICON_DOCUMENT_VERSION, lexiconDocumentText } from './lexicon-rt-source.js'
|
|
4
|
+
|
|
5
|
+
process.env.DSH_MEMU_HOME = workerData.home
|
|
6
|
+
process.env.DSH_MEMU_MEMORY_HOME = workerData.home
|
|
7
|
+
try {
|
|
8
|
+
const { loadLexiconRtSource } = await import('./lexicon.js')
|
|
9
|
+
const source = loadLexiconRtSource(workerData.libraryId)
|
|
10
|
+
if (!source.count) {
|
|
11
|
+
parentPort.postMessage({ ok: true, skipped: true })
|
|
12
|
+
} else if (source.revision !== workerData.revision) {
|
|
13
|
+
parentPort.postMessage({ ok: false, code: 'RT_SOURCE_CHANGED', revision: source.revision })
|
|
14
|
+
} else {
|
|
15
|
+
const controller = createRtIndex({ directory: workerData.directory, libraryId: workerData.libraryId,
|
|
16
|
+
namespace: 'lexicon', mode: 'on', documentVersion: LEXICON_DOCUMENT_VERSION, documentText: lexiconDocumentText,
|
|
17
|
+
maxBuildBytes: 32 * 1024 * 1024, segmentDocs: 1024, logger: { warn() {} } })
|
|
18
|
+
const result = !workerData.force && controller.validate(source).ok ? { ok: true, skipped: true } : controller.rebuild(source)
|
|
19
|
+
const current = loadLexiconRtSource(workerData.libraryId)
|
|
20
|
+
if (current.revision !== source.revision) parentPort.postMessage({ ok: false, code: 'RT_SOURCE_CHANGED', revision: current.revision })
|
|
21
|
+
else parentPort.postMessage({ ok: result.ok, code: result.code, skipped: result.skipped === true })
|
|
22
|
+
}
|
|
23
|
+
} catch (error) {
|
|
24
|
+
// The canonical reader's failure is surfaced, never converted to an empty source.
|
|
25
|
+
parentPort.postMessage({ ok: false, code: /^LEXICON_/.test(error?.code || '') ? 'RT_CANONICAL_READ_FAILED' : 'RT_BUILD_FAILED' })
|
|
26
|
+
}
|