dsh-memu-memory 1.3.7 → 1.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +58 -0
  3. package/README.md +7 -7
  4. package/README.zh.md +7 -7
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/contributing.md +2 -2
  7. package/docs/memory-semantics.md +7 -6
  8. package/docs/troubleshooting.md +74 -7
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/client.js +150 -81
  11. package/lib/consolidation-ledger.js +6 -2
  12. package/lib/inbound.js +24 -9
  13. package/lib/inject.js +379 -215
  14. package/lib/memory.js +704 -181
  15. package/lib/paths.js +24 -0
  16. package/lib/private.js +242 -132
  17. package/lib/rpc.js +53 -6
  18. package/lib/snippet.js +49 -28
  19. package/lib/state.js +185 -26
  20. package/lib/tools.js +137 -28
  21. package/lib/webui.js +25 -1
  22. package/lib/worker-pool.js +260 -26
  23. package/package.json +1 -1
  24. package/scripts/check-i18n.mjs +19 -0
  25. package/scripts/recall-bench.mjs +4 -4
  26. package/scripts/simulate-injection.mjs +3 -0
  27. package/tests/activity-wiring.test.mjs +52 -0
  28. package/tests/client-render.test.mjs +207 -0
  29. package/tests/consolidation-feed.test.mjs +26 -0
  30. package/tests/consolidation-fork.test.mjs +587 -26
  31. package/tests/cross-library-recall.test.mjs +156 -0
  32. package/tests/cue.test.mjs +15 -2
  33. package/tests/hybrid-recall.test.mjs +488 -0
  34. package/tests/inbound.test.mjs +49 -4
  35. package/tests/inject-conflict.test.mjs +70 -9
  36. package/tests/inject-guide.test.mjs +13 -1
  37. package/tests/inject.test.mjs +10 -0
  38. package/tests/injection-budget.test.mjs +101 -0
  39. package/tests/injection-chain.test.mjs +37 -0
  40. package/tests/injection-rollback.test.mjs +172 -9
  41. package/tests/issue2-chain.test.mjs +169 -0
  42. package/tests/lexicon-inject.test.mjs +33 -5
  43. package/tests/managed-memory.test.mjs +625 -1
  44. package/tests/media.test.mjs +1 -1
  45. package/tests/new-session-gate.test.mjs +280 -25
  46. package/tests/open-loop-date.test.mjs +11 -1
  47. package/tests/recall-intent.test.mjs +52 -3
  48. package/tests/simulate-injection.test.mjs +4 -4
  49. package/tests/snippet.test.mjs +33 -1
  50. package/tests/state.test.mjs +8 -3
  51. package/tests/tool-schema.test.mjs +52 -0
  52. package/tests/tools.test.mjs +394 -0
  53. package/tests/webui.test.mjs +16 -2
  54. package/tests/worker-lifecycle.test.mjs +419 -36
package/lib/rpc.js CHANGED
@@ -19,14 +19,14 @@ import { statsView } from './stats.js'
19
19
  import { recallCacheStats } from './recall-cache.js'
20
20
  import { getMemuConfig, saveMemuConfig, setEmbeddingSource, testMemuConfig, getSummaryConfig, getVisionConfig } from './memu-config.js'
21
21
  import { getLocalVectorState, downloadLocalVectorModel, installLocalVectorRuntime, selectLocalVectorModel, switchLocalVectorProfile, rollbackLocalVectorProfile, abortLocalVectorMigration, testLocalVector } from './local-vector-service.js'
22
- import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAsset, SETTINGS_PATH } from './webui.js'
22
+ import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAssetResponse, SETTINGS_PATH } from './webui.js'
23
23
  import { getGraph, listEntities, createEntity, confirmEntities, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, purgeAutoLinks, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
24
24
  import { generateAnchorCandidates, resetAnchorCandidatesCache } from './auto-link/candidates.js'
25
25
  import { refreshPrivateAutoLinks } from './private-links.js'
26
26
  import { refreshEntityMentions } from './auto-link/apply.js'
27
27
  import { clearSuppression, suppressionSet } from './auto-link/suppression.js'
28
28
  import { getAttachment, attachmentThumbnail, attachmentPreview, exportMediaBundle, importMediaBundle, streamMediaExport, importMediaStream } from './media.js'
29
- import { listEvents, logStats, clearEvents } from './activity-log.js'
29
+ import { listEvents, logStats, clearEvents, record } from './activity-log.js'
30
30
  import { redactSecrets, warn } from './paths.js'
31
31
  import { ALL_LEXICON_ID, GLOBAL_LEXICON_ID } from './lexicon.js'
32
32
  import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
@@ -670,6 +670,27 @@ async function decorateLogRows(ctx, rows) {
670
670
 
671
671
  // 侧边栏"整理提醒"的数据源:跨会话(不按当前对话过滤),失败/成功两列分开,
672
672
  // 每列只取最新 limit 条。失败的行带会话标题与库名,客户端用它挂跳转按钮。
673
+ function consolidationMeasurementView(measurement) {
674
+ if (measurement?.schemaVersion !== 2) return null
675
+ const number = value => Number.isFinite(value) && value >= 0 ? value : null
676
+ const values = (source, keys) => Object.fromEntries(keys.map(key => [key, number(source?.[key])]))
677
+ const usage = values(measurement.usage, ['inputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'outputTokens', 'reasoningTokens', 'requests'])
678
+ usage.source = measurement.usage?.source === 'assistant/message.data.usage' ? measurement.usage.source : 'unavailable'
679
+ usage.totalInputTokens = ['inputTokens', 'cacheReadTokens', 'cacheWriteTokens'].every(key => usage[key] !== null)
680
+ ? usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens : null
681
+ return {
682
+ schemaVersion: 2,
683
+ measurementVersion: number(measurement.measurementVersion),
684
+ packet: measurement.packet ? { ...values(measurement.packet, ['inputChars', 'estimatedTokens']),
685
+ kind: ['fork', 'handoff', 'increment', 'wrapup'].includes(measurement.packet.kind) ? measurement.packet.kind : null } : null,
686
+ dispatched: values(measurement.dispatched, ['inputChars', 'estimatedTokens', 'followups', 'wrapupChars']),
687
+ observed: values(measurement.observed, ['outputTextChars', 'toolArgumentsChars', 'toolResultsChars', 'reasoningChars', 'estimatedTokens']),
688
+ usage,
689
+ serializationErrors: number(measurement.serializationErrors),
690
+ logicalToolCalls: number(measurement.logicalToolCalls),
691
+ }
692
+ }
693
+
673
694
  async function consolidationFeed(ctx, payload = {}) {
674
695
  const perColumn = Math.max(1, Math.min(20, Number(payload?.limit) || 6))
675
696
  const rows = await decorateLogRows(ctx, listEvents({ kind: 'consolidate', limit: 80 }))
@@ -679,6 +700,8 @@ async function consolidationFeed(ctx, payload = {}) {
679
700
  timedOut: detail?.timedOut === true,
680
701
  count: detail?.count ?? null,
681
702
  force: detail?.force === true,
703
+ runner: ['fork', 'worker'].includes(detail?.runner) ? detail.runner : null,
704
+ measurement: consolidationMeasurementView(detail?.measurement),
682
705
  })
683
706
  return {
684
707
  failures: rows.filter(row => row.ok === false).slice(0, perColumn).map(slim),
@@ -1221,7 +1244,21 @@ async function dispatch(ctx, endpoint, payload = {}) {
1221
1244
  if (domain !== null && !allowed.includes(domain) && !String(domain || '').startsWith('project:')) {
1222
1245
  throw new Error('invalid domain')
1223
1246
  }
1224
- return bindingView(setSessionBinding(sessionId, { domainOverride: domain }))
1247
+ // 显式答案(弹窗确认或侧栏选择器)留下 chosen 凭据:gate 见到它就不再问
1248
+ // (issue #2 缺陷 2 的另一半——隐式绑定与显式绑定从此可区分)。
1249
+ return bindingView(setSessionBinding(sessionId, { domainOverride: domain, domainSource: 'chosen' }))
1250
+ }
1251
+ case 'logClientEvent': {
1252
+ // WebUI 客户端侧的错误上报(issue #2):弹窗未渲染时组件 state 里的错误
1253
+ // 谁也看不见,落进活动日志才可发现。本路由永不抛错——日志失败不能雪上加霜。
1254
+ const message = String(payload?.message || 'client event').slice(0, 400)
1255
+ return { entry: record({
1256
+ kind: payload?.kind === 'error' ? 'error' : 'system',
1257
+ level: 'warn',
1258
+ sessionId: typeof payload?.sessionId === 'string' && payload.sessionId.trim() ? payload.sessionId.trim() : null,
1259
+ message,
1260
+ detail: payload?.detail == null ? null : String(payload.detail).slice(0, 2000),
1261
+ }) }
1225
1262
  }
1226
1263
  case 'setLibrary': {
1227
1264
  const sessionId = requireSessionId(payload)
@@ -2205,10 +2242,20 @@ export function registerRpc(ctx) {
2205
2242
  return
2206
2243
  }
2207
2244
  if (req.method === 'GET' && pathname.startsWith('/dsh-memu-memory/ui-assets/')) {
2208
- const asset = standaloneAsset(pathname)
2245
+ const asset = standaloneAssetResponse(pathname, req.headers?.['if-none-match'] || null)
2209
2246
  const type = pathname.endsWith('.png') ? 'image/png' : pathname.endsWith('.svg') ? 'image/svg+xml' : 'application/javascript; charset=utf-8'
2210
- res.writeHead(asset === null ? 404 : 200, { 'Content-Type': type, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' })
2211
- res.end(asset || '')
2247
+ if (asset === null) {
2248
+ res.writeHead(404, { 'Content-Type': type, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' })
2249
+ res.end('')
2250
+ return
2251
+ }
2252
+ if (asset.notModified) {
2253
+ res.writeHead(304, { 'Cache-Control': 'no-cache', ETag: asset.etag, 'X-Content-Type-Options': 'nosniff' })
2254
+ res.end()
2255
+ return
2256
+ }
2257
+ res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-cache', ETag: asset.etag, 'X-Content-Type-Options': 'nosniff' })
2258
+ res.end(asset.body)
2212
2259
  return
2213
2260
  }
2214
2261
  if (req.method === 'GET' && (pathname === SETTINGS_PATH || pathname === `${SETTINGS_PATH}/`)) {
package/lib/snippet.js CHANGED
@@ -7,6 +7,8 @@
7
7
  // hit instead — a little before it for context, more after it, because that is
8
8
  // the direction the answer usually continues in.
9
9
 
10
+ import { redactSecrets } from './paths.js'
11
+
10
12
  const ELLIPSIS = '…'
11
13
 
12
14
  function escapeRegExp(value) {
@@ -48,23 +50,24 @@ export function firstHit(text, terms) {
48
50
  * the hit (default 40 / 120, per DESIGN). With no hit, or no query, this degrades
49
51
  * to a head cut of the same total width so callers never need two code paths.
50
52
  */
51
- export function centeredSnippet(text, query, { before = 40, after = 120 } = {}) {
53
+ export function centeredSnippetWindow(text, query, { before = 40, after = 120 } = {}) {
52
54
  const body = String(text ?? '')
55
+ const points = Array.from(body)
53
56
  const width = Math.max(1, before + after)
54
- if (body.length <= width + 1) return body
55
- const terms = queryTerms(query)
56
- const hit = firstHit(body, terms)
57
- if (hit < 0) return body.slice(0, width) + ELLIPSIS
58
- const start = Math.max(0, hit - before)
59
- const end = Math.min(body.length, start + width)
60
- const head = start > 0 ? ELLIPSIS : ''
61
- const tail = end < body.length ? ELLIPSIS : ''
62
- return head + body.slice(start, end) + tail
57
+ const hit = firstHit(body, queryTerms(query))
58
+ // firstHit returns a UTF-16 index; pagination and slicing use code points.
59
+ const hitPoint = hit < 0 ? -1 : Array.from(body.slice(0, hit)).length
60
+ const start = points.length <= width || hitPoint < 0 ? 0 : Math.max(0, hitPoint - before)
61
+ const end = Math.min(points.length, start + width)
62
+ const truncated = start > 0 || end < points.length
63
+ return {
64
+ body: (start > 0 ? ELLIPSIS : '') + points.slice(start, end).join('') + (end < points.length ? ELLIPSIS : ''),
65
+ start, end, returnedChars: end - start, totalChars: points.length, truncated,
66
+ }
63
67
  }
64
68
 
65
- function clip(value, max) {
66
- const text = String(value ?? '').replace(/\s+/g, ' ').trim()
67
- return text.length <= max ? text : text.slice(0, Math.max(0, max - 1)) + ELLIPSIS
69
+ export function centeredSnippet(text, query, options = {}) {
70
+ return centeredSnippetWindow(text, query, options).body
68
71
  }
69
72
 
70
73
  /**
@@ -84,21 +87,39 @@ function observedOf(entry) {
84
87
  return String(entry?.observed_at || entry?.updatedAt || entry?.createdAt || '')
85
88
  }
86
89
 
87
- export function conflictCard({ factKey, left, right } = {}) {
88
- if (!left?.id || !right?.id) return ''
89
- const side = (item, label) => {
90
+ export function conflictCard({ factKey, left, right, members = null, maxChars = 200, titleChars = 40 } = {}) {
91
+ if (!members && (!left?.id || !right?.id)) return ''
92
+ const ordered = (members || [left, right]).filter(item => item?.id).slice().sort((a, b) => Number(a.available === false) - Number(b.available === false)
93
+ || authorityOf(b.entry) - authorityOf(a.entry) || observedOf(b.entry).localeCompare(observedOf(a.entry)) || String(a.id).localeCompare(String(b.id)))
94
+ if (!ordered.length) return ''
95
+ const cut = (value, count) => {
96
+ const points = Array.from(redactSecrets(value).replace(/\s+/g, ' ').trim())
97
+ return points.length <= count ? points.join('') : count > 0 ? points.slice(0, count - 1).join('') + ELLIPSIS : ''
98
+ }
99
+ const titles = ordered.map(item => item.available === false ? '' : item.entry?.title || item.entry?.content || '(untitled)')
100
+ const widths = titles.map(title => Math.min(titleChars, Array.from(title).length))
101
+ const flags = ordered.map(item => {
102
+ if (item.available === false) return ''
90
103
  const entry = item.entry || {}
91
- const title = entry.title || entry.content || '(untitled)'
92
- const date = entry.absolute_date ? `(${entry.absolute_date})` : ''
93
- return `- ${label} [${item.id}] ${clip(title, 40)}${date}`
104
+ const source = entry.source || 'inferred'
105
+ return [source !== 'inferred' ? `source=${source}` : '', entry.source_kind && entry.source_kind !== source ? `source_kind=${entry.source_kind}` : '',
106
+ entry.disclosure && entry.disclosure !== 'can_tell' ? `disclosure=${entry.disclosure}` : '',
107
+ entry.speaker_id ? `speaker=${entry.speaker_id}` : ''].filter(Boolean).map(value => redactSecrets(value)).join(' · ')
108
+ })
109
+ const render = header => [`冲突 · ${header}`, ...ordered.map((item, i) => {
110
+ const label = String.fromCharCode(65 + i)
111
+ if (item.available === false) return `- ${label} 另有不可见/不可用版本`
112
+ const date = item.entry?.absolute_date ? `(${redactSecrets(item.entry.absolute_date)})` : ''
113
+ const title = cut(titles[i], widths[i])
114
+ return `- ${label} [${item.id}]${title ? ' ' + title : ''}${date}${flags[i] ? ' · ' + flags[i] : ''}`
115
+ }), '- 未确认哪版为准'].join('\n')
116
+ let header = cut(factKey || '同一事实', 60)
117
+ let text = render(header)
118
+ while (Array.from(text).length > maxChars && widths.some(width => width > 0)) {
119
+ const largest = widths.indexOf(Math.max(...widths))
120
+ widths[largest] -= 1
121
+ text = render(header)
94
122
  }
95
- const ordered = [left, right].sort((a, b) => authorityOf(b.entry) - authorityOf(a.entry)
96
- || observedOf(b.entry).localeCompare(observedOf(a.entry))
97
- || String(a.id).localeCompare(String(b.id)))
98
- return clip([
99
- `冲突 · ${clip(factKey || '同一事实', 60)}`,
100
- side(ordered[0], 'A'),
101
- side(ordered[1], 'B'),
102
- '- 未确认哪版为准',
103
- ].join('\n'), 200)
123
+ if (Array.from(text).length > maxChars) { header = '同一事实'; text = render(header) }
124
+ return Array.from(text).length <= maxChars ? text : ''
104
125
  }
package/lib/state.js CHANGED
@@ -2,7 +2,7 @@ import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import crypto from 'node:crypto'
4
4
  import {
5
- dataDir, librariesDir, indexDir, backupsDir,
5
+ dataDir, librariesDir, indexDir, backupsDir, memoryRefKey,
6
6
  ensureDir, readJson, readFailure, readFailuresUnder, writeJson, withFileLock, assertJsonShape, warn, stamp, shortHash, libraryIdForScope, isSafeId,
7
7
  } from './paths.js'
8
8
  import {
@@ -822,7 +822,16 @@ export function getSessionBinding(sessionId) {
822
822
  export function setSessionBinding(sessionId, patch) {
823
823
  return updateState((state) => {
824
824
  const previous = state.sessions[sessionId] || {}
825
- state.sessions[sessionId] = { ...previous, ...(patch || {}) }
825
+ const next = { ...previous, ...(patch || {}) }
826
+ for (const key of ['lastInjectedUserMessageId', 'guideRulesKey', 'guideMessageAt', 'anchorPushed']) {
827
+ if (!Object.hasOwn(patch || {}, key)) continue
828
+ next.injectionOwners = { ...(next.injectionOwners || {}), [key]: `legacy:${crypto.randomUUID()}` }
829
+ }
830
+ const scopeFields = ['libraryId', 'scopeKey', 'memoryContext', 'useLibrary', 'useGlobal', 'domainOverride']
831
+ if (scopeFields.some(key => Object.hasOwn(patch || {}, key) && JSON.stringify(previous[key]) !== JSON.stringify(next[key]))) {
832
+ next.scopeGeneration = Number(previous.scopeGeneration || 0) + 1
833
+ }
834
+ state.sessions[sessionId] = next
826
835
  return state
827
836
  }).sessions[sessionId]
828
837
  }
@@ -887,10 +896,11 @@ export function ensureSession(sessionId, { cwd, agentPreset, libraryId = null, c
887
896
  useGlobal: wantsGlobal,
888
897
  scopeKey,
889
898
  domain: existing?.domain || detectDomain({ agentPreset, cwd }),
890
- // Memory starts on RP unless this conversation already chose a domain. The
891
- // selector writes an explicit `general` instead of null, so "general" remains
892
- // a real choice rather than falling back to detection.
893
- domainOverride: existing?.domainOverride ?? 'rp',
899
+ // 未被问过的新会话不再硬编码 RP 兜底(issue #2 缺陷 2):领域跟随 detectDomain
900
+ // 的文件夹/预设判定,与上方 domain 字段同一口径。弹窗或侧栏写下的显式答案会
901
+ // 覆盖这里,并留下 domainSource:'chosen' 作为「已答」的凭据。
902
+ domainOverride: existing?.domainOverride ?? detectDomain({ agentPreset, cwd }),
903
+ domainSource: existing?.domainSource ?? 'auto',
894
904
  injectedIds: existing?.injectedIds || [],
895
905
  injectedAt: existing?.injectedAt || {},
896
906
  lastInjectedTurn: existing?.lastInjectedTurn ?? 0,
@@ -912,6 +922,91 @@ export function deleteSessionBinding(sessionId) {
912
922
  })
913
923
  }
914
924
 
925
+ // Only typed, host-admitted records prove content identity. Legacy bare ids do not.
926
+ export function recentMemoryRefs(binding, memoryClock, dedupeTurns) {
927
+ const window = Number(dedupeTurns)
928
+ const clock = Number(memoryClock)
929
+ if (!(window > 0) || !Number.isFinite(clock)) return []
930
+ const latest = new Map()
931
+ const revoked = new Set(binding?.revokedInjectionMessages || [])
932
+ for (const record of binding?.acceptedMemoryMessages || []) {
933
+ if (record.generation !== Number(binding.scopeGeneration || 0)
934
+ || record.epoch !== Number(binding.injectionEpoch || 0) || revoked.has(record.messageId)) continue
935
+ for (const ref of record.refs || []) {
936
+ const key = memoryRefKey(ref)
937
+ const previous = latest.get(key)
938
+ if (!previous || record.memoryClock >= previous.clock) latest.set(key, { ref, clock: record.memoryClock })
939
+ }
940
+ }
941
+ return [...latest.values()].filter(item => item.clock <= clock && clock - item.clock < window)
942
+ .map(item => ({ ...item.ref }))
943
+ }
944
+
945
+ /** Commit one immutable message after its exact body entered host history. No entry bodies. */
946
+ export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
947
+ if (!sessionId || typeof options.messageId !== 'string' || !Number.isFinite(Number(memoryClock))) return null
948
+ let committed = null
949
+ updateState(state => {
950
+ const binding = state.sessions[sessionId]
951
+ if (!binding) return state
952
+ const records = binding.acceptedMemoryMessages || []
953
+ if (records.some(record => record.messageId === options.messageId)) return state
954
+ const generation = Number(options.generation ?? binding.scopeGeneration ?? 0)
955
+ const epoch = Number(options.epoch ?? binding.injectionEpoch ?? 0)
956
+ if (generation !== Number(binding.scopeGeneration || 0) || epoch !== Number(binding.injectionEpoch || 0)) return state
957
+ const typed = (refs || []).filter(ref => ref && ['private', 'global'].includes(ref.scope)
958
+ && typeof ref.id === 'string' && typeof ref.revision === 'string'
959
+ && (ref.scope === 'global' || typeof ref.libraryId === 'string'))
960
+ .map(ref => ({ scope: ref.scope, libraryId: ref.libraryId ?? null, id: ref.id, revision: ref.revision,
961
+ ...(ref.groupKey !== undefined ? { groupKey: ref.groupKey } : {}),
962
+ ...(ref.groupRevision !== undefined ? { groupRevision: ref.groupRevision } : {}) }))
963
+ committed = { messageId: options.messageId, hostTurn: options.hostTurn ?? null, generation, epoch,
964
+ memoryClock: Number(memoryClock), refs: typed, admittedAt: stamp() }
965
+ const next = [...records, committed]
966
+ let count = next.reduce((sum, record) => sum + record.refs.length, 0)
967
+ while (next.length > 1 && (count > 400 || next.length > 400)) count -= next.shift().refs.length
968
+ if (count > 400) committed.refs = committed.refs.slice(-400)
969
+ binding.acceptedMemoryMessages = next
970
+ // Old anchor consumers retain their compatibility view, never a typed cooldown.
971
+ const ids = typed.map(ref => ref.id)
972
+ if ((binding.injectedIds || []).includes('__anchor__')) binding.anchorPushed = true
973
+ binding.injectedIds = [...new Set([...(binding.injectedIds || []).filter(id => id !== '__anchor__'), ...ids])].slice(-400)
974
+ binding.injectedAt = { ...(binding.injectedAt || {}) }
975
+ binding.injectionOwners = { ...(binding.injectionOwners || {}) }
976
+ binding.injectionOwnerClocks = { ...(binding.injectionOwnerClocks || {}) }
977
+ committed.effects = {}
978
+ const applyEffect = (key, value, field = key, id = null) => {
979
+ const owner = binding.injectionOwners[key]
980
+ const priorClock = typeof owner === 'string' && owner.startsWith('legacy:')
981
+ ? Math.max(Number(binding.lastInjectedTurn || 0), Number(binding.inbound?.clock || 0), Number(binding.injectionOwnerClocks[key] || 0))
982
+ : binding.injectionOwnerClocks[key] ?? records.find(record => record.messageId === owner)?.memoryClock ?? -1
983
+ if (Number(priorClock) > Number(memoryClock)) return
984
+ const previous = id === null ? binding[field] : binding[field]?.[id]
985
+ committed.effects[key] = { value: structuredClone(previous), owner: binding.injectionOwners[key] ?? null,
986
+ clock: binding.injectionOwnerClocks[key] ?? null, field, id }
987
+ if (id === null) binding[field] = structuredClone(value)
988
+ else binding[field] = { ...(binding[field] || {}), [id]: structuredClone(value) }
989
+ binding.injectionOwners[key] = options.messageId
990
+ binding.injectionOwnerClocks[key] = Number(memoryClock)
991
+ }
992
+ for (const id of ids) applyEffect(`id:${id}`, Number(memoryClock), 'injectedAt', id)
993
+ const actions = structuredClone(options.actions || {})
994
+ const patch = actions.patch || {}
995
+ if (actions.anchor) { patch.anchorPushed = true; patch.reinjectPending = false }
996
+ if (actions.cue) patch.activeCue = { id: String(actions.cue.id), text: String(actions.cue.text || '').slice(0, 500),
997
+ sourceId: actions.cue.sourceId ? String(actions.cue.sourceId) : null,
998
+ recallQuery: actions.cue.recallQuery ? String(actions.cue.recallQuery).slice(0, 200) : null, createdAt: stamp() }
999
+ if (actions.lexicon?.selected?.length) patch.lexiconInjectionClock = Number(memoryClock)
1000
+ for (const [key, value] of Object.entries(patch)) applyEffect(key, value)
1001
+ for (const [id, day] of Object.entries(actions.anniversaries || {})) applyEffect(`anniversary:${id}`, day, 'anniversariesShown', id)
1002
+ for (const id of actions.nudgeIds || []) applyEffect(`nudge:${id}`, stamp(), 'openLoopRemindedAt', id)
1003
+ binding.lastInjectedTurn = Math.max(Number(binding.lastInjectedTurn || 0), Number(memoryClock))
1004
+ if (typed.length || actions.anchor) binding.lastInjectedAt = stamp()
1005
+ return state
1006
+ })
1007
+ return committed ? structuredClone(committed) : null
1008
+ }
1009
+
915
1010
  export function markInjected(sessionId, ids, turn) {
916
1011
  if (!sessionId) return
917
1012
  return updateState((state) => {
@@ -927,9 +1022,14 @@ export function markInjected(sessionId, ids, turn) {
927
1022
  ...incoming.filter((id) => id !== '__anchor__'),
928
1023
  ])]
929
1024
  binding.injectedIds = merged.slice(-400)
930
- if (anchor) binding.anchorPushed = true
1025
+ const owner = `legacy:${crypto.randomUUID()}`
1026
+ binding.injectionOwners = { ...(binding.injectionOwners || {}) }
1027
+ if (anchor) { binding.anchorPushed = true; binding.injectionOwners.anchorPushed = owner }
931
1028
  const at = { ...(binding.injectedAt || {}) }
932
- for (const id of incoming) at[id] = turn ?? Date.now()
1029
+ for (const id of incoming) {
1030
+ at[id] = turn ?? Date.now()
1031
+ binding.injectionOwners[`id:${id}`] = owner
1032
+ }
933
1033
  binding.injectedAt = at
934
1034
  binding.lastInjectedTurn = turn ?? binding.lastInjectedTurn ?? 0
935
1035
  // 主动记忆抑制要一个"最近一次真正注入了记忆"的墙钟时间;turn 号不能跨会话比较。
@@ -969,13 +1069,15 @@ export function releaseInjected(sessionId) { return updateState((state) => {
969
1069
  if (binding) {
970
1070
  binding.injectedIds = []
971
1071
  binding.injectedAt = {}
1072
+ binding.injectionEpoch = Number(binding.injectionEpoch || 0) + 1
972
1073
  }
973
1074
  return state
974
1075
  })
975
1076
  }
976
1077
 
977
1078
  export function markReinjectPending(sessionId) {
978
- return setSessionBinding(sessionId, { reinjectPending: true })
1079
+ const binding = getSessionBinding(sessionId)
1080
+ return setSessionBinding(sessionId, { reinjectPending: true, injectionEpoch: Number(binding?.injectionEpoch || 0) + 1 })
979
1081
  }
980
1082
 
981
1083
  export function clearReinjectPending(sessionId) {
@@ -1072,7 +1174,8 @@ export function markAnniversaryShown(sessionId, memoryId, dayKey) {
1072
1174
  // Keep only the current day's keys so the map cannot grow without bound.
1073
1175
  const fresh = Object.fromEntries(Object.entries(shown).filter(([, v]) => v === dayKey))
1074
1176
  fresh[memoryId] = dayKey
1075
- return setSessionBinding(sessionId, { anniversariesShown: fresh })
1177
+ return setSessionBinding(sessionId, { anniversariesShown: fresh,
1178
+ injectionOwners: { ...(binding?.injectionOwners || {}), [`anniversary:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
1076
1179
  }
1077
1180
 
1078
1181
  // ── repeated open loops ────────────────────────────────────────────────────────
@@ -1127,7 +1230,8 @@ export function markOpenLoopReminded(sessionId, memoryId, at = new Date()) {
1127
1230
  const when = at instanceof Date ? at : new Date(at)
1128
1231
  const reminded = prunedOpenLoopReminded(sessionId, when)
1129
1232
  reminded[memoryId] = when.toISOString()
1130
- return setSessionBinding(sessionId, { openLoopRemindedAt: reminded })
1233
+ return setSessionBinding(sessionId, { openLoopRemindedAt: reminded,
1234
+ injectionOwners: { ...(getSessionBinding(sessionId)?.injectionOwners || {}), [`nudge:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
1131
1235
  }
1132
1236
 
1133
1237
  /**
@@ -1145,6 +1249,11 @@ export function recordInjectionRollback(sessionId, { hostTurn, ids = [], guideKe
1145
1249
  const same = previous && previous.hostTurn === turn ? previous : { ids: [], nudgeIds: [], anniversaryIds: [] }
1146
1250
  binding.injectionRollback = {
1147
1251
  hostTurn: turn,
1252
+ epoch: Number(binding.injectionEpoch || 0),
1253
+ generation: Number(binding.scopeGeneration || 0),
1254
+ snapshot: { owners: { ...binding.injectionOwners }, injectedAt: { ...binding.injectedAt }, anchorPushed: binding.anchorPushed,
1255
+ lastInjectedUserMessageId: binding.lastInjectedUserMessageId, guideMessageAt: binding.guideMessageAt,
1256
+ anniversariesShown: { ...binding.anniversariesShown }, openLoopRemindedAt: { ...binding.openLoopRemindedAt } },
1148
1257
  ids: [...new Set([...(same.ids || []), ...ids])].slice(-400),
1149
1258
  nudgeIds: [...new Set([...(same.nudgeIds || []), ...nudgeIds])].slice(-40),
1150
1259
  anniversaryIds: [...new Set([...(same.anniversaryIds || []), ...anniversaryIds])].slice(-40),
@@ -1162,30 +1271,80 @@ export function recordInjectionRollback(sessionId, { hostTurn, ids = [], guideKe
1162
1271
  * 转录实证判定(inject.js 的 injectionAdmissions),所以走到这里的内容确实没进转录,
1163
1272
  * 下一轮重投不会出现第二份。返回撤回了什么,供活动日志留信号。
1164
1273
  */
1165
- export function rollbackInjectionForTurn(sessionId, hostTurn) {
1274
+ export function rollbackInjectionForTurn(sessionId, hostTurn, { messageIds = [], epoch = null } = {}) {
1166
1275
  const turn = Number(hostTurn)
1167
1276
  if (!sessionId || !Number.isSafeInteger(turn)) return null
1168
1277
  let rolled = null
1169
1278
  updateState((state) => {
1170
1279
  const binding = state.sessions[sessionId]
1171
- const record = binding?.injectionRollback
1172
- if (!binding || !record || record.hostTurn !== turn) return state
1173
- const ids = new Set(record.ids || [])
1174
- if (ids.size) {
1175
- binding.injectedIds = (binding.injectedIds || []).filter((id) => !ids.has(id))
1176
- if (binding.injectedAt) for (const id of ids) delete binding.injectedAt[id]
1280
+ if (!binding) return state
1281
+ // Explicit host rollback evidence can revoke individual accepted messages. A model
1282
+ // request failure alone must never call this branch. Preserve immutable records.
1283
+ const targets = (binding.acceptedMemoryMessages || []).filter(record => record.hostTurn === turn
1284
+ && messageIds.includes(record.messageId) && (epoch === null || record.epoch === epoch))
1285
+ for (const accepted of targets.reverse()) {
1286
+ binding.revokedInjectionMessages = [...new Set([...(binding.revokedInjectionMessages || []), accepted.messageId])].slice(-400)
1287
+ if (accepted.epoch !== Number(binding.injectionEpoch || 0) || accepted.generation !== Number(binding.scopeGeneration || 0)) continue
1288
+ for (const [key, saved] of Object.entries(accepted.effects || {})) {
1289
+ if (binding.injectionOwners?.[key] !== accepted.messageId) continue
1290
+ let previous = saved
1291
+ const visited = new Set()
1292
+ while (previous.owner && binding.revokedInjectionMessages.includes(previous.owner) && !visited.has(previous.owner)) {
1293
+ visited.add(previous.owner)
1294
+ const revoked = (binding.acceptedMemoryMessages || []).find(record => record.messageId === previous.owner)
1295
+ previous = revoked?.effects?.[key] || { ...previous, value: undefined, owner: null, clock: null }
1296
+ }
1297
+ const field = previous.field || key
1298
+ if (previous.id !== undefined && previous.id !== null) {
1299
+ if (previous.value === undefined) delete binding[field]?.[previous.id]
1300
+ else binding[field] = { ...(binding[field] || {}), [previous.id]: structuredClone(previous.value) }
1301
+ if (field === 'injectedAt' && previous.value === undefined) binding.injectedIds = (binding.injectedIds || []).filter(id => id !== previous.id)
1302
+ } else if (previous.value === undefined) delete binding[field]
1303
+ else binding[field] = structuredClone(previous.value)
1304
+ if (previous.owner) binding.injectionOwners[key] = previous.owner
1305
+ else delete binding.injectionOwners[key]
1306
+ if (previous.clock !== undefined && previous.clock !== null) binding.injectionOwnerClocks[key] = previous.clock
1307
+ else delete binding.injectionOwnerClocks?.[key]
1308
+ }
1309
+ for (const ref of accepted.refs) {
1310
+ if (accepted.effects?.[`id:${ref.id}`] || binding.injectionOwners?.[`id:${ref.id}`] !== accepted.messageId) continue
1311
+ delete binding.injectedAt?.[ref.id]
1312
+ binding.injectedIds = (binding.injectedIds || []).filter(id => id !== ref.id)
1313
+ delete binding.injectionOwners[`id:${ref.id}`]
1314
+ }
1315
+ for (const key of Object.keys(binding.injectionOwners || {})) {
1316
+ if (binding.injectionOwners[key] !== accepted.messageId) continue
1317
+ if (key.startsWith('anniversary:')) delete binding.anniversariesShown?.[key.slice(12)]
1318
+ if (key.startsWith('nudge:')) delete binding.openLoopRemindedAt?.[key.slice(6)]
1319
+ delete binding.injectionOwners[key]
1320
+ }
1177
1321
  }
1178
- // 哨兵已不再进 injectedIds,必须单独撤掉它的"已投"标记,否则回滚后锚点不再重投。
1179
- if (ids.has('__anchor__')) delete binding.anchorPushed
1180
- // 这一轮注入没进转录,宿主重试时同一条用户消息会再送一次 pre-step:
1181
- // 清掉「一消息一投」标记,让重试还能正常注入。
1182
- delete binding.lastInjectedUserMessageId
1183
- if (record.guideKey && binding.guideRulesKey === record.guideKey) {
1322
+ if (targets.length) rolled = { ids: targets.flatMap(record => record.refs.map(ref => ref.id)), guideKey: null, anniversaries: 0, nudges: 0 }
1323
+ const record = binding.injectionRollback
1324
+ if (!record || record.hostTurn !== turn) return state
1325
+ const snapshot = record.snapshot || {}
1326
+ const owners = binding.injectionOwners || {}
1327
+ const sameEpoch = record.epoch === Number(binding.injectionEpoch || 0)
1328
+ && Number(record.generation || 0) === Number(binding.scopeGeneration || 0)
1329
+ const owns = key => owners[key] === snapshot.owners?.[key] && (!owners[key] || owners[key].startsWith('legacy:'))
1330
+ const ids = new Set((record.ids || []).filter(id => sameEpoch && owns(`id:${id}`)
1331
+ && binding.injectedAt?.[id] === snapshot.injectedAt?.[id]))
1332
+ binding.injectedIds = (binding.injectedIds || []).filter(id => !ids.has(id))
1333
+ if (binding.injectedAt) for (const id of ids) delete binding.injectedAt[id]
1334
+ if (sameEpoch && ids.has('__anchor__') && owns('anchorPushed') && binding.anchorPushed === snapshot.anchorPushed) delete binding.anchorPushed
1335
+ if (sameEpoch && snapshot.lastInjectedUserMessageId !== undefined && owns('lastInjectedUserMessageId')
1336
+ && binding.lastInjectedUserMessageId === snapshot.lastInjectedUserMessageId) delete binding.lastInjectedUserMessageId
1337
+ if (sameEpoch && owns('guideRulesKey') && record.guideKey && binding.guideRulesKey === record.guideKey
1338
+ && binding.guideMessageAt === snapshot.guideMessageAt) {
1184
1339
  delete binding.guideRulesKey
1185
1340
  delete binding.guideMessageAt
1186
1341
  }
1187
- if (binding.anniversariesShown) for (const id of record.anniversaryIds || []) delete binding.anniversariesShown[id]
1188
- if (binding.openLoopRemindedAt) for (const id of record.nudgeIds || []) delete binding.openLoopRemindedAt[id]
1342
+ if (sameEpoch && binding.anniversariesShown) for (const id of record.anniversaryIds || []) {
1343
+ if (owns(`anniversary:${id}`) && binding.anniversariesShown[id] === snapshot.anniversariesShown?.[id]) delete binding.anniversariesShown[id]
1344
+ }
1345
+ if (sameEpoch && binding.openLoopRemindedAt) for (const id of record.nudgeIds || []) {
1346
+ if (owns(`nudge:${id}`) && binding.openLoopRemindedAt[id] === snapshot.openLoopRemindedAt?.[id]) delete binding.openLoopRemindedAt[id]
1347
+ }
1189
1348
  rolled = {
1190
1349
  ids: [...ids],
1191
1350
  guideKey: record.guideKey || null,