dsh-memu-memory 1.3.7 → 1.3.9

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 (63) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +70 -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/host-adaptation.md +1 -1
  8. package/docs/memory-semantics.md +7 -6
  9. package/docs/troubleshooting.md +74 -7
  10. package/lib/auto-link/decide.js +0 -4
  11. package/lib/binding-diagnostics.js +2 -2
  12. package/lib/client.js +150 -81
  13. package/lib/consolidation-ledger.js +6 -2
  14. package/lib/curator.js +42 -10
  15. package/lib/cycle.js +28 -3
  16. package/lib/inbound.js +24 -9
  17. package/lib/inject.js +379 -215
  18. package/lib/local-vector-service.js +1 -10
  19. package/lib/memory.js +704 -181
  20. package/lib/paths.js +24 -0
  21. package/lib/private.js +294 -134
  22. package/lib/rpc.js +53 -6
  23. package/lib/snippet.js +49 -28
  24. package/lib/state.js +185 -26
  25. package/lib/tools.js +137 -28
  26. package/lib/webui.js +25 -1
  27. package/lib/worker-pool.js +260 -26
  28. package/package.json +1 -1
  29. package/scripts/check-i18n.mjs +19 -0
  30. package/scripts/recall-bench.mjs +4 -4
  31. package/scripts/simulate-injection.mjs +3 -0
  32. package/tests/activity-wiring.test.mjs +52 -0
  33. package/tests/client-render.test.mjs +207 -0
  34. package/tests/consolidation-feed.test.mjs +26 -0
  35. package/tests/consolidation-fork.test.mjs +587 -26
  36. package/tests/cross-library-recall.test.mjs +156 -0
  37. package/tests/cue.test.mjs +15 -2
  38. package/tests/curator-contract.test.mjs +191 -0
  39. package/tests/curator-probe.test.mjs +5 -5
  40. package/tests/curator.test.mjs +3 -1
  41. package/tests/hybrid-recall.test.mjs +488 -0
  42. package/tests/inbound.test.mjs +49 -4
  43. package/tests/inject-conflict.test.mjs +70 -9
  44. package/tests/inject-guide.test.mjs +13 -1
  45. package/tests/inject.test.mjs +10 -0
  46. package/tests/injection-budget.test.mjs +101 -0
  47. package/tests/injection-chain.test.mjs +37 -0
  48. package/tests/injection-rollback.test.mjs +172 -9
  49. package/tests/issue2-chain.test.mjs +169 -0
  50. package/tests/lexicon-inject.test.mjs +33 -5
  51. package/tests/managed-memory.test.mjs +625 -1
  52. package/tests/media.test.mjs +1 -1
  53. package/tests/new-session-gate.test.mjs +280 -25
  54. package/tests/open-loop-date.test.mjs +11 -1
  55. package/tests/recall-intent.test.mjs +52 -3
  56. package/tests/regression-sweep.test.mjs +281 -0
  57. package/tests/simulate-injection.test.mjs +4 -4
  58. package/tests/snippet.test.mjs +33 -1
  59. package/tests/state.test.mjs +8 -3
  60. package/tests/tool-schema.test.mjs +52 -0
  61. package/tests/tools.test.mjs +394 -0
  62. package/tests/webui.test.mjs +16 -2
  63. package/tests/worker-lifecycle.test.mjs +419 -36
package/lib/cycle.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  deleteLibrary, restoreLibrary, normalizeCwd,
5
5
  } from './state.js'
6
6
  import { expireShortTerm } from './memory.js'
7
- import { requestPrivateConsolidation, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
7
+ import { requestPrivateConsolidation, archivedSessionIdsOf, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
8
8
  import { gcTurnLogs } from './turn-log.js'
9
9
  import { startGlobalCuration } from './curator.js'
10
10
  import { runVisibilityMigrationPass } from './migrate.js'
@@ -18,6 +18,11 @@ const SWEEP_MS = 5 * 60 * 1000
18
18
  // the fork needs, short enough that a user who opens the app and reads for a minute
19
19
  // still gets the catch-up before they type their next message.
20
20
  const STARTUP_SWEEP_MS = 8000
21
+ // 「inbound 队列非空就跳过整理」只该挡住「会话马上要进下一回合」的抢跑(issue #5)。
22
+ // 队列只在用户再次发言时才被排空(inject.js 在召回错误/abort/超预算时都会留下
23
+ // pending + 30s retryAt),一次召回异常 + 用户从此不再发言 = pending 永久残留。
24
+ // 所以只有队列非空 **且** 最近一次入站活动在热窗内才让路;凉掉的残骸不再永久阻断。
25
+ const INBOUND_PENDING_HOT_MS = 15 * 60 * 1000
21
26
 
22
27
  function liveAgent(ctx, sessionId) {
23
28
  try {
@@ -84,10 +89,16 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
84
89
  // not need a transcript read.
85
90
  let ledger = null
86
91
  try { ledger = loadLedger() } catch { ledger = null }
92
+ // 归档会话事前跳过(issue #4 缺陷 3):宿主会在 agent/pre-step 拒绝祖先含归档会话
93
+ // 的 subagent("the fork turn ended blocked"),撞两次就踩中 snapshot-failed 冻结。
94
+ // 在候选阶段直接 continue:不占 budget 名额、不计失败、不推进游标。空注册表 =
95
+ // 无成员信息,与 rpc.js 的读法一致,不当成「全是归档」。
96
+ const archived = archivedSessionIdsOf(ctx)
87
97
  const candidates = []
88
98
  for (const binding of listSessionBindings()) {
89
99
  if (binding.consolidationFork || !binding.lastTurnAt) continue
90
100
  if (binding.sessionGone) continue
101
+ if (archived?.size && archived.has(String(binding.sessionId))) continue
91
102
  const lastSleepAt = getLastSleepAt(binding.sessionId)
92
103
  const activeAt = Math.max(Date.parse(binding.lastTurnAt) || 0, Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastAgentIdleAt) || 0)
93
104
  const idle = now - activeAt >= idleMs
@@ -116,7 +127,12 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
116
127
  // Running includes a long-lived asynchronous tool. Waiting is not proof that
117
128
  // the conversation ended, and a fork should not race its active agent.
118
129
  if (liveAgent(ctx, binding.sessionId)?.status === 'running') continue
119
- if (binding.inbound?.pending?.length) continue
130
+ // Fresh inbound queue = a step may be about to race the fork. A queue that has
131
+ // gone cold (no inbound activity within INBOUND_PENDING_HOT_MS) is residue from
132
+ // a recall error that only the user's next message would drain — it must not
133
+ // block idle consolidation forever (issue #5).
134
+ const inboundFreshAt = Math.max(Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastInboundOutcome?.at) || 0)
135
+ if (binding.inbound?.pending?.length && now - inboundFreshAt < INBOUND_PENDING_HOT_MS) continue
120
136
  if ((Date.parse(binding.sleepRetryAt || '') || 0) > now) continue
121
137
  // Backlog first, then real idle, then cheap probes: a sweep with a limited
122
138
  // budget must not let probe-only sessions crowd out work that is actually due.
@@ -165,12 +181,21 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
165
181
  if (result.settled === false) {
166
182
  // 任何没结算的结果都要记探针时间,不只是「水位不足」那两种:low-score 也
167
183
  // 会读一遍转录并打分,不记就会在每次 5 分钟扫描里把同一段重读一遍。
184
+ // 后续:snapshot-failed 冻结回执带 cooldownUntil,可据此退避省去冻结期每扫
185
+ // 重读快照/种子;但不能直接写 sleepRetryAt——它不因新消息清零,会把冻结期
186
+ // 到来的新活动一并挡死,需「冻结感知且不惩罚新活动」的独立字段再做。
168
187
  setSessionBinding(binding.sessionId, { lastConsolidationProbeAt: new Date(now).toISOString() })
169
188
  log(`sleep consolidation deferred for ${binding.sessionId}: ${result.skipped || 'not settled'}`)
170
189
  continue
171
190
  }
172
191
  // Only cover activity this pass began with, not new messages during it.
173
- setLastSleepAt(binding.sessionId, binding.lastTurnAt)
192
+ // 多窗收口(issue #4 缺陷 2):`settled` 是「本窗完成」的语义,ledger 的
193
+ // lastSleepSeq 已随本窗回执推进(private.js advanceSleepCursor),不会重扫;
194
+ // 但粗游标 lastSleepAt 只有在整段(remaining === 0)扫完时才推平——否则
195
+ // 尾段 < 200 事件(backlog 够不着)的会话会在候选阶段 `!newActivity && !backlog` 处被永久跳过。
196
+ if (!(Number(result.remaining) > 0)) {
197
+ setLastSleepAt(binding.sessionId, binding.lastTurnAt)
198
+ }
174
199
  setSessionBinding(binding.sessionId, {
175
200
  sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null,
176
201
  lastConsolidationProbeAt: new Date(now).toISOString(),
package/lib/inbound.js CHANGED
@@ -71,7 +71,7 @@ export function nativeInboundMessage(message) {
71
71
  let images = 0
72
72
  const content = (message?.content || []).filter(block => block?.type === 'text' || block?.type === 'image')
73
73
  .filter(block => block.type !== 'image' || ++images <= 8).slice(0, 16)
74
- .map(block => block.type === 'text' ? { type: 'text', text: String(block.text || '').slice(0, MAX_TEXT) } : block)
74
+ .map(block => block.type === 'text' ? { type: 'text', text: redactSecrets(String(block.text || '').slice(0, MAX_TEXT)) } : block)
75
75
  return content.some(block => block.type === 'image' || block.text.trim()) ? { id: message.id, role: 'user', content } : null
76
76
  }
77
77
 
@@ -136,18 +136,23 @@ export function ingestInboundBatch({ sessionId, batch, session, ctx, now = Date.
136
136
  return { accepted: accepted.length, duplicate: normalized.messages.length - accepted.length, pending: pending.length }
137
137
  }
138
138
 
139
- export function noteNativeUserMessages(sessionId, messages, { now = Date.now() } = {}) {
139
+ export function noteNativeUserMessages(sessionId, messages, { now = Date.now(), admitted = false } = {}) {
140
+ if (!admitted) return
140
141
  const binding = getSessionBinding(sessionId)
141
142
  if (!binding) return
142
143
  const before = journal(binding)
143
- const keys = messages.filter(message => message?.source?.kind === 'user' && message.role === 'user' && typeof message.id === 'string')
144
- .map(message => messageKey({ id: message.id, context: binding.memoryContext }))
144
+ const native = messages.filter(message => message?.source?.kind === 'user' && message.role === 'user' && typeof message.id === 'string')
145
+ const keys = native.map(message => messageKey({ id: message.id, context: binding.memoryContext }))
145
146
  const seen = [...new Set([...before.seen, ...keys])].slice(-MAX_SEEN)
146
147
  setSessionBinding(sessionId, {
147
- inbound: { ...before, seen, pending: before.pending.filter(item => !keys.includes(item.key)) },
148
+ inbound: { ...before, seen, pending: before.pending.map(item => native.some(message => item.producer === 'host.user'
149
+ && item.id === message.id && JSON.stringify(item.content) === JSON.stringify(nativeInboundMessage(message)?.content))
150
+ ? { ...item, nativeAdmitted: true } : item) },
148
151
  lastTurnAt: new Date(now).toISOString(),
149
152
  sessionGone: false, sessionGoneAt: null,
150
153
  })
154
+ const outcome = getSessionBinding(sessionId)?.lastInboundOutcome
155
+ if (outcome?.keys?.length) finishInbound(sessionId, outcome.keys, outcome.clock, outcome)
151
156
  }
152
157
 
153
158
  export function hasPendingInbound(sessionId) {
@@ -188,10 +193,19 @@ export function finishInbound(sessionId, keys, clock, outcome) {
188
193
  if (!binding) return
189
194
  const before = journal(binding)
190
195
  const done = new Set(keys)
191
- const claims = before.pending.filter(item => done.has(item.key)).map(item => deliveryClaim({ producer: item.producer, batchId: item.batchId }))
196
+ const matched = before.pending.filter(item => done.has(item.key))
197
+ if (!matched.length) return
198
+ const ready = matched.filter(item => item.producer === 'host.user' ? item.nativeAdmitted === true : outcome?.admitted === true)
199
+ if (ready.length !== matched.length) {
200
+ setSessionBinding(sessionId, { lastInboundOutcome: { ...structuredClone(outcome), status: 'proposed',
201
+ keys: [...keys], clock, at: new Date().toISOString(), count: matched.length } })
202
+ }
203
+ if (!ready.length) return
204
+ const readyKeys = new Set(ready.map(item => item.key))
205
+ const claims = ready.map(item => deliveryClaim({ producer: item.producer, batchId: item.batchId }))
192
206
  setSessionBinding(sessionId, {
193
- inbound: { ...before, seen: [...new Set([...before.seen, ...keys])].slice(-MAX_SEEN), claimed: [...new Set([...before.claimed, ...claims])].slice(-MAX_SEEN), pending: before.pending.filter(item => !done.has(item.key)), clock, retryAt: null },
194
- lastInboundOutcome: { ...outcome, at: new Date().toISOString(), count: keys.length },
207
+ inbound: { ...before, seen: [...new Set([...before.seen, ...readyKeys])].slice(-MAX_SEEN), claimed: [...new Set([...before.claimed, ...claims])].slice(-MAX_SEEN), pending: before.pending.filter(item => !readyKeys.has(item.key)), clock: Math.max(Number(before.clock || 0), Number(clock) || 0), retryAt: null },
208
+ lastInboundOutcome: { ...structuredClone(outcome), keys: [...keys], clock, at: new Date().toISOString(), count: ready.length },
195
209
  })
196
210
  flushState()
197
211
  }
@@ -249,11 +263,12 @@ export function observeInboundEvent(ctx, session, event) {
249
263
  const binding = getSessionBinding(id)
250
264
  if (!binding || !event.data.id) return
251
265
  const message = nativeInboundMessage(event.data)
252
- if (!message) { noteNativeUserMessages(id, [event.data]); return }
266
+ if (!message) { noteNativeUserMessages(id, [event.data], { admitted: true }); return }
253
267
  ingestInboundBatch({ sessionId: id, session, ctx, batch: {
254
268
  type: INBOUND_TYPE, version: 1, producer: 'host.user', batchId: `user:${event.data.id}`,
255
269
  messages: [message],
256
270
  }, mediaEventKey: event.seq !== undefined ? `seq:${event.seq}` : `id:${event.data.id}` })
271
+ noteNativeUserMessages(id, [event.data], { admitted: true })
257
272
  } else if (event?.type === 'turn/end') {
258
273
  calls.delete(id)
259
274
  }