dsh-memu-memory 1.3.13 → 1.3.15
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 +1 -1
- package/CHANGELOG.md +29 -0
- package/docs/binding-lifecycle.md +1 -1
- package/docs/host-adaptation.md +26 -0
- package/docs/memory-semantics.md +4 -1
- package/docs/troubleshooting.md +41 -23
- package/lib/binding-diagnostics.js +1 -1
- package/lib/consolidation-snapshot.js +31 -1
- package/lib/cycle.js +46 -8
- package/lib/inject.js +428 -32
- package/lib/rpc.js +35 -4
- package/lib/state.js +144 -2
- package/package.json +1 -1
- package/tests/cue.test.mjs +2 -1
- package/tests/cycle.test.mjs +158 -1
- package/tests/inject.test.mjs +7 -7
- package/tests/injection-chain.test.mjs +40 -2
- package/tests/injection-rollback.test.mjs +4 -3
- package/tests/media.test.mjs +4 -1
- package/tests/memory-chain.test.mjs +4 -3
- package/tests/pending-injection.test.mjs +107 -0
package/lib/inject.js
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
markInjected, markInjectedRefs, recentMemoryRefs, releaseInjected, markReinjectPending, clearReinjectPending,
|
|
6
6
|
armCue, getActiveCue, setSessionMood, wasAnniversaryShown, markAnniversaryShown,
|
|
7
7
|
recordInjectionRollback, rollbackInjectionForTurn, consumeInjectionRollback,
|
|
8
|
+
rememberPendingInjection, findPendingInjection, forgetPendingInjection,
|
|
8
9
|
markOpenLoopReminded, DEFAULT_SETTINGS,
|
|
9
10
|
touchSession, getSessionBinding, setSessionBinding, setRecallError, effectiveScope,
|
|
10
11
|
} from './state.js'
|
|
@@ -257,6 +258,40 @@ function lastRealUser(messages) {
|
|
|
257
258
|
return null
|
|
258
259
|
}
|
|
259
260
|
|
|
261
|
+
// 宿主自己的提醒和插件消息同样是 user 角色,只有来源/正文前缀能区分。通道驱动的消息
|
|
262
|
+
// (channel-qq 等)source.kind 不是 `user`,旧口径把它当成「没有人说话」,整条记忆块
|
|
263
|
+
// 于是退到 inbound 路径追加到批次末尾——工具调用之后就出现了锚点。
|
|
264
|
+
const HARNESS_NOTICE_PREFIXES = ['<system-reminder>', '[Plugin context from', '(过程纪律']
|
|
265
|
+
const HARNESS_USER_SOURCES = new Set([
|
|
266
|
+
'runtime-context', 'skill-catalog', 'time-context', 'progress-rules',
|
|
267
|
+
'agent-instructions', 'dsh-ops:step-tail', 'user-approval', 'system-prompt',
|
|
268
|
+
'memory-guide', 'memory-context', 'memory-anchor',
|
|
269
|
+
])
|
|
270
|
+
|
|
271
|
+
function isHarnessUserMessage(message) {
|
|
272
|
+
const kind = String(message?.source?.kind || '')
|
|
273
|
+
if (kind.startsWith('plugin:')) return true
|
|
274
|
+
if (kind.startsWith('tool')) return true
|
|
275
|
+
if (kind.startsWith('system')) return true
|
|
276
|
+
if (HARNESS_USER_SOURCES.has(kind)) return true
|
|
277
|
+
const text = messageText(message)
|
|
278
|
+
if (!text.trim()) return true
|
|
279
|
+
return HARNESS_NOTICE_PREFIXES.some(prefix => text.startsWith(prefix))
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// 本步批次里最后一条「人类消息」。记忆块的落点口径是它后面(injectForStep 末尾按
|
|
283
|
+
// index + 1 前插),批次里没有人类消息时(纯工具步、中途步)一律不投——那样必然落在
|
|
284
|
+
// assistant 消息之后,正是「回复完才拿到上下文」的成因。
|
|
285
|
+
function humanMessage(messages) {
|
|
286
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
287
|
+
const message = messages[i]
|
|
288
|
+
if (message?.role !== 'user') continue
|
|
289
|
+
if (isHarnessUserMessage(message)) continue
|
|
290
|
+
return message
|
|
291
|
+
}
|
|
292
|
+
return null
|
|
293
|
+
}
|
|
294
|
+
|
|
260
295
|
export function contextualQuery(messages, current) {
|
|
261
296
|
const query = userText(current)
|
|
262
297
|
if (query.length > 24 || !/(?:她|他|它|那|这|上次|刚才|后来|呢|然后|\b(?:it|that|then|her|him)\b)/i.test(query)) return query
|
|
@@ -1197,6 +1232,40 @@ export function createMemoryMessage(text) {
|
|
|
1197
1232
|
// 和第二个锚点;没实证(配置无效、额度、取消发生在投放之前)才该把记账还回去。
|
|
1198
1233
|
// 证据只留在内存:进程重启后宁可什么都不做,也不要误投。
|
|
1199
1234
|
const injectionAdmissions = new Map()
|
|
1235
|
+
// 会话级「本进程已经投过锚点」的兜底。不落盘:重启后再发一次是可接受的代价,
|
|
1236
|
+
// 比因为接纳回调不生效而每步重发要好得多。压缩时清空(与 reinjectPending 同步)。
|
|
1237
|
+
const anchorSeen = new Set()
|
|
1238
|
+
// 「这条人类消息 / 这张图 / 这套规则已经在本次进程里投过」。走同一层理由:这些都只在
|
|
1239
|
+
// 宿主接纳回调里落盘,回调长期不来时幂等就不存在,于是每步重投(实测单回合 22 次媒体块)。
|
|
1240
|
+
// 进程内先记,回调成功时照旧落盘;重启后最多重发一次,远好过每步重发。
|
|
1241
|
+
const servedHumans = new Map()
|
|
1242
|
+
const servedMedia = new Map()
|
|
1243
|
+
const servedInbound = new Map()
|
|
1244
|
+
|
|
1245
|
+
function servedSet(map, sessionId, cap = 512) {
|
|
1246
|
+
let set = map.get(sessionId)
|
|
1247
|
+
if (!set) { set = new Set(); map.set(sessionId, set) }
|
|
1248
|
+
while (set.size > cap) set.delete(set.values().next().value)
|
|
1249
|
+
return set
|
|
1250
|
+
}
|
|
1251
|
+
function humanServed(sessionId, messageId) {
|
|
1252
|
+
return Boolean(messageId) && servedHumans.get(sessionId)?.has(messageId) === true
|
|
1253
|
+
}
|
|
1254
|
+
function markHumanServed(sessionId, messageId) {
|
|
1255
|
+
if (messageId) servedSet(servedHumans, sessionId).add(messageId)
|
|
1256
|
+
}
|
|
1257
|
+
function mediaServed(sessionId, messageId, sha256) {
|
|
1258
|
+
return Boolean(messageId && sha256) && servedMedia.get(sessionId)?.has(`${messageId}|${sha256}`) === true
|
|
1259
|
+
}
|
|
1260
|
+
function markMediaServed(sessionId, messageId, sha256) {
|
|
1261
|
+
if (messageId && sha256) servedSet(servedMedia, sessionId).add(`${messageId}|${sha256}`)
|
|
1262
|
+
}
|
|
1263
|
+
function clearInjectionSeen(sessionId) {
|
|
1264
|
+
servedHumans.delete(sessionId)
|
|
1265
|
+
servedMedia.delete(sessionId)
|
|
1266
|
+
servedInbound.delete(sessionId)
|
|
1267
|
+
anchorSeen.delete(sessionId)
|
|
1268
|
+
}
|
|
1200
1269
|
const nativeAdmissions = new Map()
|
|
1201
1270
|
const turnClosures = new Map()
|
|
1202
1271
|
function turnClosure(sessionId, turn) { return turnClosures.get(sessionId)?.get(Number(turn)) || 0 }
|
|
@@ -1219,6 +1288,26 @@ function pendingProposal(sessionId, key) {
|
|
|
1219
1288
|
return null
|
|
1220
1289
|
}
|
|
1221
1290
|
|
|
1291
|
+
// 落盘凭据只留提交必需的部分:patch 白名单 + 计数用 id 列表,避免把整份 actions
|
|
1292
|
+
// (含 lexicon 行、投影消息)塞进 state.json。
|
|
1293
|
+
const LITE_PATCH_KEYS = new Set(['anchorPushed', 'reinjectPending', 'guideRulesKey', 'guideMessageAt',
|
|
1294
|
+
'guideLost', 'lastInjectedUserMessageId', 'lastRecallOutcome', 'replayIds', 'replayedAt',
|
|
1295
|
+
'activeCue', 'lexiconInjectionClock'])
|
|
1296
|
+
|
|
1297
|
+
function liteInjectionActions(actions = {}) {
|
|
1298
|
+
const patch = {}
|
|
1299
|
+
for (const [key, value] of Object.entries(actions.patch || {})) if (LITE_PATCH_KEYS.has(key)) patch[key] = value
|
|
1300
|
+
return {
|
|
1301
|
+
anchor: actions.anchor === true,
|
|
1302
|
+
patch,
|
|
1303
|
+
anniversaries: actions.anniversaries || {},
|
|
1304
|
+
nudgeIds: actions.nudgeIds || [],
|
|
1305
|
+
inbound: actions.inbound ? { keys: (actions.inbound.keys || []).slice(-8), outcome: actions.inbound.outcome } : null,
|
|
1306
|
+
lexicon: actions.lexicon ? { hits: (actions.lexicon.hits || []).slice(-8),
|
|
1307
|
+
selected: (actions.lexicon.selected || []).map(row => ({ termId: row.termId, libraryId: row.libraryId })) } : null,
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1222
1311
|
function proposeInjection(sessionId, hostTurn, message, refs, memoryClock, actions, key, projection = [], beforeUserId = null) {
|
|
1223
1312
|
const binding = getSessionBinding(sessionId)
|
|
1224
1313
|
if (!binding || !message?.id) return
|
|
@@ -1238,6 +1327,13 @@ function proposeInjection(sessionId, hostTurn, message, refs, memoryClock, actio
|
|
|
1238
1327
|
while (map.size > 128) map.delete(map.keys().next().value)
|
|
1239
1328
|
injectionAdmissions.set(sessionId, map)
|
|
1240
1329
|
while (injectionAdmissions.size > 128) injectionAdmissions.delete(injectionAdmissions.keys().next().value)
|
|
1330
|
+
// 落盘凭据:观察端换进程/重启后仍能补完接纳(内存 Map 会跟着进程消失)。
|
|
1331
|
+
const stored = map.get(message.id)
|
|
1332
|
+
try {
|
|
1333
|
+
rememberPendingInjection(sessionId, { digest: stored.digest, messageId: message.id,
|
|
1334
|
+
turn: stored.turn, clock: memoryClock, generation: stored.generation, epoch: stored.epoch,
|
|
1335
|
+
refs: stored.refs, actions: liteInjectionActions(copiedActions) })
|
|
1336
|
+
} catch {}
|
|
1241
1337
|
}
|
|
1242
1338
|
|
|
1243
1339
|
function reuseProposal(decision, proposal, hostTurn = null) {
|
|
@@ -1252,23 +1348,109 @@ function reuseProposal(decision, proposal, hostTurn = null) {
|
|
|
1252
1348
|
if (!ids.has(human.id) && !admitted) { messages.push(structuredClone(human)); ids.add(human.id) }
|
|
1253
1349
|
}
|
|
1254
1350
|
if (!ids.has(proposal.message.id)) {
|
|
1255
|
-
|
|
1256
|
-
|
|
1351
|
+
// 落点口径与首次注入一致:紧跟那条人类消息之后。
|
|
1352
|
+
const anchorAt = proposal.beforeUserId ? messages.findIndex(message => message.id === proposal.beforeUserId) : -1
|
|
1353
|
+
messages.splice(anchorAt < 0 ? messages.length : anchorAt + 1, 0, structuredClone(proposal.message))
|
|
1257
1354
|
}
|
|
1258
1355
|
return { ...decision, messages }
|
|
1259
1356
|
}
|
|
1260
1357
|
|
|
1358
|
+
// 接纳失败必须留一句可查的原因(硬规则 10):否则「记忆没注入」只能靠猜,qq-dm 那种
|
|
1359
|
+
// 长期不接纳的会话就是证据。同一会话同一原因 60 秒内只记一条,避免刷屏。
|
|
1360
|
+
const injectionRejects = new Map()
|
|
1361
|
+
|
|
1362
|
+
function snapshotDrift(sessionId, snapshot) {
|
|
1363
|
+
const current = getSessionBinding(sessionId)
|
|
1364
|
+
if (!current) return { binding: 'missing' }
|
|
1365
|
+
const drift = {}
|
|
1366
|
+
if (Number(current.injectionEpoch || 0) !== snapshot.epoch) drift.epoch = snapshot.epoch + '→' + Number(current.injectionEpoch || 0)
|
|
1367
|
+
if ((current.libraryId || null) !== snapshot.libraryId) drift.libraryId = String(snapshot.libraryId) + '→' + String(current.libraryId || null)
|
|
1368
|
+
if ((current.scopeKey || null) !== snapshot.scopeKey) drift.scopeKey = String(snapshot.scopeKey).slice(-30) + '→' + String(current.scopeKey).slice(-30)
|
|
1369
|
+
if (JSON.stringify(current.memoryContext || {}) !== snapshot.memoryContext) {
|
|
1370
|
+
drift.memoryContext = String(snapshot.memoryContext) + '→' + JSON.stringify(current.memoryContext || {})
|
|
1371
|
+
}
|
|
1372
|
+
const scope = effectiveScope(current)
|
|
1373
|
+
if (scope.useLibrary !== snapshot.useLibrary) drift.useLibrary = String(snapshot.useLibrary) + '→' + String(scope.useLibrary)
|
|
1374
|
+
if (scope.useGlobal !== snapshot.useGlobal) drift.useGlobal = String(snapshot.useGlobal) + '→' + String(scope.useGlobal)
|
|
1375
|
+
return drift
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
function noteInjectionReject(sessionId, reason, drift = null) {
|
|
1379
|
+
try {
|
|
1380
|
+
const last = injectionRejects.get(sessionId)
|
|
1381
|
+
if (last && last.reason === reason && Date.now() - last.at < 60_000) { last.count += 1; return false }
|
|
1382
|
+
injectionRejects.set(sessionId, { reason, at: Date.now(), count: 1 })
|
|
1383
|
+
while (injectionRejects.size > 128) injectionRejects.delete(injectionRejects.keys().next().value)
|
|
1384
|
+
record({ kind: 'system', scope: 'private', sessionId, ok: false, level: 'warn',
|
|
1385
|
+
message: `注入消息未被接纳 · ${reason}`,
|
|
1386
|
+
detail: { reason, drift, hint: reason === 'proposal-missing'
|
|
1387
|
+
? '提案不在进程内也不在落盘凭据里:宿主重启过,或该会话由另一个进程观察'
|
|
1388
|
+
: '观察到的消息与提案对不上,本条按未接纳处理,下一轮会重投' } })
|
|
1389
|
+
} catch {}
|
|
1390
|
+
return false
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
// 「注入评估」两条 info 记录是解释性日志,不是故障:在话痨会话里它每个无内容
|
|
1394
|
+
// 回合都可能来一条。同一会话同一签名 60 秒合并一条,长会话不再刷满活动日志。
|
|
1395
|
+
const injectionEvalNotes = new Map()
|
|
1396
|
+
|
|
1397
|
+
function evalNoteOnce(sessionId, signature) {
|
|
1398
|
+
const last = injectionEvalNotes.get(sessionId)
|
|
1399
|
+
if (last && last.signature === signature && Date.now() - last.at < 60_000) return false
|
|
1400
|
+
injectionEvalNotes.set(sessionId, { signature, at: Date.now() })
|
|
1401
|
+
while (injectionEvalNotes.size > 128) injectionEvalNotes.delete(injectionEvalNotes.keys().next().value)
|
|
1402
|
+
return true
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1261
1405
|
function observeInjectionMessage(sessionId, message, log) {
|
|
1406
|
+
if (!sessionId || message?.role !== 'user' || message.source?.kind !== `plugin:${PLUGIN}`) return false
|
|
1262
1407
|
const map = injectionAdmissions.get(sessionId)
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1408
|
+
let proposal = map?.get(message.id)
|
|
1409
|
+
const digest = bodyDigest(message)
|
|
1410
|
+
if (!proposal) {
|
|
1411
|
+
// 内存提案会随进程消失;落盘凭据按内容 digest 把它补认回来。接纳仍只发生在
|
|
1412
|
+
// 「真的看见这条消息进了转录」的时刻,契约不变。
|
|
1413
|
+
const pending = findPendingInjection(sessionId, digest)
|
|
1414
|
+
if (!pending) return noteInjectionReject(sessionId, 'proposal-missing')
|
|
1415
|
+
const lateBinding = getSessionBinding(sessionId) || {}
|
|
1416
|
+
proposal = { ...pending, status: 'proposed', fromStore: true, actions: pending.actions || {},
|
|
1417
|
+
// 迟到的接纳(跨重启)不能沿用当时那个已经落后的时钟:markInjectedRefs 会按
|
|
1418
|
+
// 「时钟必须前进」拒掉全部 effects,于是账记了、标记却没落,又回到重投。
|
|
1419
|
+
memoryClock: Math.max(Number(pending.clock) || 0, Number(lateBinding.lastInjectedTurn) || 0,
|
|
1420
|
+
Number(lateBinding.inbound?.clock) || 0) || Number(pending.clock) || 0,
|
|
1421
|
+
snapshot: injectionSnapshot(lateBinding), autoInject: getSettings().autoInject }
|
|
1422
|
+
}
|
|
1423
|
+
// 已经接纳过的同一条消息不是故障:重复观察直接当成功,别再记一条 warn 噪音。
|
|
1424
|
+
if (proposal.status === 'admitted') return true
|
|
1425
|
+
if (proposal.status !== 'proposed') return noteInjectionReject(sessionId, `proposal-${proposal.status}`)
|
|
1426
|
+
if (digest !== proposal.digest) return noteInjectionReject(sessionId, 'digest-mismatch')
|
|
1427
|
+
// 先算漂移:既用于阻塞判断,也用于"不阻塞但要看得见"的记录。
|
|
1428
|
+
const drift = snapshotDrift(sessionId, proposal.snapshot)
|
|
1429
|
+
if (!snapshotStillDescribesTranscript(sessionId, proposal.snapshot)) {
|
|
1430
|
+
map?.delete(message.id)
|
|
1431
|
+
return noteInjectionReject(sessionId, 'snapshot-stale', drift)
|
|
1432
|
+
}
|
|
1433
|
+
if (Object.keys(drift).length) {
|
|
1434
|
+
// 不阻塞,但要让"是谁把快照弄脏了"留在日志里,而不是靠猜。
|
|
1435
|
+
record({ kind: 'system', scope: 'private', sessionId, ok: true, level: 'info',
|
|
1436
|
+
message: '注入接纳 · 记账漂移(不阻塞)· ' + Object.entries(drift).map(([k, v]) => k + ': ' + v).join(' ; '),
|
|
1437
|
+
detail: { drift, turn: proposal.turn } })
|
|
1438
|
+
}
|
|
1267
1439
|
const accepted = markInjectedRefs(sessionId, proposal.refs, proposal.memoryClock, {
|
|
1268
1440
|
messageId: message.id, hostTurn: proposal.turn, generation: proposal.generation, epoch: proposal.epoch, actions: proposal.actions,
|
|
1269
1441
|
})
|
|
1270
|
-
if (!accepted) return
|
|
1442
|
+
if (!accepted) return noteInjectionReject(sessionId, 'commit-refused')
|
|
1271
1443
|
proposal.status = 'admitted'
|
|
1444
|
+
// 跨进程补认成功后把提案放回内存:同一消息再被观察(宿主重放、事件回环)
|
|
1445
|
+
// 走 admitted→true,而不是凭据已删后的 proposal-missing 误报警。
|
|
1446
|
+
if (proposal.fromStore) {
|
|
1447
|
+
const admittedMap = injectionAdmissions.get(sessionId) || new Map()
|
|
1448
|
+
admittedMap.set(message.id, proposal)
|
|
1449
|
+
while (admittedMap.size > 128) admittedMap.delete(admittedMap.keys().next().value)
|
|
1450
|
+
injectionAdmissions.set(sessionId, admittedMap)
|
|
1451
|
+
}
|
|
1452
|
+
// 凭据按它自己的 messageId 作废:补认观察到的消息 id 与凭据 id 可能不同(同内容重投)。
|
|
1453
|
+
try { forgetPendingInjection(sessionId, proposal.messageId || message.id) } catch {}
|
|
1272
1454
|
const actions = proposal.actions || {}
|
|
1273
1455
|
try {
|
|
1274
1456
|
// Group foreign libraries independently; identical bare ids never cross layers.
|
|
@@ -1297,12 +1479,17 @@ function finishInjectionTurn(sessionId, hostTurn, kind, log) {
|
|
|
1297
1479
|
const map = injectionAdmissions.get(sessionId)
|
|
1298
1480
|
if (!map) return
|
|
1299
1481
|
let discarded = 0
|
|
1482
|
+
const abandoned = []
|
|
1300
1483
|
for (const [id, proposal] of map) {
|
|
1301
1484
|
if (Number.isFinite(Number(hostTurn)) && proposal.turn !== Number(hostTurn)) continue
|
|
1302
1485
|
if (proposal.status === 'proposed') discarded += 1
|
|
1486
|
+
abandoned.push(id)
|
|
1303
1487
|
map.delete(id)
|
|
1304
1488
|
}
|
|
1305
1489
|
if (!map.size) injectionAdmissions.delete(sessionId)
|
|
1490
|
+
// 落盘凭据只服务「这一轮内的跨进程/重启补认」;回合一收就作废,否则迟到的同内容消息
|
|
1491
|
+
// 会把一条已被丢弃的提案重新认领回来(回合末尾撤账的正确性依赖这里)。
|
|
1492
|
+
for (const id of abandoned) { try { forgetPendingInjection(sessionId, id) } catch {} }
|
|
1306
1493
|
if (discarded) {
|
|
1307
1494
|
log?.(`discarded ${discarded} unadmitted injection proposals for turn ${hostTurn}; inbound remains retryable`)
|
|
1308
1495
|
record({ kind: 'system', scope: 'private', sessionId, ok: false, level: 'warn',
|
|
@@ -1327,6 +1514,21 @@ function injectionSnapshot(binding) {
|
|
|
1327
1514
|
}
|
|
1328
1515
|
}
|
|
1329
1516
|
|
|
1517
|
+
// 接纳专用:`scopeGeneration` 只是「这只 binding 的 scope 被写过几次」的记账编号,
|
|
1518
|
+
// 频道每轮写一次 memoryContext 就会推进它。观察时若只发生了这种推进,内容口径(库、
|
|
1519
|
+
// scopeKey、上下文、两开关、压缩代际)其实没变,整条注入就该照常接纳——否则接纳永远
|
|
1520
|
+
// 落不了账,锚点/幂等全部停摆(qq-dm 实测:`未被接纳 · snapshot-stale`)。
|
|
1521
|
+
function snapshotStillDescribesTranscript(sessionId, snapshot) {
|
|
1522
|
+
const current = getSessionBinding(sessionId)
|
|
1523
|
+
if (!current) return false
|
|
1524
|
+
// 只看压缩代际:它变了说明转录被替换过,旧消息的记账不该继续。
|
|
1525
|
+
// generation / libraryId / scopeKey / memoryContext 的漂移**不该**否掉接纳——那条消息
|
|
1526
|
+
// 已经由宿主写进转录、模型也确实读到了;内容口径的正确性由「发布前」的严格快照负责,
|
|
1527
|
+
// 事后记账再按它拒一次,只会让接纳永久失败(实测 reason 恒为 snapshot-stale)。
|
|
1528
|
+
if (Number(current.injectionEpoch || 0) !== snapshot.epoch) return false
|
|
1529
|
+
return effectiveScope(current).enabled
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1330
1532
|
function injectionSnapshotIsCurrent(sessionId, snapshot, autoInject) {
|
|
1331
1533
|
const current = getSessionBinding(sessionId)
|
|
1332
1534
|
if (!current) return false
|
|
@@ -1466,7 +1668,13 @@ function ensureUnifiedGuide(ctx, payload, decision) {
|
|
|
1466
1668
|
if (pending) return reuseProposal(decision, pending, payload?.turn)
|
|
1467
1669
|
const next = decision.messages.filter((message) => !isMemoryGuideMessage(message))
|
|
1468
1670
|
const guideMessage = createMemoryMessage(guide.text)
|
|
1469
|
-
|
|
1671
|
+
// 规则消息也落进「人类消息 → 下一次模型开口」这个窗口里:优先紧跟本步的记忆块,
|
|
1672
|
+
// 没有记忆块就紧跟人类消息,都没有才退回末尾。
|
|
1673
|
+
const memoryBlock = next.filter((message) => message?.source?.kind === `plugin:${PLUGIN}`
|
|
1674
|
+
&& !isMemoryGuideMessage(message)).pop()
|
|
1675
|
+
const hostMessage = memoryBlock || humanMessage(next)
|
|
1676
|
+
const guideAt = hostMessage ? next.indexOf(hostMessage) + 1 : next.length
|
|
1677
|
+
next.splice(guideAt, 0, guideMessage)
|
|
1470
1678
|
proposeInjection(sessionId, payload?.turn, guideMessage, [], Number(binding.inbound?.clock || payload?.turn || 0), {
|
|
1471
1679
|
patch: { guideRulesKey: guide.key, guideMessageAt: new Date().toISOString(), guideLost: false },
|
|
1472
1680
|
}, proposalKey, next)
|
|
@@ -1489,6 +1697,10 @@ function ensureUnifiedGuide(ctx, payload, decision) {
|
|
|
1489
1697
|
|
|
1490
1698
|
async function injectInboundForStep({ agent, decision, turn, signal, log, ctx }) {
|
|
1491
1699
|
const sessionId = agent.session.header.id
|
|
1700
|
+
// 这条路径同时服务两种情况:本步批次里有外来人类消息(插在它后面),以及队列里的
|
|
1701
|
+
// 外部批次(decision.messages 可能是空的,只能追加)。两者都不允许因为「没有人类消息」
|
|
1702
|
+
// 被一刀切掉——排空队列、恢复待投批次都靠它。
|
|
1703
|
+
const human = humanMessage(decision.messages)
|
|
1492
1704
|
const before = getSessionBinding(sessionId)
|
|
1493
1705
|
if (!before || !hasPendingInbound(sessionId)) return decision
|
|
1494
1706
|
const waiting = await pendingInbound(sessionId, ctx, agent.session)
|
|
@@ -1499,8 +1711,15 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1499
1711
|
const proposedKeys = new Set([...(injectionAdmissions.get(sessionId)?.values() || [])]
|
|
1500
1712
|
.filter(proposal => proposal.status === 'proposed' && proposal.generation === Number(before.scopeGeneration || 0)
|
|
1501
1713
|
&& proposal.epoch === Number(before.injectionEpoch || 0)).flatMap(proposal => proposal.actions?.inbound?.keys || []))
|
|
1502
|
-
|
|
1503
|
-
|
|
1714
|
+
// 进程内批次键去重:同一批外部输入在本次进程里只投一次。宿主接纳回调不来时,
|
|
1715
|
+
// pending 不会被清,于是同一批会在每个后续 step 反复满足条件——实测单回合 22 次。
|
|
1716
|
+
const servedKey = (key) => `${turn}|${key}`
|
|
1717
|
+
const batch = waiting.filter(item => !proposedKeys.has(item.key)
|
|
1718
|
+
&& servedInbound.get(sessionId)?.has(servedKey(item.key)) !== true)
|
|
1719
|
+
if (signal?.aborted) return decision
|
|
1720
|
+
// 空批不等于没事可做:这一步可能带着一条人类消息,而锚点/规则是一次性的。旧代码
|
|
1721
|
+
// 在这里直接 return,于是「陈旧 pending 把首步劫持到 inbound 路径」的会话首步一条
|
|
1722
|
+
// 记忆都投不出来,模型先开口、下一步才补锚点(qq-dm turn 335 实测)。
|
|
1504
1723
|
const binding = getSessionBinding(sessionId)
|
|
1505
1724
|
if (!binding || binding.libraryId !== before.libraryId) return decision
|
|
1506
1725
|
const scope = effectiveScope(binding)
|
|
@@ -1509,17 +1728,32 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1509
1728
|
const priorOutcome = binding.lastInboundOutcome
|
|
1510
1729
|
const sameBatch = JSON.stringify(priorOutcome?.keys) === JSON.stringify(keys)
|
|
1511
1730
|
const clock = sameBatch && Number.isFinite(priorOutcome?.clock) ? priorOutcome.clock : nextMemoryClock(binding, turn)
|
|
1512
|
-
const proposalKey = `batch:${keys.slice().sort().join(',')}`
|
|
1513
|
-
const pending = pendingProposal(sessionId, proposalKey)
|
|
1514
|
-
if (pending) return reuseProposal(decision, pending, turn)
|
|
1515
1731
|
const admissible = batch.filter(item => {
|
|
1516
1732
|
const current = binding.memoryContext || {}
|
|
1517
1733
|
return (item.libraryId || null) === (binding.libraryId || null)
|
|
1518
1734
|
&& ['channelId', 'characterId', 'worldId', 'branchId'].every(key => !item.context[key] || item.context[key] === current[key])
|
|
1519
1735
|
&& (!item.context.knownBy?.length || item.context.knownBy.includes(current.characterId))
|
|
1520
1736
|
})
|
|
1521
|
-
|
|
1522
|
-
|
|
1737
|
+
// 「批里没有一条属于本库/本上下文」和空批等价:这一批没有可注入的召回内容。只要本步
|
|
1738
|
+
// 带着人类消息,锚点/规则仍然要投,否则模型先开口、锚点下一步才补(qq-dm turn 338 实测)。
|
|
1739
|
+
const anchorOnly = Boolean(human) && !admissible.length
|
|
1740
|
+
if (!batch.length && !anchorOnly) {
|
|
1741
|
+
if (evalNoteOnce(sessionId, 'inbound-no-batch')) record({ kind: 'system', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: false, level: 'info',
|
|
1742
|
+
message: '注入评估 · inbound 无批次 · human=' + Boolean(human) + ' · waiting=' + waiting.length
|
|
1743
|
+
+ ' · proposed=' + proposedKeys.size + ' · served=' + (servedInbound.get(sessionId)?.size || 0),
|
|
1744
|
+
detail: { turn, human: Boolean(human), waiting: waiting.length, proposed: proposedKeys.size } })
|
|
1745
|
+
return decision
|
|
1746
|
+
}
|
|
1747
|
+
const proposalKey = anchorOnly ? `anchor:${turn}` : `batch:${keys.slice().sort().join(',')}`
|
|
1748
|
+
const pending = pendingProposal(sessionId, proposalKey)
|
|
1749
|
+
if (pending) return reuseProposal(decision, pending, turn)
|
|
1750
|
+
if (settings.autoInject === 'off' || !scope.enabled) {
|
|
1751
|
+
if (anchorOnly) return decision
|
|
1752
|
+
finishInbound(sessionId, keys, clock, { reason: 'disabled', injectedCount: 0 })
|
|
1753
|
+
return decision
|
|
1754
|
+
}
|
|
1755
|
+
if (!admissible.length && !anchorOnly) {
|
|
1756
|
+
finishInbound(sessionId, keys, clock, { reason: 'scope', injectedCount: 0 })
|
|
1523
1757
|
return decision
|
|
1524
1758
|
}
|
|
1525
1759
|
const images = admissible.flatMap(item => imageTurn(item).images)
|
|
@@ -1587,7 +1821,8 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1587
1821
|
const lexiconUserTexts = admissible.map(item => imageTurn(item).query).filter(Boolean)
|
|
1588
1822
|
let outcome = 'anchor-only'
|
|
1589
1823
|
let errors = []
|
|
1590
|
-
|
|
1824
|
+
const minInboundChars = Math.max(1, Math.min(Number(settings.minUserChars ?? 6), 2))
|
|
1825
|
+
if (settings.autoInject !== 'anchor-only' && (imageCount || query.length >= minInboundChars)) {
|
|
1591
1826
|
const recallBudget = Math.max(0, Math.min(turnBudget, totalRoom()))
|
|
1592
1827
|
if (recallBudget > 0) {
|
|
1593
1828
|
const recall = await buildRecall(effective, query, clock, { ...settings, turnTokens: recallBudget }, { agent }, sessionId, { excludedRefs: anchorRefs })
|
|
@@ -1640,6 +1875,7 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1640
1875
|
if (text) {
|
|
1641
1876
|
inboundMessage = createMemoryMessage(text)
|
|
1642
1877
|
const anchorPushed = anchorNeeded && Boolean(parts[0]?.startsWith('===== memory anchor'))
|
|
1878
|
+
if (anchorPushed) anchorSeen.add(sessionId)
|
|
1643
1879
|
proposeInjection(sessionId, turn, inboundMessage, refs, clock, {
|
|
1644
1880
|
anchor: anchorPushed, lexicon: lexiconTurnCommit,
|
|
1645
1881
|
inbound: { keys, outcome: { reason: outcome, injectedCount: refs.length } },
|
|
@@ -1649,7 +1885,122 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1649
1885
|
advanceMemoryClock(sessionId, clock)
|
|
1650
1886
|
finishInbound(sessionId, keys, clock, { reason: outcome, injectedCount: 0 })
|
|
1651
1887
|
}
|
|
1652
|
-
|
|
1888
|
+
if (!inboundMessage) return decision
|
|
1889
|
+
const placed = [...decision.messages]
|
|
1890
|
+
const at = human ? placed.indexOf(human) : -1
|
|
1891
|
+
placed.splice(at < 0 ? placed.length : at + 1, 0, inboundMessage)
|
|
1892
|
+
for (const item of batch) servedSet(servedInbound, sessionId).add(servedKey(item.key))
|
|
1893
|
+
return { ...decision, messages: placed }
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
// 回合中途的补充召回(coding 长回合)。位置不变式在这里物理上不成立:这一批里没有
|
|
1897
|
+
// 人类消息,落点只能在工具结果之后、下一次模型请求之前。所以它是单独一类内容:
|
|
1898
|
+
// 带 phase 标记、单独预算、每回合有上限,靠「自上次注入以来的增量」触发,不是每步都跑。
|
|
1899
|
+
const midTurnMarks = new Map()
|
|
1900
|
+
|
|
1901
|
+
function midTurnStateFor(sessionId, turn) {
|
|
1902
|
+
const previous = midTurnMarks.get(sessionId)
|
|
1903
|
+
if (previous && previous.turn === Number(turn)) return previous
|
|
1904
|
+
const next = { turn: Number(turn), units: 0, chars: 0, injections: 0, emptyStreak: 0, lastStep: 1, lastAt: 0 }
|
|
1905
|
+
midTurnMarks.set(sessionId, next)
|
|
1906
|
+
while (midTurnMarks.size > 128) midTurnMarks.delete(midTurnMarks.keys().next().value)
|
|
1907
|
+
return next
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
function midTurnPolicy(settings) {
|
|
1911
|
+
return {
|
|
1912
|
+
enabled: settings.midTurnRecall !== false,
|
|
1913
|
+
minSteps: Math.max(1, Number(settings.midTurnMinSteps ?? 4)),
|
|
1914
|
+
minUnits: Math.max(1, Number(settings.midTurnMinUnits ?? 3)),
|
|
1915
|
+
minChars: Math.max(0, Number(settings.midTurnMinChars ?? 6000)),
|
|
1916
|
+
maxPerTurn: Math.max(1, Number(settings.midTurnMaxPerTurn ?? 2)),
|
|
1917
|
+
cooldownMs: Math.max(0, Number(settings.midTurnCooldownMs ?? 60000)),
|
|
1918
|
+
tokens: Math.max(120, Number(settings.midTurnTokens ?? 400)),
|
|
1919
|
+
fullUnits: Math.max(1, Number(settings.midTurnFullUnits ?? 6)),
|
|
1920
|
+
fullChars: Math.max(0, Number(settings.midTurnFullChars ?? 15000)),
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
|
|
1924
|
+
// 增量证据与 active-memory 的计分口径一致:同一条工具结果重复出现(轮询、重读、重试)
|
|
1925
|
+
// 只算一次,否则一个重读循环就能把分数刷爆。
|
|
1926
|
+
function collectMidTurnEvidence(messages) {
|
|
1927
|
+
const seen = new Set()
|
|
1928
|
+
let units = 0
|
|
1929
|
+
let chars = 0
|
|
1930
|
+
const texts = []
|
|
1931
|
+
for (const message of messages || []) {
|
|
1932
|
+
const blocks = Array.isArray(message?.content) ? message.content : []
|
|
1933
|
+
const isToolResult = message?.role === 'tool'
|
|
1934
|
+
|| String(message?.source?.kind || '').startsWith('tool')
|
|
1935
|
+
|| blocks.some(block => block?.type === 'tool-result')
|
|
1936
|
+
if (!isToolResult) continue
|
|
1937
|
+
const text = messageText(message)
|
|
1938
|
+
if (!text) continue
|
|
1939
|
+
const key = text.slice(0, 160) + '|' + text.length
|
|
1940
|
+
if (seen.has(key)) continue
|
|
1941
|
+
seen.add(key)
|
|
1942
|
+
units += 1
|
|
1943
|
+
chars += Math.min(text.length, 2000)
|
|
1944
|
+
texts.push(text)
|
|
1945
|
+
}
|
|
1946
|
+
return { units, chars, text: texts.join('\n') }
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
async function maybeMidTurnRecall({ agent, decision, turn, step, ctx, log = null }) {
|
|
1950
|
+
const sessionId = agent?.session?.header?.id
|
|
1951
|
+
if (!sessionId) return decision
|
|
1952
|
+
const settings = getSettings()
|
|
1953
|
+
const policy = midTurnPolicy(settings)
|
|
1954
|
+
if (!policy.enabled || settings.autoInject === 'off' || settings.autoInject === 'anchor-only') return decision
|
|
1955
|
+
const binding = getSessionBinding(sessionId)
|
|
1956
|
+
const admitted = binding ? admissionFor(binding) : null
|
|
1957
|
+
if (!admitted) return decision
|
|
1958
|
+
const state = midTurnStateFor(sessionId, turn)
|
|
1959
|
+
const evidence = collectMidTurnEvidence(decision.messages)
|
|
1960
|
+
state.units += evidence.units
|
|
1961
|
+
state.chars += evidence.chars
|
|
1962
|
+
const currentStep = Math.max(1, Number(step) || 1)
|
|
1963
|
+
if (currentStep - state.lastStep < policy.minSteps) return decision
|
|
1964
|
+
if (state.units < policy.minUnits && state.chars < policy.minChars) return decision
|
|
1965
|
+
if (state.injections >= policy.maxPerTurn || state.emptyStreak >= 2) return decision
|
|
1966
|
+
if (state.lastAt && Date.now() - state.lastAt < policy.cooldownMs) return decision
|
|
1967
|
+
const effective = { ...binding, useLibrary: admitted.scope.useLibrary, useGlobal: admitted.scope.useGlobal }
|
|
1968
|
+
const snapshot = injectionSnapshot(effective)
|
|
1969
|
+
const clock = nextMemoryClock(binding, turn)
|
|
1970
|
+
const note = `[回合中途补充 · 这不是用户新说的话 · 本回合已跑 ${currentStep} 步]`
|
|
1971
|
+
const full = state.units >= policy.fullUnits && state.chars >= policy.fullChars
|
|
1972
|
+
let text = null
|
|
1973
|
+
let refs = []
|
|
1974
|
+
if (full) {
|
|
1975
|
+
const query = truncateToTokens(evidence.text, 300)
|
|
1976
|
+
if (!query) return decision
|
|
1977
|
+
try {
|
|
1978
|
+
const recall = await buildRecall(effective, query, clock,
|
|
1979
|
+
{ ...settings, turnTokens: policy.tokens }, { agent }, sessionId, {})
|
|
1980
|
+
if (recall.errors?.length) setRecallError(sessionId, recall.errors.join('; '))
|
|
1981
|
+
if (recall.text && estTokens(recall.text) <= policy.tokens + 60) {
|
|
1982
|
+
text = [note, recall.text].join('\n')
|
|
1983
|
+
refs = recall.refs || []
|
|
1984
|
+
}
|
|
1985
|
+
} catch (error) {
|
|
1986
|
+
try { log?.(`mid-turn recall degraded: ${error?.message || error}`) } catch {}
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
if (!text) {
|
|
1990
|
+
// 分数刚过线:只提示工具有得查,不投正文。
|
|
1991
|
+
text = [note, '如果你需要更早的上下文,可以调用 memu_private_recall 按关键词查。'].join('\n')
|
|
1992
|
+
}
|
|
1993
|
+
if (!injectionSnapshotIsCurrent(sessionId, snapshot, settings.autoInject)) return decision
|
|
1994
|
+
if (estTokens(text) > Math.max(0, Number(settings.injectionTotalTokens ?? 2000))) return decision
|
|
1995
|
+
const message = createMemoryMessage(text)
|
|
1996
|
+
proposeInjection(sessionId, turn, message, refs, clock, { patch: {} }, `mid:${turn}:${currentStep}`, decision.messages)
|
|
1997
|
+
state.injections += 1
|
|
1998
|
+
state.lastStep = currentStep
|
|
1999
|
+
state.lastAt = Date.now()
|
|
2000
|
+
// 空召回退避只针对「真的去查了却查空」;提示卡是刻意投的,不算失败。
|
|
2001
|
+
if (refs.length) state.emptyStreak = 0
|
|
2002
|
+
else if (full) state.emptyStreak += 1
|
|
2003
|
+
return { ...decision, messages: [...decision.messages, message] }
|
|
1653
2004
|
}
|
|
1654
2005
|
|
|
1655
2006
|
export async function injectForStep({ agent, decision, turn, step, signal, log = null, ctx = null }) {
|
|
@@ -1666,10 +2017,15 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
1666
2017
|
messages: fresh.map(nativeInboundMessage).filter(Boolean),
|
|
1667
2018
|
} })
|
|
1668
2019
|
}
|
|
1669
|
-
|
|
2020
|
+
const inbound = await injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
2021
|
+
if (inbound !== decision) return inbound
|
|
2022
|
+
// 中转批次没有人类消息 → inbound 路径不投;此时才轮到回合中途的补充召回。
|
|
2023
|
+
return maybeMidTurnRecall({ agent, decision, turn, step, ctx, log })
|
|
1670
2024
|
}
|
|
1671
2025
|
|
|
1672
|
-
|
|
2026
|
+
// 人类消息优先用 humanMessage:通道驱动(channel-qq 等)的 source.kind 不是 `user`,
|
|
2027
|
+
// 旧口径在这里直接退到 inbound 路径,记忆块因此被追加到批次末尾(工具调用之后)。
|
|
2028
|
+
const lastUser = humanMessage(decision.messages) || lastRealUser(decision.messages)
|
|
1673
2029
|
if (!lastUser) return injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
1674
2030
|
|
|
1675
2031
|
const sessionId = header.id
|
|
@@ -1679,11 +2035,17 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
1679
2035
|
const proposalKey = `user:${lastUser.id}:${bodyDigest(lastUser)}`
|
|
1680
2036
|
const pending = pendingProposal(sessionId, proposalKey)
|
|
1681
2037
|
if (pending) return reuseProposal(decision, pending, turn)
|
|
1682
|
-
|
|
2038
|
+
const humanAlreadyServed = humanServed(sessionId, lastUser.id)
|
|
2039
|
+
if ((binding.lastInjectedUserMessageId === lastUser.id || humanAlreadyServed) && binding.reinjectPending !== true) {
|
|
1683
2040
|
return hasPendingInbound(sessionId) ? injectInboundForStep({ agent, decision, turn, signal, log, ctx }) : decision
|
|
1684
2041
|
}
|
|
1685
|
-
const realIds = new Set(decision.messages.filter(message => message.source?.kind === 'user').map(message => message.id)
|
|
1686
|
-
|
|
2042
|
+
const realIds = new Set([...decision.messages.filter(message => message.source?.kind === 'user').map(message => message.id),
|
|
2043
|
+
lastUser.id].filter(Boolean))
|
|
2044
|
+
// 强制口径:本步批次里只要有原生人类消息(source.kind === 'user'),就不再被陈旧
|
|
2045
|
+
// pending 劫持去 inbound 路径。劫持会让首步一条记忆都投不出来,锚点只能等下一步补,
|
|
2046
|
+
// 于是出现「工具已经把消息发出去、锚点才到」(qq-dm turn 335/338/339 反复实测)。
|
|
2047
|
+
const hasNativeHuman = decision.messages.some(message => message?.role === 'user' && message?.source?.kind === 'user' && message?.id)
|
|
2048
|
+
if (!hasNativeHuman && (binding.inbound?.pending || []).some(item => item.producer !== 'host.user' || !realIds.has(item.id))) {
|
|
1687
2049
|
const fresh = decision.messages.filter(message => message.role === 'user' && message.source?.kind === 'user' && message.id)
|
|
1688
2050
|
if (fresh.length) ingestInboundBatch({ sessionId, session: agent.session, ctx, batch: {
|
|
1689
2051
|
type: INBOUND_TYPE, version: 1, producer: 'host.user', batchId: `step:${turn}:${step || 1}`,
|
|
@@ -1723,10 +2085,21 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
1723
2085
|
const query = contextualQuery(decision.messages, lastUser)
|
|
1724
2086
|
const imageCount = imageTurn(lastUser).imageCount
|
|
1725
2087
|
setSessionBinding(sessionId, { lastImageCount: imageCount })
|
|
1726
|
-
|
|
2088
|
+
// 短句也要召回:QQ 里常见「摸摸」「现在有点饿」这类 2–5 字回合,原来的 minUserChars=6
|
|
2089
|
+
// 会把它们挡在召回之外,叠加「锚点一会话一次」就变成「首步一条记忆都没有」。
|
|
2090
|
+
// 现在门槛下限是 2 字(minUserChars 仍可调,只是不再让短句完全静默)。
|
|
2091
|
+
const minQueryChars = Math.max(1, Math.min(Number(settings.minUserChars ?? 6), 2))
|
|
2092
|
+
const tooShort = !imageCount && query.length < minQueryChars
|
|
1727
2093
|
const reinject = binding.reinjectPending === true
|
|
2094
|
+
// 口径 A:锚点一会话一份,位置紧跟人类消息。首步要有内容,靠的是「短句也召回」
|
|
2095
|
+
// (minQueryChars 下限 2 字),不靠每回合重发整块索引——后者会破坏「锚点一会话一次」
|
|
2096
|
+
// 的契约(单测与验收 J-8 都钉着它),并且每回合多烧 600~900 token。
|
|
2097
|
+
// anchorPushed / reinjectPending 只在宿主接纳时清除,长期不回调会卡死;
|
|
2098
|
+
// anchorSeen 是本进程的兜底,不落盘,重启后重发一次,压缩时清空。
|
|
1728
2099
|
const anchorPushedAlready = binding.anchorPushed ?? (binding.injectedIds || []).includes(ANCHOR_SENTINEL)
|
|
1729
|
-
|
|
2100
|
+
// A 方案:锚点仍是一会话一次(契约不变)。首步要有内容,靠的是下面把召回门槛降下来,
|
|
2101
|
+
// 不是靠每回合重发整块索引。anchorSeen 是不依赖接纳回调的进程内兜底。
|
|
2102
|
+
const anchorNeeded = reinject || (anchorPushedAlready !== true && !anchorSeen.has(sessionId))
|
|
1730
2103
|
|
|
1731
2104
|
// Read the present mood before retrieval so the recall ordering can use it.
|
|
1732
2105
|
if (!reinject && !tooShort) setSessionMood(sessionId, readMood(query))
|
|
@@ -1754,13 +2127,20 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
1754
2127
|
} catch {}
|
|
1755
2128
|
const injectionBudget = Math.max(0, totalInjectionBudget - guideReserve)
|
|
1756
2129
|
const totalRoom = () => Math.max(0, injectionBudget - estTokens(parts.join('\n\n')) - (parts.length ? 2 : 0))
|
|
1757
|
-
|
|
2130
|
+
// 媒体块按「人类消息 + sha256」去重:同一条消息里的同一张图只提示一次,
|
|
2131
|
+
// 新消息里重新发同一张图仍然会提示(那是新的附件引用)。
|
|
2132
|
+
const mediaToMark = []
|
|
2133
|
+
if (imageCount && effective.useLibrary && lastUser?.id) {
|
|
1758
2134
|
const current = getSessionBinding(sessionId)
|
|
1759
2135
|
const pending = (current?.pendingMedia || []).slice(-8)
|
|
2136
|
+
.filter(item => item?.sha256 && !mediaServed(sessionId, lastUser.id, item.sha256))
|
|
1760
2137
|
if (pending.length) {
|
|
1761
2138
|
const details = pending.map(item => `${item.sha256} · ${item.captionBy}: ${clip(item.caption || '[图片]', 35)}${item.missing ? ' · missing' : ''}`).join('\n')
|
|
1762
2139
|
const mediaText = ['<memory-media>', truncateToTokens(details, 150), current.stickerHint ? '同图反复出现,可以用 track=habit 聚合表达习惯,不必逐次写记忆。' : '', '只知道描述与引用,不能凭空声称看过像素。attachments 只接受 sha256。', '</memory-media>'].filter(Boolean).join('\n')
|
|
1763
|
-
if (estTokens(mediaText) <= totalRoom())
|
|
2140
|
+
if (estTokens(mediaText) <= totalRoom()) {
|
|
2141
|
+
parts.push(mediaText)
|
|
2142
|
+
mediaToMark.push(...pending.map(item => item.sha256))
|
|
2143
|
+
}
|
|
1764
2144
|
}
|
|
1765
2145
|
}
|
|
1766
2146
|
|
|
@@ -1919,6 +2299,13 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
1919
2299
|
}
|
|
1920
2300
|
|
|
1921
2301
|
if (parts.length === 0) {
|
|
2302
|
+
// 自述:首步到底为什么一条都没投。否则「模型先开口、锚点下一步才到」只能靠猜。
|
|
2303
|
+
if (evalNoteOnce(sessionId, 'step1-empty')) record({ kind: 'system', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: false, level: 'info',
|
|
2304
|
+
message: '注入评估 · 本步无内容 · anchor=' + (anchorNeeded ? 'on' : 'off')
|
|
2305
|
+
+ ' · anchorPushed=' + String(binding.anchorPushed) + ' · reinject=' + String(reinject)
|
|
2306
|
+
+ ' · tooShort=' + String(tooShort) + ' · query=' + query.length + ' 字 · 库=' + (binding.libraryId || 'none')
|
|
2307
|
+
+ ' · 开关=' + (scope.useLibrary ? 'L' : '-') + (scope.useGlobal ? 'G' : '-'),
|
|
2308
|
+
detail: { step: 1, anchorNeeded, reinject, tooShort, queryLen: query.length, anchorTokens: settings.anchorTokens } })
|
|
1922
2309
|
if (inboundKeys.length) finishInbound(sessionId, inboundKeys, memoryClock, { reason: 'no-match', injectedCount: 0 })
|
|
1923
2310
|
return decision
|
|
1924
2311
|
}
|
|
@@ -1934,22 +2321,26 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
1934
2321
|
const rewritten = [...decision.messages]
|
|
1935
2322
|
const index = rewritten.indexOf(lastUser)
|
|
1936
2323
|
if (index < 0) return decision
|
|
1937
|
-
//
|
|
1938
|
-
//
|
|
1939
|
-
//
|
|
1940
|
-
//
|
|
2324
|
+
// 位置口径:记忆块**紧跟在这一步的人类消息之后**(index + 1),且只在批次里真的有
|
|
2325
|
+
// 人类消息时才投。旧口径是前插到用户消息之前,理由是「回应用户前先想起来的上下文」;
|
|
2326
|
+
// 但通道驱动的回合根本走不到这里,实际落点是批次末尾,于是锚点出现在工具调用之后。
|
|
2327
|
+
// 后插在语义上仍然是「用户说完、模型开口之前」,而且跨通道一致。
|
|
1941
2328
|
//
|
|
1942
2329
|
// 关于缓存:v1 审计曾说前插会破坏宿主 KV cache——已证伪。agent/pre-step 是
|
|
1943
2330
|
// waterfall,`payload.messages` 是「这一步从收件箱里新取出的一批」,已缓存的
|
|
1944
2331
|
// 历史前缀逐字未动;createUserMessage 也是新建一条冻结消息,不改旧消息。前插
|
|
1945
2332
|
// 只改变这一批内部的顺序。
|
|
1946
|
-
rewritten.splice(index, 0, message)
|
|
2333
|
+
rewritten.splice(index + 1, 0, message)
|
|
1947
2334
|
deferredActions.anchor = ids.includes(ANCHOR_SENTINEL)
|
|
2335
|
+
if (deferredActions.anchor) anchorSeen.add(sessionId)
|
|
1948
2336
|
deferredActions.nudgeIds = recurringNudgeIds
|
|
1949
2337
|
deferredActions.lexicon = lexiconTurnCommit
|
|
1950
2338
|
deferredActions.patch.lastInjectedUserMessageId = lastUser.id
|
|
1951
2339
|
if (inboundKeys.length) deferredActions.inbound = { keys: inboundKeys, outcome: { reason: 'memory', injectedCount: refs.length } }
|
|
1952
2340
|
proposeInjection(sessionId, turn, message, refs, memoryClock, deferredActions, proposalKey, rewritten, lastUser.id)
|
|
2341
|
+
// 进程内先记「已投」:接纳回调不来时,这就是唯一的幂等依据。
|
|
2342
|
+
markHumanServed(sessionId, lastUser.id)
|
|
2343
|
+
for (const sha of mediaToMark) markMediaServed(sessionId, lastUser.id, sha)
|
|
1953
2344
|
return { ...decision, messages: rewritten }
|
|
1954
2345
|
}
|
|
1955
2346
|
|
|
@@ -2031,7 +2422,11 @@ export function registerInjection(ctx) {
|
|
|
2031
2422
|
const kind = event?.data?.reason?.kind
|
|
2032
2423
|
finishInjectionTurn(failedSessionId, turnNumber, kind, message => ctx.logger?.warn?.(`dsh-memu-memory: ${message}`))
|
|
2033
2424
|
// Compatibility records belong to older paths, not to these proposals.
|
|
2034
|
-
if (kind === 'error' || kind === 'aborted')
|
|
2425
|
+
if (kind === 'error' || kind === 'aborted') {
|
|
2426
|
+
rollbackInjectionForTurn(failedSessionId, turnNumber)
|
|
2427
|
+
// 这一轮没发出去:进程内的「已投」也撤掉,真重试时还能重投。
|
|
2428
|
+
clearInjectionSeen(failedSessionId)
|
|
2429
|
+
}
|
|
2035
2430
|
else consumeInjectionRollback(failedSessionId, turnNumber)
|
|
2036
2431
|
}
|
|
2037
2432
|
} catch (error) {
|
|
@@ -2051,6 +2446,7 @@ export function registerInjection(ctx) {
|
|
|
2051
2446
|
.slice(-REPLAY_MAX)
|
|
2052
2447
|
releaseInjected(sessionId)
|
|
2053
2448
|
markReinjectPending(sessionId)
|
|
2449
|
+
clearInjectionSeen(sessionId)
|
|
2054
2450
|
// The compaction summary drops the plugin's rules message. Flag it so the
|
|
2055
2451
|
// next turn's first step replaces it even though guideRulesKey still matches.
|
|
2056
2452
|
if (before) setSessionBinding(sessionId, { guideLost: true })
|