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/lib/rpc.js CHANGED
@@ -36,6 +36,26 @@ import { runEnvironmentCheck, repairEnvironment, SAFE_REPAIRS, MANUAL_REPAIRS, R
36
36
  import { ALL_LEXICON_ID, GLOBAL_LEXICON_ID } from './lexicon.js'
37
37
  import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
38
38
 
39
+ let rejectionGuardWarned = false
40
+
41
+ function requestRejectionOf(connection, req) {
42
+ try {
43
+ if (typeof connection?.requestRejection === 'function') return connection.requestRejection(req)
44
+ if (typeof connection?.isTrustedApiRequest === 'function') {
45
+ return connection.isTrustedApiRequest(req) === true ? undefined : 401
46
+ }
47
+ } catch { return 403 }
48
+ if (!rejectionGuardWarned) {
49
+ rejectionGuardWarned = true
50
+ try {
51
+ warn('dsh-memu-memory: host exposes no request-rejection guard on connection; falling back to loopback-only admission for the memory RPC')
52
+ } catch {}
53
+ }
54
+ // 没有守卫能力时保持原语义(放行):仓库的取舍是「宁可降级并留一行日志,也不 fail
55
+ // closed」,而逐条库授权(authorizeLibrary)仍在每次请求里生效。风险写进诊断,不静默。
56
+ return undefined
57
+ }
58
+
39
59
  const ENDPOINT = '/dsh-memu-memory'
40
60
 
41
61
  function bindingView(binding) {
@@ -1142,6 +1162,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1142
1162
  'sleepConsolidation', 'sleepAfterIdleMinutes', 'autoCurateEveryHours', 'autoCurateSessionLimit',
1143
1163
  'memoryMode', 'memoryBackend', 'habitsInjection', 'purgeArchivedAfterDays',
1144
1164
  'shortTermTtlHours',
1165
+ // 回合中途补充召回的开关与阈值(lib/inject.js midTurnPolicy):不在名单里
1166
+ // 的 patch 会被静默丢弃,「midTurnRecall: false 可关」必须是可写的。
1167
+ 'midTurnRecall', 'midTurnMinSteps', 'midTurnMinUnits', 'midTurnMinChars',
1168
+ 'midTurnMaxPerTurn', 'midTurnCooldownMs', 'midTurnTokens', 'midTurnFullUnits', 'midTurnFullChars',
1145
1169
  'sidebarSettings', 'visionCaptionEnabled', 'inboundToolNames',
1146
1170
  // 全局提炼的审核模式(spec §6.1):不进 allowlist 的 patch 会被静默丢弃。
1147
1171
  'curatorReviewMode',
@@ -1312,7 +1336,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
1312
1336
  if (!getLibrary(id)) throw new Error('library not found')
1313
1337
  if (getLibrary(id).archived !== true) throw new Error('archive the library before deleting it')
1314
1338
  const safety = await backupDatabases()
1315
- const result = deleteLibrary(id)
1339
+ // 绑定会话还在的库默认拒绝删除(state.deleteLibrary 的新守卫)。force 只在用户
1340
+ // 显式确认过时透传:宿主没发 session/disposed 的死绑定不能变成"永远删不掉"。
1341
+ const result = deleteLibrary(id, { force: payload?.confirmed === true && payload?.force === true })
1316
1342
  if (!result.ok) throw new Error(result.error)
1317
1343
  return { ok: true, safety, archived: archivedLibraryView() }
1318
1344
  }
@@ -2250,15 +2276,20 @@ export function registerRpc(ctx) {
2250
2276
  kind: 'prefix',
2251
2277
  path: ENDPOINT,
2252
2278
  handler: async (req, res) => {
2279
+ // 入口守卫的能力探测(不写版本比较):
2280
+ // 1) 0.2.x:`connection.requestRejection(req)`;
2281
+ // 2) 更早的 rc.8 / 0.1.1:只有 `connection.isTrustedApiRequest(req)`;
2282
+ // 3) 0.2.3-alpha.2:两者都不在 connection 服务上(源码核对:只剩模块级
2283
+ // `isTrustedApiRequest(request, trustedHosts, bindHost, protocol)`)。
2284
+ // 第 3 种没有可用守卫:保持放行(仓库取舍:不 fail closed),但 warn 一次,
2285
+ // 免得「守卫在宿主升级后消失」这件事没人发现。
2253
2286
  // Capability probe, not a version check: `requestRejection` exists on
2254
2287
  // 0.1.2-rc.x and later of dsh-client-connection and not at all on the rc.8
2255
2288
  // / 0.1.1-rc.2 copies, where the service only exposes
2256
2289
  // `isTrustedApiRequest`. Calling it blindly threw a TypeError out of the
2257
2290
  // request handler, which the host turns into a 500 — an unauthenticated
2258
2291
  // caller then learned the route exists instead of being refused.
2259
- const rejection = typeof c.connection?.requestRejection === 'function'
2260
- ? c.connection.requestRejection(req)
2261
- : undefined
2292
+ const rejection = requestRejectionOf(c.connection, req)
2262
2293
  if (rejection !== undefined) {
2263
2294
  const status = rejection === 401 ? 401 : 403
2264
2295
  res.writeHead(status)
package/lib/state.js CHANGED
@@ -165,6 +165,18 @@ export const DEFAULT_SETTINGS = {
165
165
  consolidationTurnLogTools: 'none',
166
166
  // A positive age marks cleanup candidates; deletion always needs a user action.
167
167
  purgeArchivedAfterDays: 0,
168
+ // 回合中途补充召回(inject.js midTurnPolicy):默认开。这些键必须注册在这里——
169
+ // updateSettings 对 DEFAULT_SETTINGS 之外的键静默丢弃,文档里「midTurnRecall: false
170
+ // 可关」的承诺只有落了默认值与白名单才成立。阈值口径见 docs/memory-semantics.md §8.4。
171
+ midTurnRecall: true,
172
+ midTurnMinSteps: 4,
173
+ midTurnMinUnits: 3,
174
+ midTurnMinChars: 6000,
175
+ midTurnMaxPerTurn: 2,
176
+ midTurnCooldownMs: 60000,
177
+ midTurnTokens: 400,
178
+ midTurnFullUnits: 6,
179
+ midTurnFullChars: 15000,
168
180
  }
169
181
 
170
182
  function defaultState() {
@@ -421,6 +433,9 @@ export function updateSettings(patch) {
421
433
  autoCurateEveryHours: [0, 8760], autoCurateSessionLimit: [1, 10], purgeArchivedAfterDays: [0, 36500],
422
434
  activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
423
435
  activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
436
+ midTurnMinSteps: [1, 64], midTurnMinUnits: [1, 200], midTurnMinChars: [0, 200000],
437
+ midTurnMaxPerTurn: [1, 10], midTurnCooldownMs: [0, 600000], midTurnTokens: [120, 2000],
438
+ midTurnFullUnits: [1, 200], midTurnFullChars: [0, 200000],
424
439
  }
425
440
  const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'], consolidationTurnLog: ['on', 'off'], consolidationTurnLogTools: ['none', 'errors', 'summary'], consolidationRunner: ['worker', 'fork'] }
426
441
  for (const [key, value] of Object.entries(patch || {})) {
@@ -661,11 +676,21 @@ export function libraryScopeMissing(lib) {
661
676
 
662
677
  // Hard delete: the sqlite store and its sidecar index leave with the state entry.
663
678
  // Only ever called on an already-archived library, so the caller had to confirm twice.
664
- export function deleteLibrary(id) {
679
+ // `force` exists for the one legitimate case the state cannot see: the caller already
680
+ // unbound every session and knows it. Without it, a library that a live conversation
681
+ // still points at cannot be deleted — the sweep used to be able to put an in-use
682
+ // library into the only state `deleteLibrary` accepts (2026-11-21 外部报告).
683
+ export function deleteLibrary(id, { force = false } = {}) {
665
684
  if (!isSafeId(id)) throw new Error('invalid library id')
666
685
  const state = loadState()
667
686
  if (!state.libraries[id]) return { ok: false, error: 'library not found' }
668
687
  if (state.libraries[id].archived !== true) return { ok: false, error: 'archive the library before deleting it' }
688
+ // 只拦「危险归档 + 仍在用」:扫描误归档的那一类才有一键删掉全部记忆的风险。
689
+ // 用户主动归档仍有绑定会话时照旧允许(删除会连同绑定一起清掉,这是既有语义);
690
+ // 冷数据的旧归档同理放行,否则本机 rp / ai中转站 这类库会变成"永远删不掉"。
691
+ if (!force && archivedWhileInUse(state.libraries[id], { inUse: inUseLibraryIds(state).has(id) })) {
692
+ return { ok: false, error: 'this library was archived while a conversation still uses it; unbind or delete those sessions first (force overrides)' }
693
+ }
669
694
  const activeVectorDb = removeActiveLibrary(id)
670
695
  const legacyVectorDb = path.join(librariesDir(), id + '.sqlite3')
671
696
  delete state.libraries[id]
@@ -788,11 +813,60 @@ export function adoptDefaultLibrary(libraryId, cwd) {
788
813
  return { id: libraryId, ...lib, adopted: true }
789
814
  }
790
815
 
791
- export function archiveLibrary(id) {
816
+ /**
817
+ * 哪些库正被真实会话使用:有存活绑定(`sessionGone !== true`)指向它即算在用。
818
+ *
819
+ * 为什么需要这个判据:归档扫描(cycle.js `runLibraryHousekeeping`)以前只看
820
+ * workspaceRegistry 里注册的目录。IM 插件数据目录、profile 下的目录这类 scope 永远不在
821
+ * 注册表里,于是「建库 → 176 秒后被归档 → 绑定会话继续读写 9 小时」这种自相矛盾的状态
822
+ * 会稳定发生(2026-11-21 外部报告:归档后 172 条活动、6 次召回全部成功,而 UI 里库已经
823
+ * 消失,且它恰好处于 `deleteLibrary` 唯一允许删除的状态)。
824
+ *
825
+ * 只认绑定关系、不掺时间窗口:过期时间会让「刚打开就被归档」在边界上复现,而绑定关系是
826
+ * 确定的事实。传 state 进来是为了让 sweep 一次读盘、只算一次。
827
+ */
828
+ export function inUseLibraryIds(state = null) {
829
+ const snapshot = state || loadState()
830
+ const ids = new Set()
831
+ for (const binding of Object.values(snapshot.sessions || {})) {
832
+ if (!binding || binding.sessionGone === true) continue
833
+ const libraryId = binding.libraryId
834
+ if (!libraryId || !snapshot.libraries?.[libraryId]) continue
835
+ ids.add(libraryId)
836
+ }
837
+ return ids
838
+ }
839
+
840
+ export function isLibraryInUse(id) {
841
+ return Boolean(id) && inUseLibraryIds().has(id)
842
+ }
843
+
844
+ // 1.3.13 及更早的归档没有 `archivedBy`:分不清是用户点的归档还是老扫描误归档。
845
+ // 对这类库只认「还热」的(lastUsedAt 在 14 天内),冷归档按用户意图对待。
846
+ export const ARCHIVE_REVIVE_FRESH_MS = 14 * 86_400_000
847
+
848
+ /**
849
+ * 「归档了但其实还在用」——扫描误归档的判据,同时也是删除守卫的判据。
850
+ *
851
+ * 用户主动归档(`archivedBy === 'user'`)永远不算;扫描归档的(`'sweep'`)永远算;
852
+ * 旧数据按 lastUsedAt 的新鲜度判。两处共用同一个函数,避免"扫描复活、删除又放行"这种
853
+ * 两套口径各说各话。
854
+ */
855
+ export function archivedWhileInUse(lib, { inUse = false, now = Date.now() } = {}) {
856
+ if (!inUse || !lib) return false
857
+ if (lib.archivedBy === 'user') return false
858
+ if (lib.archivedBy === 'sweep') return true
859
+ const lastUsed = Date.parse(lib.lastUsedAt || '') || 0
860
+ return lastUsed > 0 && now - lastUsed <= ARCHIVE_REVIVE_FRESH_MS
861
+ }
862
+
863
+ /** `by` 记录是谁归档的:用户的主动归档不该被扫描悄悄复活。 */
864
+ export function archiveLibrary(id, { by = 'user' } = {}) {
792
865
  const state = loadState()
793
866
  if (!state.libraries[id]) return false
794
867
  state.libraries[id].archived = true
795
868
  state.libraries[id].archivedAt = stamp()
869
+ state.libraries[id].archivedBy = by
796
870
  saveState(state)
797
871
  return true
798
872
  }
@@ -807,6 +881,7 @@ export function restoreLibrary(id) {
807
881
  if (!lib) return { ok: false, error: 'library not found' }
808
882
  lib.archived = false
809
883
  lib.archivedAt = null
884
+ lib.archivedBy = null
810
885
  lib.revivedAt = stamp()
811
886
  lib.lastUsedAt = stamp()
812
887
  saveState(state)
@@ -842,6 +917,15 @@ export function ensureSession(sessionId, { cwd, agentPreset, libraryId = null, c
842
917
  const previous = initial.sessions[sessionId]
843
918
  if (previous?.libraryId && initial.libraries[previous.libraryId]) {
844
919
  const boundLibrary = initial.libraries[previous.libraryId]
920
+ // 一个正在被这个会话读写的库不该停在 archived:归档的语义是「隐藏、准备清理」,
921
+ // 而在用的库既不该消失,也不该落进 `deleteLibrary` 唯一允许删除的状态。旧版扫描
922
+ // 只要 scope 不在 workspaceRegistry 就归档,而这条快路径从不复活,于是库能一边
923
+ // 「归档」一边长数据 9 小时。用户主动归档(archivedBy === 'user')除外。
924
+ if (boundLibrary.archived === true && boundLibrary.archivedBy !== 'user') {
925
+ restoreLibrary(previous.libraryId)
926
+ const revived = loadState().sessions[sessionId]
927
+ if (revived) return revived
928
+ }
845
929
  const libraryScope = normalizeCwd(boundLibrary.scopeKey || '')
846
930
  // Repair the old placeholder bucket as soon as the live conversation reveals
847
931
  // its folder. Without this, every historical Default library stays mislabelled
@@ -1007,6 +1091,64 @@ export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
1007
1091
  return committed ? structuredClone(committed) : null
1008
1092
  }
1009
1093
 
1094
+ /**
1095
+ * 待接纳提案的**落盘**副本(2026-11-23)。
1096
+ *
1097
+ * `injectionAdmissions` 是进程内 Map:宿主重启、或同一个 home 被另一个进程观察时,
1098
+ * 提案会凭空消失,于是接纳永远不会发生——qq-dm 会话 333 个回合里
1099
+ * `acceptedMemoryMessages` 一次都没出现过,就是这么来的(同库的 qq-group 正常)。
1100
+ * 这里只存最小的提交凭据(按消息内容 digest 匹配),观察端换进程也能补完接纳。
1101
+ * 只保留最近 8 条:同一消息重投会被 digest 覆盖,过期条目自然被挤掉。
1102
+ */
1103
+ const PENDING_INJECTION_MAX = 8
1104
+ // 凭据只为「这一轮内的跨进程补认」服务:崩溃错过 turn/end 时它可能残留,
1105
+ // 同内容重投(锚点文本高度重复)会认领到最旧那条、把 turn 归属记错。
1106
+ // 读取时按 30 分钟 TTL 过滤并取最新匹配;写入时顺手清扫过期项。
1107
+ const PENDING_INJECTION_TTL_MS = 30 * 60 * 1000
1108
+
1109
+ function pendingInjectionFresh(item, now = Date.now()) {
1110
+ const at = Date.parse(item?.at || '')
1111
+ return Number.isFinite(at) && now - at < PENDING_INJECTION_TTL_MS
1112
+ }
1113
+
1114
+ export function rememberPendingInjection(sessionId, record = {}) {
1115
+ if (!sessionId || !record.digest || !record.messageId) return null
1116
+ return updateState((state) => {
1117
+ const binding = state.sessions[sessionId]
1118
+ if (!binding) return state
1119
+ const kept = (binding.pendingInjections || []).filter(item => item?.messageId !== record.messageId && pendingInjectionFresh(item))
1120
+ kept.push({
1121
+ digest: String(record.digest), messageId: String(record.messageId),
1122
+ turn: Number(record.turn) || 0, clock: Number(record.clock) || 0,
1123
+ generation: Number(record.generation) || 0, epoch: Number(record.epoch) || 0,
1124
+ refs: Array.isArray(record.refs) ? record.refs : [],
1125
+ actions: record.actions && typeof record.actions === 'object' ? record.actions : {},
1126
+ at: stamp(),
1127
+ })
1128
+ binding.pendingInjections = kept.slice(-PENDING_INJECTION_MAX)
1129
+ return state
1130
+ })
1131
+ }
1132
+
1133
+ export function findPendingInjection(sessionId, digest) {
1134
+ if (!sessionId || !digest) return null
1135
+ const rows = (getSessionBinding(sessionId)?.pendingInjections || [])
1136
+ .filter(item => item?.digest === digest && pendingInjectionFresh(item))
1137
+ return rows[rows.length - 1] || null
1138
+ }
1139
+
1140
+ export function forgetPendingInjection(sessionId, messageId) {
1141
+ if (!sessionId || !messageId) return null
1142
+ return updateState((state) => {
1143
+ const binding = state.sessions[sessionId]
1144
+ if (!binding?.pendingInjections) return state
1145
+ const kept = binding.pendingInjections.filter(item => item?.messageId !== messageId)
1146
+ if (kept.length) binding.pendingInjections = kept
1147
+ else delete binding.pendingInjections
1148
+ return state
1149
+ })
1150
+ }
1151
+
1010
1152
  export function markInjected(sessionId, ids, turn) {
1011
1153
  if (!sessionId) return
1012
1154
  return updateState((state) => {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.3.13",
4
+ "version": "1.3.15",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -31,7 +31,8 @@ test('random cue is injected once and armed', async () => {
31
31
  const sessionEvent = handlers.get('session/event')
32
32
  assert.equal(typeof sessionEvent, 'function')
33
33
  const out = await inject.injectForStep({ agent, decision, turn: 2, step: 1, signal: { aborted: false }, ctx })
34
- const text = out.messages[0]?.content?.[0]?.text || ''
34
+ const pluginMessage = out.messages.find(message => message?.source?.kind === 'plugin:dsh-memu-memory')
35
+ const text = pluginMessage?.content?.[0]?.text || ''
35
36
  assert.ok(text.includes('<memory-cue id="'))
36
37
  assert.equal(state.getActiveCue('cue-session'), null, 'a proposal must not arm the cue')
37
38
  for (const message of out.messages) {
@@ -408,4 +408,161 @@ test('only the host saying the conversation is gone counts as deleted', () => {
408
408
  assert.equal(cycle.isGoneSessionError('this session does not exist any more'), true)
409
409
  assert.equal(cycle.isGoneSessionError("ENOENT: no such file or directory, open 'D:/x/log.jsonl'"), false)
410
410
  assert.equal(cycle.isGoneSessionError('EACCES: permission denied, open D:/x'), false)
411
- })
411
+ })
412
+ // ---------------------------------------------------------------- 归档 vs 在用(2026-11-21 外部报告)
413
+
414
+ // 报告里的真实形态:IM 插件数据目录不是 DSH 工作区,库建好后 176 秒被扫描归档,
415
+ // 而绑定会话继续写 9 小时。这里把那条时间线压成三轮 sweep。
416
+
417
+ test('a library bound to a live conversation is never archived for an unregistered scope', () => {
418
+ const cwd = path.join(home, 'im-in-use')
419
+ state.ensureSession('cycle-im', { cwd })
420
+ const binding = state.getSessionBinding('cycle-im')
421
+ const libId = binding.libraryId
422
+ assert.ok(libId, 'the session created a library')
423
+
424
+ const first = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
425
+ assert.ok(!first.archived.includes(libId), 'an in-use library must not be archived')
426
+ assert.ok(first.skippedInUse.includes(libId), 'the sweep must report why it skipped')
427
+ assert.ok(state.listLibraries().some((lib) => lib.id === libId), 'it stays in the active list')
428
+
429
+ // 连续三轮(≈15 分钟的真实节奏)都不能翻车。
430
+ const second = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
431
+ const third = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
432
+ for (const pass of [second, third]) assert.ok(!pass.archived.includes(libId))
433
+ const lib = state.getLibrary(libId)
434
+ assert.equal(lib.archived, undefined, 'never archived')
435
+ assert.equal(lib.archivedAt, undefined)
436
+ })
437
+
438
+ test('an unbound library with an unregistered scope still archives (the cleanup keeps working)', () => {
439
+ const lib = state.createLibrary({ name: 'cycle-unused', cwd: '/work/cycle-unused' })
440
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
441
+ assert.ok(pass.archived.includes(lib.id), 'nobody uses it, so the old behaviour stands')
442
+ assert.equal(state.getLibrary(lib.id).archivedBy, 'sweep', 'the sweep records that it did the archiving')
443
+ })
444
+
445
+ test('a library the old sweep archived while in use comes back instead of staying hidden', () => {
446
+ const cwd = path.join(home, 'im-misarchived')
447
+ state.ensureSession('cycle-im-revive', { cwd })
448
+ const libId = state.getSessionBinding('cycle-im-revive').libraryId
449
+ // 复现旧版:扫描把在用的库归档,且当时还没有 archivedBy 字段。
450
+ state.archiveLibrary(libId, { by: 'sweep' })
451
+ assert.ok(state.listArchivedLibraries().some((lib) => lib.id === libId))
452
+
453
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
454
+ assert.ok(pass.revived.includes(libId), 'an in-use archive is a bug and must self-heal')
455
+ assert.ok(state.listLibraries().some((lib) => lib.id === libId))
456
+ assert.ok(!pass.archived.includes(libId), 'and it must not be archived again in the same pass')
457
+ })
458
+
459
+ test('a user-archived library is respected even while a conversation still points at it', () => {
460
+ const cwd = path.join(home, 'im-user-archived')
461
+ state.ensureSession('cycle-user-archive', { cwd })
462
+ const libId = state.getSessionBinding('cycle-user-archive').libraryId
463
+ state.archiveLibrary(libId) // 默认 by: 'user'
464
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
465
+ assert.ok(!pass.revived.includes(libId), 'the sweep must not undo a deliberate archive')
466
+ assert.ok(state.listArchivedLibraries().some((lib) => lib.id === libId))
467
+ })
468
+
469
+ test('purging never proposes an archived library that is still in use', () => {
470
+ const cwd = path.join(home, 'im-purge')
471
+ state.ensureSession('cycle-purge', { cwd })
472
+ const libId = state.getSessionBinding('cycle-purge').libraryId
473
+ state.archiveLibrary(libId)
474
+ const st = state.loadState()
475
+ st.libraries[libId].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
476
+ state.saveState(st)
477
+ state.updateSettings({ purgeArchivedAfterDays: 30 })
478
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
479
+ assert.ok(!pass.purgeCandidates.includes(libId), 'age alone must not queue a live library for deletion')
480
+ })
481
+
482
+ test('deleting a library the sweep archived while still in use is refused', () => {
483
+ const cwd = path.join(home, 'im-delete')
484
+ state.ensureSession('cycle-delete', { cwd })
485
+ const libId = state.getSessionBinding('cycle-delete').libraryId
486
+ // 危险类:旧版扫描归档的库(archivedBy='sweep')仍在被会话使用,一次误点就会删掉全部记忆。
487
+ state.archiveLibrary(libId, { by: 'sweep' })
488
+ const refused = state.deleteLibrary(libId)
489
+ assert.equal(refused.ok, false)
490
+ assert.match(refused.error, /still uses it|live conversations/)
491
+ assert.ok(state.getLibrary(libId), 'the refusal leaves the data alone')
492
+
493
+ // 解绑之后不再是「在用」,同一个调用就放行——这正是正常删除流程。
494
+ state.deleteSessionBinding('cycle-delete')
495
+ const allowed = state.deleteLibrary(libId)
496
+ assert.equal(allowed.ok, true, allowed.error || '')
497
+ assert.equal(state.getLibrary(libId), null)
498
+ })
499
+
500
+ test('a user-archived library can still be deleted while a conversation points at it', () => {
501
+ const cwd = path.join(home, 'im-user-delete')
502
+ state.ensureSession('cycle-user-delete', { cwd })
503
+ const libId = state.getSessionBinding('cycle-user-delete').libraryId
504
+ state.archiveLibrary(libId) // by: 'user'
505
+ const result = state.deleteLibrary(libId)
506
+ assert.equal(result.ok, true, result.error || 'the user asked for this; the bindings go with it')
507
+ assert.equal(state.getLibrary(libId), null)
508
+ })
509
+
510
+ test('a session arriving at an archived library revives it through the fast path', () => {
511
+ const cwd = path.join(home, 'im-fastpath')
512
+ state.ensureSession('cycle-fastpath', { cwd })
513
+ const libId = state.getSessionBinding('cycle-fastpath').libraryId
514
+ state.archiveLibrary(libId, { by: 'sweep' })
515
+ // 快路径 = 已绑定会话再来一轮。旧版只刷新 lastUsedAt,库永远停在归档。
516
+ const again = state.ensureSession('cycle-fastpath', { cwd })
517
+ assert.equal(again.libraryId, libId, 'the binding is unchanged')
518
+ const lib = state.getLibrary(libId)
519
+ assert.notEqual(lib.archived, true, 'an in-use library must not stay archived')
520
+ assert.ok(lib.revivedAt)
521
+ })
522
+
523
+ test('a legacy archive with no recorded source is not revived just because an old binding exists', () => {
524
+ // 本机实测:rp(14 个绑定)、ai中转站(4 个)都是「归档 + 还有旧绑定」,但 lastUsed 三周前。
525
+ // 旧数据分不清是用户归档还是老扫描误归档,所以只复活「还热」的;冷的不动。
526
+ const lib = state.createLibrary({ name: 'legacy-cold', cwd: path.join(home, 'legacy-cold') })
527
+ const st = state.loadState()
528
+ st.libraries[lib.id].archived = true
529
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
530
+ st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 30 * 86_400_000).toISOString()
531
+ delete st.libraries[lib.id].archivedBy
532
+ st.sessions['cycle-legacy'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-cold') }
533
+ state.saveState(st)
534
+
535
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
536
+ assert.ok(!pass.revived.includes(lib.id), 'a cold legacy archive stays archived')
537
+ assert.ok(state.listArchivedLibraries().some((row) => row.id === lib.id))
538
+ })
539
+
540
+ test('a warm legacy archive (no source recorded, used minutes ago) is revived', () => {
541
+ const lib = state.createLibrary({ name: 'legacy-warm', cwd: path.join(home, 'legacy-warm') })
542
+ const st = state.loadState()
543
+ st.libraries[lib.id].archived = true
544
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 60_000).toISOString()
545
+ st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 60_000).toISOString()
546
+ delete st.libraries[lib.id].archivedBy
547
+ st.sessions['cycle-warm'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-warm') }
548
+ state.saveState(st)
549
+
550
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
551
+ assert.ok(pass.revived.includes(lib.id), 'a library still being written minutes ago must not stay hidden')
552
+ assert.ok(state.listLibraries().some((row) => row.id === lib.id))
553
+ })
554
+
555
+ test('a cold legacy archive with an old binding can still be deleted', () => {
556
+ // 本机 rp / ai中转站 形态:很久以前归档、仍留着旧绑定、lastUsed 三周前。
557
+ // 它不是扫描误归档(那类会被自愈),也不该因为“有旧绑定”变成永远删不掉。
558
+ const lib = state.createLibrary({ name: 'legacy-deletable', cwd: path.join(home, 'legacy-deletable') })
559
+ const st = state.loadState()
560
+ st.libraries[lib.id].archived = true
561
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
562
+ st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 30 * 86_400_000).toISOString()
563
+ delete st.libraries[lib.id].archivedBy
564
+ st.sessions['cycle-legacy-del'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-deletable') }
565
+ state.saveState(st)
566
+ const result = state.deleteLibrary(lib.id)
567
+ assert.equal(result.ok, true, result.error || '')
568
+ })
@@ -159,7 +159,7 @@ test('with the same anchorTokens, title cards expose at least as many ids as ful
159
159
  `title cards exposed ${anchor.ids.length} ids, full text ${legacy.ids.length}`)
160
160
  })
161
161
 
162
- test('pre-step inserts a plugin message before the user message', async () => {
162
+ test('pre-step inserts a plugin message right after the user message', async () => {
163
163
  const cwd = path.join(home, 'project-step')
164
164
  const binding = state.ensureSession('inject-step', { cwd, agentPreset: 'coding' })
165
165
  const index = state.loadPrivateIndex(binding.libraryId)
@@ -199,13 +199,13 @@ test('pre-step inserts a plugin message before the user message', async () => {
199
199
  const agent = { session: { header: { id: 'inject-step', cwd, agentPreset: 'coding', origin: 'user' } } }
200
200
  const out = await inject.injectForStep({ agent, decision, turn: 1, step: 1, signal: { aborted: false } })
201
201
  assert.equal(out.messages.length, 2)
202
- assert.equal(out.messages[0].role, 'user')
203
- assert.equal(out.messages[0].source.kind, 'plugin:dsh-memu-memory')
204
- assert.equal(out.messages[0].source.plugin, undefined)
205
- assert.equal(out.messages[0].source.form, 'recall')
206
- assert.equal(out.messages[1].source.kind, 'user')
202
+ assert.equal(out.messages[0].source.kind, 'user', 'the human message stays first')
203
+ assert.equal(out.messages[1].role, 'user')
204
+ assert.equal(out.messages[1].source.kind, 'plugin:dsh-memu-memory')
205
+ assert.equal(out.messages[1].source.plugin, undefined)
206
+ assert.equal(out.messages[1].source.form, 'recall')
207
207
 
208
- const injected = out.messages[0].content[0].text
208
+ const injected = out.messages[1].content[0].text
209
209
  assert.ok(injected.includes('[mem-recall]'), 'per-turn recall must surface the matching entry by id')
210
210
  assert.ok(injected.includes('Deploy convention'), 'the title is what reaches the prompt')
211
211
  assert.equal(injected.includes('The deploy script lives in tools/deploy.ps1'), false,
@@ -281,8 +281,8 @@ test('the hint ships in the same plugin message as the recall block', async () =
281
281
  const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [user] }, turn: 1, step: 1, signal: { aborted: false } })
282
282
 
283
283
  assert.equal(out.messages.length, 2)
284
- assert.equal(out.messages[0].source.kind, 'plugin:dsh-memu-memory')
285
- const text = out.messages[0].content[0].text
284
+ assert.equal(out.messages[1].source.kind, 'plugin:dsh-memu-memory', 'memory follows the human turn')
285
+ const text = out.messages[1].content[0].text
286
286
  assert.ok(text.includes('[mem-fresh-message]'))
287
287
  assert.equal((text.match(/<memory-freshness>/g) || []).length, 1)
288
288
  assert.ok(text.indexOf('<memory-freshness>') > text.lastIndexOf('</memory-context>'))
@@ -402,3 +402,41 @@ test('typed cooldown follows content revisions, library identity and a new injec
402
402
  const reinjected = await inject.buildRecall(state.getSessionBinding(id), '部署脚本的位置', 4, settings, exec, id)
403
403
  assert.ok(reinjected.ids.includes('mem-shared-id'))
404
404
  })
405
+
406
+ // ---------------------------------------------------------------- I: mid-turn recall
407
+ // 回合中途补充召回:只可能在非首步、批次无人类消息、inbound 没改动决策时出现;
408
+ // 门 = 步距 + 增量证据 + 每回合上限 + 冷却 + 空召回退避;midTurnRecall 必须是可写设置
409
+ // (1.3.15 审核修正:此前键未注册,updateSettings 会静默丢弃,「可关」是空头承诺)。
410
+
411
+ test('a long tool-only step gets one mid-turn hint card, gated by step distance', async () => {
412
+ const cwd = path.join(home, 'mid-turn')
413
+ state.ensureSession('mid-turn', { cwd, agentPreset: 'coding' })
414
+ const agent = { session: { header: { id: 'mid-turn', cwd, agentPreset: 'coding', origin: 'user' } } }
415
+ const toolMsgs = (n) => Array.from({ length: n }, (_, i) => ({
416
+ id: 'mid-tool-' + i, role: 'tool', source: { kind: 'tool' },
417
+ content: [{ type: 'text', text: 'x'.repeat(120) + ' #' + i }],
418
+ }))
419
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs(3) }, turn: 11, step: 5, signal: { aborted: false } })
420
+ const plugin = out.messages.filter(m => m?.source?.kind === 'plugin:dsh-memu-memory')
421
+ .find(m => String(m?.content?.[0]?.text || '').includes('回合中途补充'))
422
+ assert.ok(plugin, 'step 5 with three distinct tool units earns the hint card')
423
+ const early = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs(3) }, turn: 12, step: 2, signal: { aborted: false } })
424
+ assert.ok(!early.messages.some(m => String(m?.content?.[0]?.text || '').includes('回合中途补充')), 'step 2 cannot clear the four-step gap')
425
+ })
426
+
427
+ test('midTurnRecall:false is a writable kill switch for mid-turn recall', async () => {
428
+ const cwd = path.join(home, 'mid-turn-off')
429
+ state.ensureSession('mid-turn-off', { cwd, agentPreset: 'coding' })
430
+ const agent = { session: { header: { id: 'mid-turn-off', cwd, agentPreset: 'coding', origin: 'user' } } }
431
+ const toolMsgs = Array.from({ length: 3 }, (_, i) => ({
432
+ id: 'off-tool-' + i, role: 'tool', source: { kind: 'tool' },
433
+ content: [{ type: 'text', text: 'y'.repeat(120) + ' #' + i }],
434
+ }))
435
+ const before = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs }, turn: 21, step: 6, signal: { aborted: false } })
436
+ assert.ok(before.messages.some(m => String(m?.content?.[0]?.text || '').includes('回合中途补充')), 'default-on proves the fixture actually reaches the gate')
437
+ const saved = state.updateSettings({ midTurnRecall: false })
438
+ assert.equal(saved.midTurnRecall, false, 'the switch survives updateSettings validation (it is a registered key now)')
439
+ const after = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs }, turn: 22, step: 6, signal: { aborted: false } })
440
+ assert.ok(!after.messages.some(m => String(m?.content?.[0]?.text || '').includes('回合中途补充')), 'the kill switch stops it')
441
+ state.updateSettings({ midTurnRecall: true })
442
+ })
@@ -314,18 +314,19 @@ for (const acceptedPart of ['guide', 'recall']) test(`partial ${acceptedPart} ad
314
314
  assert.deepEqual(facts(session.id), after, 'discarded partial sibling cannot commit late')
315
315
  })
316
316
 
317
- test('proposal reuse preserves pre-human ordering and missing human projection without duplicate IDs', async () => {
317
+ test('proposal reuse preserves post-human ordering and missing human projection without duplicate IDs', async () => {
318
318
  const session = makeSession('projection')
319
319
  const human = user('projection', '林眠的相机镜头修好了吗')
320
320
  const first = await step(session, 1, [human])
321
321
  const memory = first.find(message => ANCHOR_RE.test(textOf(message)))
322
322
  const second = await step(session, 1, [human])
323
323
  assert.equal(second.find(message => ANCHOR_RE.test(textOf(message))).id, memory.id)
324
- assert.ok(second.findIndex(message => message.id === memory.id) < second.findIndex(message => message.id === human.id))
324
+ assert.ok(second.findIndex(message => message.id === memory.id) > second.findIndex(message => message.id === human.id),
325
+ 'memory sits after the human turn')
325
326
  const missing = await step(session, 1, [])
326
327
  assert.equal(missing.filter(message => message.id === human.id).length, 1, 'retry carries the pending human too')
327
328
  assert.equal(missing.filter(message => message.id === memory.id).length, 1)
328
- assert.ok(missing.findIndex(message => message.id === memory.id) < missing.findIndex(message => message.id === human.id))
329
+ assert.ok(missing.findIndex(message => message.id === memory.id) > missing.findIndex(message => message.id === human.id))
329
330
  await accept(session, [human])
330
331
  const nativeAlready = await step(session, 1, [])
331
332
  assert.equal(nativeAlready.some(message => message.id === human.id), false, 'a Native-admitted human is not appended twice')
@@ -42,7 +42,10 @@ test('image-only turns retrieve a saved image and expose the image count in stat
42
42
  const message = { id: 'image-only-native-user', role: 'user', ...event(4).data }
43
43
  const decision = await inject.injectForStep({ agent: exec.agent, decision: { kind: 'enter', messages: [message] }, turn: 2, step: 1 })
44
44
  assert.ok(decision.messages.length > 1)
45
- assert.ok(decision.messages[0].content[0].text.includes(saved.id))
45
+ const injectedText = decision.messages
46
+ .filter(message => message?.source?.kind === 'plugin:dsh-memu-memory')
47
+ .map(message => String(message?.content?.[0]?.text || '')).join('\n')
48
+ assert.ok(injectedText.includes(saved.id))
46
49
  assert.equal(state.getSessionBinding('images').recentQueries.at(-1).imageCount, 1)
47
50
  const tools = []
48
51
  registerTools({ tools: { register: tool => { tools.push(tool); return () => {} } } })
@@ -110,9 +110,10 @@ test('the real tool → recall → injection chain is reachable and carries S1
110
110
  assert.match(datedText, /date=2026-11-07/, 'the resolved absolute date reaches the prompt')
111
111
  assert.match(datedText, /source=assistant_said/)
112
112
  assert.match(datedText, /speaker=assistant/)
113
- // The user message is untouched and the plugin message comes before it.
114
- assert.equal(dated.messages.at(-1).source.kind, 'user')
115
- assert.equal(dated.messages.at(-1).content[0].text, dateUser.content[0].text)
113
+ // The user message is untouched and the plugin message comes right after it.
114
+ assert.equal(dated.messages.at(-2).source.kind, 'user')
115
+ assert.equal(dated.messages.at(-2).content[0].text, dateUser.content[0].text)
116
+ assert.equal(dated.messages.at(-1).source.kind, 'plugin:dsh-memu-memory')
116
117
 
117
118
  const floorUser = {
118
119
  id: 'chain-u2', role: 'user', source: { kind: 'user' },