dsh-memu-memory 1.3.8 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # 更新日志 / Changelog
2
2
 
3
+ ## [1.3.9] - 2026-11-19
4
+
5
+ > 联合扫雷 #3 / #4 / #5:全局提炼兼容两代宿主激活契约、空闲整理不再被熔断/多窗尾段/归档会话/冷 inbound 残骸永久卡死。附带复审修正与保守死代码清理。
6
+
7
+ - **#3 全局提炼兼容两代宿主契约**:`@deepseek-ai/dsh-subagent` 0.2.2-rc.2 把 `SubagentActivationSpec` 扁平化(移除 `request` 外层),0.2.2-rc.2+ 上全局提炼(手动 + 每 6 小时自动)100% 崩溃(`Cannot read properties of undefined (reading 'id')`)。现按 `docs/host-adaptation.md` §3.4 约定用结构探测(`rootOf`/`namesOf` 标记方法)选形态,另带零副作用 `TypeError` 单次回退兜底(核对过两代宿主,均在任何副作用之前抛错);提炼失败现在落 `activity.jsonl`(此前只存内存,重启无痕)。用例:`tests/curator-contract.test.mjs`(flat/nested/双向回退/失败日志四条);`tests/curator.test.mjs`、`tests/curator-probe.test.mjs` 主链路同步改走扁平契约。
8
+ - **#4-1 snapshot-failed 熔断不再假装完工**:同一快照失败达上限的熔断此前返回 `ok:true, settled:true`,`cycle.js` 把游标推平 → 安静会话永久静默、`lastSleepError` 被清、1.3.7 的 `effortRefusal` 自愈结构性失效。现返回 `settled:false`(走 deferred 路径:不推游标、不清错误),熔断加 6 小时冷却(到期清零连击、放行一次真实重试),冻结期内重复扫入不再刷活动日志(同一冻结记录只落一条)。
9
+ - **#4-2 多窗尾段不再悬空**:多窗整理的 `settled` 是「本窗完成」语义,`cycle.js` 却直接推平粗游标——尾段 <200 事件(够不着 backlog 水位)的会话被永久跳过。现仅 `remaining === 0` 时推 `lastSleepAt`;`lastSleepSeq` 本就随回执逐窗推进,不会重扫。
10
+ - **#4-3 归档会话事前跳过**:宿主在 `agent/pre-step` 拒绝祖先含归档会话的 subagent,撞两次就踩进熔断。现 `cycle.js` 候选阶段跳过(不占 budget、不计失败、不推游标),`private.js` 入口拦手动调用并返回 `reasonCode: 'session-archived'`。
11
+ - **#5 冷掉的 inbound 残骸不再永久阻断**:召回异常留下的 `inbound.pending` 只有用户再次发言才被排空,旧代码在候选阶段无条件跳过导致「一次召回异常 + 用户不再发言 = 永不整理且零日志」。现改为热窗判断(队列非空 **且** 最近入站活动 < 15 分钟才让路)。注意不能换用 `hasPendingInbound()`——其语义是「不在 30s 退避期内」,`retryAt` 过期后恒为 true,仍会永久挡死。
12
+ - 全链路回归:`tests/regression-sweep.test.mjs` 7 条(热队列让路 / 冷残骸放行 / 归档候选跳过 / 手动归档拒绝 / 熔断 settled:false + 日志去重 / 冷却放行 / 多窗尾段收口),均走 `runSleepPass → requestPrivateConsolidation → fork → 回执 → 账本` 真实链路;三条 A/B 对照(还原旧代码各跑一次)确认每条用例都能抓住对应旧缺陷。
13
+ - 复审修正与保守清理:拆分 `startGlobalCuration` 合并行;宿主契约注释改引 §3.4 与 src 抛点行号;`inFlight` 诊断行号注释同步 1014;冷却到期去掉与下方共用的重复 `recordOperation`;`cycle.js` 复用 `archivedSessionIdsOf` 消除重复读法。删除死代码 `entryText`(auto-link/decide.js,与 `eligibleEntries` 内联重复)与零引用测试助手 `resetLocalVectorService`。curator-policy 规格常量表、`candidateConfirmationTarget` 等有意单点定义/功能钩子按设计保留。后续:snapshot-failed 冻结回执已带 `cooldownUntil`,据此退避可省冻结期每扫重读快照/种子,但需「冻结感知且不惩罚新活动」的独立字段——直接写 `sleepRetryAt` 会把冻结期到来的新活动一并挡死,故本版未做。
14
+
3
15
  ## [1.3.8] - 2026-11-18
4
16
 
5
17
  > 修复新会话领域弹窗失效(issue #2):点「稍后」的空白会话在「再点新建会话」后永不再问、首轮注入静默按 RP 兜底提炼。附带:RPC 失败不再被当成"已答"、错误落活动日志、隐式绑定可重问、未询问会话的领域兜底跟随 detectDomain。同版并入召回与整理链路优化(R1–R4 / W1/W2 / O1)。
@@ -28,7 +28,7 @@
28
28
  | `ctx.get('agents')`(`list()` / `get()` / `create()`) | `lib/preset-scope.js`、`lib/private.js`、`lib/curator.js` | 未变;`Agent.ctx` 仍在 |
29
29
  | `ctx.get('sessionQuery')`(`listSessions` / `readSession` / `observeSession` / `readTitleSnapshots`) | `lib/rpc.js`、`lib/private.js`、`lib/curator.js` | 包源码未变 |
30
30
  | `ctx.get('workspaceRegistry')` / `domain/changed` | `lib/rpc.js`、`lib/cycle.js` | 未变 |
31
- | `ctx.get('subagents').startActivation` | `lib/curator.js` | 形状未变(`provider`/`label`/`delivery`/`request`/`signal`;结果 `stopReason`/`output`) |
31
+ | `ctx.get('subagents').startActivation` | `lib/curator.js` | **0.2.2-rc.2 起形状变了**:`SubagentActivationSpec` 扁平化(`parent`/`cwd`/`prompt`/`agentOptions` 平铺顶层,移除 `request` 外层),同批新增树内省方法 `rootOf`/`namesOf`/`resolveName`/`waitForTreeWork`。插件按 §3.4 用标记方法做结构探测选形态,另带零副作用 `TypeError` 单次回退兜底(两代宿主都在任何副作用之前抛 `TypeError`);覆盖两代契约的用例在 `tests/curator-contract.test.mjs`。结果 `stopReason`/`output` 未变 |
32
32
  | `ctx.get('attachments').readImage` | `lib/media.js` | 未变 |
33
33
  | `ctx.get('schedule')` | `lib/salient-wake.js` | **变了**:见 §6.1 |
34
34
  | `connection.requestRejection` / `authorizeLibrary` / `webServer.register` | `lib/rpc.js` | 未变;路由仍是 `kind:'prefix'` + `handler` |
@@ -41,10 +41,6 @@ export function eligibleEntries(index) {
41
41
  .map(([id, entry]) => ({ id: String(id), entry, text: `${entry.title || ''}\n${entry.content || ''}` }))
42
42
  }
43
43
 
44
- function entryText(entry) {
45
- return `${entry?.title || ''}\n${entry?.content || ''}`
46
- }
47
-
48
44
  /** One name per normalized key; longest first so the most specific surface wins. */
49
45
  function entitySurfaces(entity) {
50
46
  const seen = new Set()
@@ -54,7 +54,7 @@ export const RUNTIME_STATE = Object.freeze([
54
54
  { layer: 'temporary-map', file: 'lib/inbound.js:13', name: 'calls', keyedBy: 'sessionId', clearedBy: 'tool/result or turn/end' },
55
55
  { layer: 'temporary-map', file: 'lib/inbound.js:14', name: 'sessions', keyedBy: 'sessionId', clearedBy: 'session/disposed (releaseInboundSession)' },
56
56
  { layer: 'temporary-map', file: 'lib/media.js:19', name: 'captures', keyedBy: 'sessionId', clearedBy: 'capture settle' },
57
- { layer: 'temporary-map', file: 'lib/private.js:988', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
57
+ { layer: 'temporary-map', file: 'lib/private.js:1014', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
58
58
  { layer: 'temporary-map', file: 'lib/curator.js:56', name: 'jobs', keyedBy: 'job id', clearedBy: 'curation settle' },
59
59
  { layer: 'cache', file: 'lib/state.js:1392', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
60
60
  { layer: 'cache', file: 'lib/paths.js:52', name: 'readFailures', keyedBy: 'absolute file', clearedBy: 'a later successful read' },
package/lib/curator.js CHANGED
@@ -1626,6 +1626,15 @@ export async function undoGlobalAbsorb({ id } = {}) {
1626
1626
  return { id: mergedId, status: 'archived', undone: true }
1627
1627
  }
1628
1628
 
1629
+ // —— 宿主契约兼容(docs/host-adaptation.md §3.4:形状变化用能力探测,不按版本号分支)——
1630
+ // 0.2.2-rc.2 随 SubagentActivationSpec 扁平化(parent/cwd/prompt/agentOptions 平铺到
1631
+ // 顶层,无 request 外层)同批在 SubagentService 上新增了树内省方法 rootOf/namesOf/
1632
+ // resolveName/waitForTreeWork(0.2.1-rc.5 与 0.2.2-rc.1 上四者均不存在)。用标记方法
1633
+ // 探测形态:真实宿主上一次命中,无多余字段、无异常噪音。
1634
+ function activationUsesFlatSpec(subagents) {
1635
+ return typeof subagents?.rootOf === 'function' || typeof subagents?.namesOf === 'function'
1636
+ }
1637
+
1629
1638
  export function startGlobalCuration(ctx, { sessionIds, parentSessionId, model } = {}) {
1630
1639
  const ids = [...new Set((Array.isArray(sessionIds) ? sessionIds : []).filter((s) => typeof s === 'string' && s.trim()))]
1631
1640
  const jobId = `curate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
@@ -1705,20 +1714,34 @@ export function startGlobalCuration(ctx, { sessionIds, parentSessionId, model }
1705
1714
  const prompt = loadPrompt('global-curator', { input }).text
1706
1715
  job.step = 'curator running'
1707
1716
  log('starting non-main curator subagent')
1708
- const activation = await subagents.startActivation({
1717
+ const curatorModel = model || getSettings().curatorModel
1718
+ const agentOptions = agentOptionsFor(curatorModel)
1719
+ const task = {
1720
+ parent,
1721
+ cwd: parent.session?.header?.cwd,
1722
+ prompt: [{ type: 'text', text: prompt }],
1723
+ ...(agentOptions ? { agentOptions } : {}),
1724
+ }
1725
+ const base = {
1709
1726
  provider: 'spawn',
1710
1727
  label: 'dsh-memu-memory global curator',
1711
1728
  delivery: 'caller',
1712
1729
  signal: abort.signal,
1713
- request: {
1714
- parent,
1715
- cwd: parent.session?.header?.cwd,
1716
- prompt: [{ type: 'text', text: prompt }],
1717
- ...(agentOptionsFor(model || getSettings().curatorModel)
1718
- ? { agentOptions: agentOptionsFor(model || getSettings().curatorModel) }
1719
- : {}),
1720
- },
1721
- })
1730
+ }
1731
+ const flat = activationUsesFlatSpec(subagents)
1732
+ let activation
1733
+ try {
1734
+ activation = await subagents.startActivation(flat ? { ...base, ...task } : { ...base, request: task })
1735
+ } catch (error) {
1736
+ // 零副作用兜底:两代宿主都在产生任何副作用(建子会话、落盘)之前读取形态
1737
+ // 不符的字段并抛 TypeError——旧契约 src/index.ts 读 spec.request.maxDepth
1738
+ //(0.2.1-rc.5:274 / 0.2.2-rc.1:276),0.2.2-rc.2+:275 读 spec.parent.id。遇到
1739
+ // 极简 mock(只提供 startActivation,无从探测)或未来宿主移除标记方法时,catch
1740
+ // 后换另一种形态重试一次是安全的。仅 TypeError 且未被取消时重试,且只重试一次。
1741
+ if (!(error instanceof TypeError) || abort.signal.aborted) throw error
1742
+ log(`activation shape mismatch (${flat ? 'flat' : 'nested'} rejected by TypeError); retrying with ${flat ? 'nested' : 'flat'} shape`)
1743
+ activation = await subagents.startActivation(flat ? { ...base, request: task } : { ...base, ...task })
1744
+ }
1722
1745
  let result
1723
1746
  try {
1724
1747
  result = await activation.result
@@ -1758,6 +1781,15 @@ export function startGlobalCuration(ctx, { sessionIds, parentSessionId, model }
1758
1781
  job.error = String(error?.message || error)
1759
1782
  job.endedAt = new Date().toISOString()
1760
1783
  log(`${job.status}: ${job.error}`)
1784
+ // 失败落活动日志:此前只写内存 job.error,宿主重启后失败原因无从追溯
1785
+ //(issue #3 附带观察)。取消不记——那不是故障。
1786
+ if (!aborted) {
1787
+ record({
1788
+ kind: 'curate', scope: 'global', ok: false, level: 'error',
1789
+ message: '全局提炼失败:' + job.error,
1790
+ detail: { jobId, model: model || getSettings().curatorModel, sessions: ids.length, step: job.step || null },
1791
+ })
1792
+ }
1761
1793
  }
1762
1794
  })()
1763
1795
 
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(),
@@ -10,7 +10,7 @@ import { createVectorMigrator } from './vector-migration.js'
10
10
  import { profileFromCatalog, setRequestedProfile, vectorStatus, assertProfileVerified } from './vector-profile.js'
11
11
  import { embeddingWorkerManager } from './local-embedding-manager.js'
12
12
  import { modelIdForRole } from './local-embedding-protocol.js'
13
- import { managedEmbeddingRuntime, resetManagedEmbeddingRuntime } from './embedding-runtime.js'
13
+ import { managedEmbeddingRuntime } from './embedding-runtime.js'
14
14
 
15
15
  const root = path.join(downloadsDir(), 'embeddings')
16
16
  // 受管 runtime 与模型制品分开放:模型在 downloads/embeddings/<id>,运行时在
@@ -451,12 +451,3 @@ export function closeLocalVectorService() {
451
451
  try { getDownloader().dispose() } catch {}
452
452
  try { getInstaller().abort() } catch {}
453
453
  }
454
-
455
- /** 仅供测试:清掉进程级单例,避免测试之间互相污染。 */
456
- export function resetLocalVectorService() {
457
- try { getDownloader().dispose() } catch {}
458
- downloader = null
459
- migrator = null
460
- installer = null
461
- resetManagedEmbeddingRuntime()
462
- }
package/lib/private.js CHANGED
@@ -186,6 +186,11 @@ export const CONSOLIDATION_WINDOW_EVENTS = 500
186
186
  export const WORKER_WINDOW_EXTEND_EVENTS = 20_000
187
187
  export const CONSOLIDATION_PROBE_MINUTES = 15
188
188
  export const CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2
189
+ // 冻结冷却(issue #4 缺陷 1):同一快照失败到上限后熔断——但熔断不该是永久锁死。
190
+ // 外部条件可能恢复(归档被解除、服务商恢复、effortRefusal 自愈),冷却到期后清零
191
+ // 连击、放行一次真实重试;仍失败则按上限重新冻结并重新计时。每个冷却期最多
192
+ // LIMIT 次真实 fork,成本有界。
193
+ export const CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS = 6 * 60 * 60 * 1000
189
194
  const SEED_TOOL_RESULT_CHARS = 1_100
190
195
  const SEED_TOOL_CALL_CHARS = 500
191
196
  const SEED_TEXT_CHARS = 12_000
@@ -808,10 +813,31 @@ function advanceSleepCursor(sessionId, seq, patch = {}) {
808
813
  return value
809
814
  }
810
815
 
816
+ // 归档会话集合(issue #4 缺陷 3):宿主 workspaceRegistry 的 archivedSessionIds 是
817
+ // 使命名数组;包装成 Set 供 cycle.js 与 private.js 入口共用。注册表缺失/异常时返回
818
+ // null(无信息,不做拦截),与 rpc.js 的读法一致。
819
+ export function archivedSessionIdsOf(ctx) {
820
+ try {
821
+ return new Set((ctx?.get?.('workspaceRegistry')?.archivedSessionIds || []).map(String))
822
+ } catch {
823
+ return null
824
+ }
825
+ }
826
+
811
827
  export async function requestPrivateConsolidation(ctx, sessionId, options = {}) {
812
828
  const binding = getSessionBinding(sessionId)
813
829
  if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
814
830
  if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
831
+ // 归档会话在宿主 agent/pre-step 必被拒("the fork turn ended blocked"),fork 只会
832
+ // 白建一次再计两次失败踩进冻结。cycle.js 已在候选阶段事前跳过;这里拦手动调用,
833
+ // 给出明确的 reasonCode 而不是让用户等到失败回执。
834
+ const archived = archivedSessionIdsOf(ctx)
835
+ if (archived?.size && archived.has(String(sessionId))) {
836
+ return {
837
+ ok: false, skipped: 'session-archived', settled: false, reasonCode: 'session-archived',
838
+ error: 'session is archived; unarchive it before consolidating',
839
+ }
840
+ }
815
841
  // Always a fork, never the live session's own inbox. `agent.followup` on the
816
842
  // chat the user is looking at does queue a real turn — but the host renders a
817
843
  // queued next-turn message as a pending draft above the composer (editable,
@@ -993,7 +1019,7 @@ const inFlight = new Map()
993
1019
  const WORKER_STOP_GRACE_MS = 5_000
994
1020
 
995
1021
  // 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
996
- // 的 file:line 当成诊断契约(当前 lib/private.js:988),修改位置时同步更新该诊断映射,
1022
+ // 的 file:line 当成诊断契约(当前 lib/private.js:1014),修改位置时同步更新该诊断映射,
997
1023
  // 而那是别人的文件、本包不改。ESM 的 import 声明是提升的,写在语句之后合法。
998
1024
  import { warn, dataDir, readJsonStrict, withFileLock, writeJson } from './paths.js'
999
1025
  import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
@@ -1119,6 +1145,10 @@ export const CONSOLIDATION_WAIT_POLICY = Object.freeze({
1119
1145
  // 拒绝不是转录有病、也不是服务商不可达,是参数不匹配,落盘完全安全。
1120
1146
  // 按当前 home 惰性加载;干净缓存只查 Set,失败的读/写留到下一次调用重试。
1121
1147
  const effortRefusalCaches = new Map()
1148
+ // snapshot-failed 冻结期内的活动日志去重(issue #4 缺陷 1):同一份冻结记录
1149
+ // (操作键 → 冻结时间戳)只落一条日志,重复 sweep 扫入静默返回。进程重启清空,
1150
+ // 重启后多落一条,无害。
1151
+ const frozenLogStamps = new Map()
1122
1152
 
1123
1153
  function effortRefusalCache() {
1124
1154
  const file = path.resolve(dataDir(), 'effort-refusals.json')
@@ -1482,10 +1512,30 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1482
1512
  const changedExecution = execution && (!previous.executionSettingsKey || execution.settingsKey !== previous.executionSettingsKey
1483
1513
  || execution.defaultsComparable && execution.key !== previous.executionKey)
1484
1514
  if (!newRefusal && !changedExecution) {
1485
- return finish({
1486
- ok: true, sessionId, skipped: 'snapshot-failed', settled: !outputLimited, reasonCode: 'snapshot-failed-too-many',
1487
- snapshot: snapshotMeta, failures: Number(previous.failures) || 0, lastError,
1488
- })
1515
+ // 冷却(issue #4 缺陷 1):冻结超过冷却期就放行一次真实重试——连击清零交给
1516
+ // 下方与 newRefusal/changedExecution 共用的 recordOperation;否则维持熔断。
1517
+ const frozenAt = Date.parse(previous.at || '') || 0
1518
+ if (Date.now() - frozenAt >= CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS) {
1519
+ warn('consolidation freeze expired: ' + String(previous.reasonCode || 'snapshot-failed') + ' streak reset after cooldown; retrying this window')
1520
+ } else {
1521
+ // settled: false(不再假装这段已整理——那是失败熔断,不是终态跳过):
1522
+ // cycle.js 走 deferred 路径,不推 lastSleepAt、不清 lastSleepError,
1523
+ // 「整理提醒」里保持可见;冷却到期后闸门自动放行重试。
1524
+ const result = {
1525
+ ok: true, sessionId, skipped: 'snapshot-failed', settled: false, deferred: true,
1526
+ reasonCode: 'snapshot-failed-too-many', cooldownUntil: new Date(frozenAt + CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS).toISOString(),
1527
+ snapshot: snapshotMeta, failures: Number(previous.failures) || 0, lastError,
1528
+ }
1529
+ // 冻结期内的重复扫入不重复写活动日志:同一份冻结记录(按 previous.at 判同)
1530
+ // 只在第一次返回时走 finish() 落一条,之后 sweep 每 5 分钟扫进来一次,
1531
+ // 静默返回结果(cycle.js 只记 probe 时间),避免日志刷屏。
1532
+ const freezeStamp = String(previous.at || '')
1533
+ if (frozenLogStamps.get(opKey) !== freezeStamp) {
1534
+ frozenLogStamps.set(opKey, freezeStamp)
1535
+ return finish(result)
1536
+ }
1537
+ return result
1538
+ }
1489
1539
  }
1490
1540
  if (newRefusal) {
1491
1541
  warn('consolidation unfrozen: ' + staleRefusal.key + ' was refused by the model; retrying this window without the effort')
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.8",
4
+ "version": "1.3.9",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -0,0 +1,191 @@
1
+ // Issue #3(dsh-memu-memory#3):宿主 0.2.2-rc.2 把 SubagentActivationSpec 扁平化
2
+ // (parent/cwd/prompt/agentOptions 平铺顶层,无 request 外层),旧契约
3
+ // (0.2.1-rc.5 / 0.2.2-rc.1)把任务字段装在 request 信封里。这里用两种形态的
4
+ // mock 宿主各跑一遍完整的 startGlobalCuration 链路(选形态 → startActivation →
5
+ // 回执 → commit),并验证 TypeError 零副作用回退与失败日志落地。
6
+ import test from 'node:test'
7
+ import assert from 'node:assert/strict'
8
+ import fs from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+ import http from 'node:http'
12
+ import crypto from 'node:crypto'
13
+
14
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-curator-contract-'))
15
+ process.env.DSH_MEMU_HOME = home
16
+
17
+ // commit → embedding 的最小桩(与 curator.test.mjs 同款)。
18
+ function vector(text) {
19
+ const h = crypto.createHash('sha256').update(String(text)).digest()
20
+ const out = []
21
+ for (let i = 0; i < 8; i++) out.push((h[i] / 255) * 2 - 1)
22
+ const norm = Math.sqrt(out.reduce((a, b) => a + b * b, 0)) || 1
23
+ return out.map((x) => x / norm)
24
+ }
25
+ const server = http.createServer((req, res) => {
26
+ let body = ''
27
+ req.on('data', (d) => { body += d })
28
+ req.on('end', () => {
29
+ try {
30
+ const data = JSON.parse(body || '{}')
31
+ const inputs = Array.isArray(data.input) ? data.input : [data.input]
32
+ res.writeHead(200, { 'content-type': 'application/json' })
33
+ res.end(JSON.stringify({
34
+ object: 'list',
35
+ data: inputs.map((text, index) => ({ object: 'embedding', index, embedding: vector(text) })),
36
+ model: data.model || 'test-embed',
37
+ usage: { prompt_tokens: inputs.length, total_tokens: inputs.length },
38
+ }))
39
+ } catch (error) {
40
+ res.writeHead(500, { 'content-type': 'application/json' })
41
+ res.end(JSON.stringify({ error: { message: String(error) } }))
42
+ }
43
+ })
44
+ })
45
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
46
+ process.env.MEMU_EMBED_PROVIDER = 'openai'
47
+ process.env.MEMU_EMBED_MODEL = 'test-embed'
48
+ process.env.MEMU_BASE_URL = `http://127.0.0.1:${server.address().port}/v1`
49
+ process.env.MEMU_API_KEY = 'test-key'
50
+ process.env.OPENAI_API_KEY = 'test-key'
51
+
52
+ const { startGlobalCuration, getCurationJob } = await import('../lib/curator.js')
53
+ const activityLog = await import('../lib/activity-log.js')
54
+
55
+ test.after(async () => {
56
+ await new Promise((resolve) => server.close(resolve))
57
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
58
+ })
59
+
60
+ function ctxFor({ markers = false, mode = 'accept', onSpec = () => {} } = {}) {
61
+ // markers: true → mock 带新版树内省方法(flat 探测命中);false → 极简 mock
62
+ //(只能靠 TypeError 回退兜底)。mode: 'accept' 两种形态都收;'reject-request'
63
+ // 收 flat 拒 nested(老宿主);'reject-flat' 收 nested 拒 flat(模拟探测失灵)。
64
+ const parent = { id: 'parent', session: { header: { cwd: path.join(home, 'project') } } }
65
+ const calls = []
66
+ const subagents = {
67
+ ...(markers ? { rootOf: () => { throw new Error('not used by the plugin') } } : {}),
68
+ startActivation: async (spec) => {
69
+ calls.push(spec)
70
+ onSpec(spec)
71
+ const flat = !('request' in spec)
72
+ if (mode === 'reject-request' && !flat) throw new TypeError('Cannot read properties of undefined (reading \'maxDepth\')')
73
+ if (mode === 'reject-flat' && flat) throw new TypeError('Cannot read properties of undefined (reading \'id\')')
74
+ return {
75
+ result: Promise.resolve({
76
+ stopReason: 'completed',
77
+ output: [{ type: 'text', text: JSON.stringify(curatorOutput()) }],
78
+ }),
79
+ dispose: async () => {},
80
+ }
81
+ },
82
+ }
83
+ return {
84
+ parent,
85
+ calls,
86
+ get(name) {
87
+ if (name === 'agents') return { get: (id) => (id === 'parent' ? parent : undefined) }
88
+ if (name === 'subagents') return subagents
89
+ if (name === 'sessionQuery') {
90
+ return {
91
+ listSessions: async () => [{
92
+ header: { id: 's1', cwd: path.join(home, 'project'), createdAt: Date.now(), agentPreset: 'coding' },
93
+ live: false,
94
+ persisted: true,
95
+ }],
96
+ readTitleSnapshots: async () => [],
97
+ readSession: async () => ({
98
+ session: { id: 's1', cwd: path.join(home, 'project'), agentPreset: 'coding' },
99
+ inheritedEventCount: 0,
100
+ events: [
101
+ { type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'I prefer conclusions first.' }] } },
102
+ { type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'Understood.' }] } } },
103
+ ],
104
+ }),
105
+ }
106
+ }
107
+ return undefined
108
+ },
109
+ }
110
+ }
111
+
112
+ function curatorOutput() {
113
+ return {
114
+ sessions: [{ id: 's1', domain: 'coding', reason: 'code and tool calls' }],
115
+ memories: [{
116
+ op: 'create',
117
+ track: 'memory',
118
+ domain: 'coding',
119
+ applies_to: ['coding'],
120
+ title: 'Prefers conclusion first',
121
+ content: 'The user prefers a conclusion before details in coding tasks.',
122
+ confidence: 0.9,
123
+ evidence: [{ session_id: 's1', quote: 'I prefer conclusions first.' }],
124
+ reason: 'cross-session style',
125
+ }],
126
+ domain_summary: { coding: 'coding preference' },
127
+ skipped: [],
128
+ }
129
+ }
130
+
131
+ async function waitJob(id) {
132
+ for (let i = 0; i < 200; i += 1) {
133
+ const job = getCurationJob(id)
134
+ if (job && job.status !== 'running') return job
135
+ await new Promise((resolve) => setTimeout(resolve, 10))
136
+ }
137
+ throw new Error('curation job did not settle')
138
+ }
139
+
140
+ test('a flat host (0.2.2-rc.2+) receives the task fields at the top level', async () => {
141
+ const ctx = ctxFor({ markers: true })
142
+ const queued = startGlobalCuration(ctx, { sessionIds: ['s1'], parentSessionId: 'parent' })
143
+ const job = await waitJob(queued.id)
144
+ assert.equal(job.status, 'completed', job.error || '')
145
+ assert.equal(ctx.calls.length, 1)
146
+ const spec = ctx.calls[0]
147
+ assert.equal(spec.parent, ctx.parent, 'parent is flat at the top level')
148
+ assert.equal(spec.prompt[0].type, 'text')
149
+ assert.equal(spec.cwd, path.join(home, 'project'))
150
+ assert.ok(!('request' in spec), 'no request envelope on the flat contract')
151
+ })
152
+
153
+ test('a flat-shaped rejection falls back to the nested envelope (future host without the flat path)', async () => {
154
+ const ctx = ctxFor({ markers: true, mode: 'reject-flat' })
155
+ const queued = startGlobalCuration(ctx, { sessionIds: ['s1'], parentSessionId: 'parent' })
156
+ const job = await waitJob(queued.id)
157
+ assert.equal(job.status, 'completed', job.error || '')
158
+ assert.equal(ctx.calls.length, 2, 'one TypeError fallback retry')
159
+ assert.ok(!('request' in ctx.calls[0]), 'first attempt followed the flat detection')
160
+ assert.ok('request' in ctx.calls[1], 'retry used the nested envelope and was accepted')
161
+ assert.equal(ctx.calls[1].request.parent, ctx.parent)
162
+ })
163
+
164
+ test('a bare mock that rejects the nested shape falls back to flat (issue #3 crash path)', async () => {
165
+ const ctx = ctxFor({ markers: false, mode: 'reject-request' })
166
+ const queued = startGlobalCuration(ctx, { sessionIds: ['s1'], parentSessionId: 'parent' })
167
+ const job = await waitJob(queued.id)
168
+ assert.equal(job.status, 'completed', job.error || '')
169
+ assert.equal(ctx.calls.length, 2)
170
+ assert.ok('request' in ctx.calls[0], 'bare mock → nested first (old contract)')
171
+ assert.ok(!('request' in ctx.calls[1]), 'TypeError fallback switched to the flat shape')
172
+ })
173
+
174
+ test('a non-TypeError failure is not retried and lands in activity.jsonl', async () => {
175
+ const parent = { id: 'parent', session: { header: { cwd: path.join(home, 'project') } } }
176
+ const ctx = {
177
+ get(name) {
178
+ if (name === 'agents') return { get: (id) => (id === 'parent' ? parent : undefined) }
179
+ if (name === 'subagents') return { startActivation: async () => { throw new Error('provider spawn is not registered') } }
180
+ if (name === 'sessionQuery') return ctxFor().get('sessionQuery')
181
+ return undefined
182
+ },
183
+ }
184
+ const queued = startGlobalCuration(ctx, { sessionIds: ['s1'], parentSessionId: 'parent' })
185
+ const job = await waitJob(queued.id)
186
+ assert.equal(job.status, 'error')
187
+ assert.match(job.error, /provider spawn is not registered/)
188
+ const events = activityLog.listEvents({ kind: 'curate', limit: 10 })
189
+ const failure = events.find((entry) => entry.ok === false && /provider spawn is not registered/.test(entry.message || ''))
190
+ assert.ok(failure, 'the failure is recorded in activity.jsonl, not only in the in-memory job')
191
+ })
@@ -181,7 +181,7 @@ function ctxFor(events, onActivation) {
181
181
  get(name) {
182
182
  if (name === 'sessionQuery') return sessionQueryFor(events)
183
183
  if (name === 'agents') return { get: (id) => (id === 'parent' ? parent : undefined) }
184
- if (name === 'subagents') return { startActivation: onActivation }
184
+ if (name === 'subagents') return { rootOf: () => { throw new Error('not used by the plugin') }, startActivation: onActivation } // 0.2.2-rc.2+ 树内省标记 → 扁平激活契约
185
185
  return undefined
186
186
  },
187
187
  }
@@ -280,7 +280,7 @@ test('six channels, layer by layer: transcript -> prompt -> simulated output ->
280
280
 
281
281
  const onActivation = async (spec) => {
282
282
  captured = spec
283
- const input = promptInput(spec.request.prompt[0].text)
283
+ const input = promptInput(spec.prompt[0].text)
284
284
  const transcript = input.sessions[0].transcript
285
285
  const existing = JSON.stringify(input.existing_global_index)
286
286
  // A strict copy-through model: it can only echo markers that its prompt
@@ -320,10 +320,10 @@ test('six channels, layer by layer: transcript -> prompt -> simulated output ->
320
320
  assert.ok(captured, 'startGlobalCuration should reach subagents.startActivation')
321
321
  assert.equal(captured.provider, 'spawn')
322
322
  assert.equal(captured.delivery, 'caller')
323
- assert.equal(captured.request.prompt.length, 1)
324
- assert.equal(captured.request.parent.session.header.cwd, path.join(home, 'project'))
323
+ assert.equal(captured.prompt.length, 1)
324
+ assert.equal(captured.parent.session.header.cwd, path.join(home, 'project'))
325
325
 
326
- const prompt = captured.request.prompt[0].text
326
+ const prompt = captured.prompt[0].text
327
327
  assert.match(prompt, /全局记忆提炼任务/)
328
328
  const input = promptInput(prompt)
329
329
  assert.deepEqual(Object.keys(input).sort(), ['candidate_clusters', 'clusters_truncated', 'existing_global_index', 'index_truncated', 'sessions'])
@@ -90,8 +90,10 @@ function fakeContext() {
90
90
  if (name === 'agents') return { get: (id) => id === 'parent' ? parent : undefined }
91
91
  if (name === 'subagents') {
92
92
  return {
93
+ // 0.2.2-rc.2+ 的树内省方法(plugin 用它探测扁平化后的激活契约)。
94
+ rootOf: () => { throw new Error('not used by the plugin') },
93
95
  startActivation: async (spec) => {
94
- assert.equal(spec.request.parent, parent)
96
+ assert.equal(spec.parent, parent, 'flat SubagentActivationSpec (0.2.2-rc.2+)')
95
97
  return {
96
98
  result: Promise.resolve({
97
99
  stopReason: 'completed',
@@ -0,0 +1,281 @@
1
+ // Issue #4 / #5(dsh-memu-memory#4、#5)的 sweep 全链路模拟:
2
+ // #5 冷掉的 inbound.pending 残骸不再永久阻断空闲整理,热队列仍然让路;
3
+ // #4-1 snapshot-failed 熔断不再返回 settled:true(游标不推平、错误不清零)、
4
+ // 冻结期内活动日志去重、冷却到期自动放行真实重试;
5
+ // #4-2 多窗整理 remaining>0 时粗游标不推平,尾段 <200 事件由下一扫收口;
6
+ // #4-3 归档会话在候选阶段事前跳过,手动整理返回明确的 session-archived。
7
+ // 全部走 runSleepPass → requestPrivateConsolidation → fork → 回执 → 账本 的真实链路。
8
+ import test from 'node:test'
9
+ import assert from 'node:assert/strict'
10
+ import fs from 'node:fs'
11
+ import os from 'node:os'
12
+ import path from 'node:path'
13
+
14
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-sweep-issues-'))
15
+ process.env.DSH_MEMU_HOME = home
16
+
17
+ const state = await import('../lib/state.js')
18
+ const cycle = await import('../lib/cycle.js')
19
+ const privateLib = await import('../lib/private.js')
20
+ const ledger = await import('../lib/consolidation-ledger.js')
21
+ const activityLog = await import('../lib/activity-log.js')
22
+
23
+ test.after(() => {
24
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
25
+ })
26
+
27
+ function touchAgo(sessionId, minutesAgo) {
28
+ state.setSessionBinding(sessionId, { lastTurnAt: new Date(Date.now() - minutesAgo * 60_000).toISOString() })
29
+ }
30
+
31
+ // 与 cycle.test.mjs 的 fakeCtx 同款,外加三个旋钮:
32
+ // receipts: 'full'(回执覆盖整段转录,默认)/ 'window'(回执只覆盖本窗种子,
33
+ // 用来模拟多窗的第一窗)/ 'error'(turn 以 error 收尾,走 failJob 退避)。
34
+ // archived: 宿主 workspaceRegistry 的 archivedSessionIds。
35
+ // events: 会话转录(默认一段最小真人对话)。
36
+ function fakeCtx({ live = [], receipts = 'full', archived = [], events = null, inbound = {} } = {}) {
37
+ const liveSet = new Set(live)
38
+ const created = []
39
+ const disposed = []
40
+ const forkFollowups = []
41
+ const sessionHandlers = []
42
+ const transcript = events || [
43
+ { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '帮我看一下这个插件为什么空闲整理从来没跑过,日志里只有 skip 一行' }] } },
44
+ { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '排查结果:inbound 队列里留着召回异常的残骸,把会话挡住了。' }] } } },
45
+ { seq: 2, type: 'turn/end', data: { turn: 0, reason: { kind: 'completed' } } },
46
+ ]
47
+ const ctx = {
48
+ created, disposed, forkFollowups,
49
+ on: (name, handler) => {
50
+ if (name !== 'session/event') return () => {}
51
+ sessionHandlers.push(handler)
52
+ return () => {
53
+ const index = sessionHandlers.indexOf(handler)
54
+ if (index >= 0) sessionHandlers.splice(index, 1)
55
+ }
56
+ },
57
+ get: (name) => {
58
+ if (name === 'agents') {
59
+ return {
60
+ get: (id) => (liveSet.has(id)
61
+ ? { options: { provider: 'test-provider', model: 'test-model' } }
62
+ : undefined),
63
+ create: async (spec) => {
64
+ created.push(spec)
65
+ const childSession = { id: spec.sessionId }
66
+ return {
67
+ agent: {
68
+ session: childSession,
69
+ followup: (message) => {
70
+ forkFollowups.push({ child: spec.sessionId, message })
71
+ if (receipts === 'error') {
72
+ for (const handler of sessionHandlers) {
73
+ handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: 'worker turn blew up' }] } } })
74
+ handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason: { kind: 'error', error: { message: 'the fork turn ended error: simulated' } } } })
75
+ }
76
+ return
77
+ }
78
+ // 回执的 checkedRange:full = 整段转录;window = 本窗(多窗第一窗)。
79
+ // 窗口边界用与 private.js 相同的 selectConsolidationWindow 计算——
80
+ // seed.lastSeq 只是最后一个「对话」事件的 seq(todo/write 不进 seed),
81
+ // 不是窗口边界。
82
+ const childBinding = state.getSessionBinding(spec.sessionId)
83
+ const throughSeq = receipts === 'window'
84
+ ? privateLib.selectConsolidationWindow(transcript, privateLib.CONSOLIDATION_WINDOW_EVENTS).throughSeq
85
+ : transcript[transcript.length - 1].seq
86
+ const proof = {
87
+ version: 1,
88
+ jobId: childBinding.jobId,
89
+ snapshotHash: childBinding.snapshotHash,
90
+ status: 'completed',
91
+ outcome: 'no_value',
92
+ checkedRange: { fromSeq: spec.seed?.fromSeq ?? 0, throughSeq },
93
+ createdIds: [], updatedIds: [], heldIds: [],
94
+ }
95
+ const tick = '```'
96
+ for (const handler of sessionHandlers) {
97
+ handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: tick + 'memu-consolidation-receipt\n' + JSON.stringify(proof) + '\n' + tick }] } } })
98
+ handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason: { kind: 'completed' } } })
99
+ }
100
+ },
101
+ whenIdle: async () => {},
102
+ },
103
+ dispose: async () => { disposed.push(spec.sessionId) },
104
+ }
105
+ },
106
+ }
107
+ }
108
+ if (name === 'sessionQuery') {
109
+ return {
110
+ readSession: async () => ({ events: transcript, session: { cwd: path.join(home, 'p'), agentPreset: 'rp' } }),
111
+ }
112
+ }
113
+ if (name === 'workspaceRegistry') return { archivedSessionIds: archived }
114
+ return undefined
115
+ },
116
+ }
117
+ return ctx
118
+ }
119
+
120
+ function ensureIdle(id, { minutesAgo = 60, inbound = null, lastInboundMinutesAgo = null } = {}) {
121
+ state.ensureSession(id, { cwd: path.join(home, 'p-' + id), agentPreset: 'rp' })
122
+ touchAgo(id, minutesAgo)
123
+ if (inbound) {
124
+ const ago = (m) => new Date(Date.now() - m * 60_000).toISOString()
125
+ state.setSessionBinding(id, {
126
+ inbound,
127
+ ...(lastInboundMinutesAgo !== null ? {
128
+ lastInboundAt: ago(lastInboundMinutesAgo),
129
+ lastInboundOutcome: { reason: 'error', at: ago(lastInboundMinutesAgo), count: inbound.pending.length, injectedCount: 0 },
130
+ } : {}),
131
+ })
132
+ }
133
+ }
134
+
135
+ // 失败后的两条退避时钟都清掉(binding.sleepRetryAt + 账本 entry.retryAt),
136
+ // 让下一扫立刻有资格再次进入,模拟「退避到期后」的时序。
137
+ function clearBackoffs(sessionId) {
138
+ state.setSessionBinding(sessionId, { sleepRetryAt: null, sleepAttempts: 0 })
139
+ patchLedger(sessionId, (entry) => { entry.retryAt = null })
140
+ }
141
+
142
+ // 直接编辑 consolidation.json(mutateLedger 未导出;测试只改自家临时目录里的文件)。
143
+ function patchLedger(sessionId, patch) {
144
+ const file = ledger.ledgerPath()
145
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
146
+ patch(raw.sessions[sessionId])
147
+ fs.writeFileSync(file, JSON.stringify(raw, null, 2), 'utf8')
148
+ }
149
+
150
+ // —— Issue #5:inbound.pending 热窗 ——
151
+
152
+ test('issue #5: a hot inbound queue still defers the sweep', async () => {
153
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
154
+ ensureIdle('issue5-hot', { minutesAgo: 30, inbound: { pending: [{ key: 'k1' }], retryAt: new Date(Date.now() + 20_000).toISOString() }, lastInboundMinutesAgo: 1 })
155
+ const out = await cycle.runSleepPass(fakeCtx({ live: ['issue5-hot'] }))
156
+ assert.equal(out.ran, 0)
157
+ assert.equal(out.considered, 0, 'a hot queue is skipped at the candidate stage, without entering private.js')
158
+ assert.equal(state.getLastSleepAt('issue5-hot'), null)
159
+ })
160
+
161
+ test('issue #5: cold queue residue no longer blocks idle consolidation forever', async () => {
162
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
163
+ ensureIdle('issue5-cold', { minutesAgo: 30, inbound: { pending: [{ key: 'k1' }, { key: 'k2' }, { key: 'k3' }], retryAt: new Date(Date.now() - 3 * 60 * 60_000).toISOString() }, lastInboundMinutesAgo: 3 * 60 })
164
+ const ctx = fakeCtx({ live: ['issue5-cold'] })
165
+ const out = await cycle.runSleepPass(ctx, { limit: 10 })
166
+ assert.equal(out.ran, 1, 'the residue is not drained until the user speaks again, so the sweep must proceed')
167
+ assert.equal(ctx.created.length, 1, 'the fork ran')
168
+ assert.ok(state.getLastSleepAt('issue5-cold'), 'the cursor advanced and the tail is not stranded')
169
+ })
170
+
171
+ // —— Issue #4 缺陷 3:归档会话事前跳过 ——
172
+
173
+ test('issue #4/defect 3: archived sessions are skipped at the candidate stage', async () => {
174
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
175
+ ensureIdle('issue4-arch', { minutesAgo: 30 })
176
+ ensureIdle('issue4-live', { minutesAgo: 30 })
177
+ const ctx = fakeCtx({ live: ['issue4-arch', 'issue4-live'], archived: ['issue4-arch'] })
178
+ const out = await cycle.runSleepPass(ctx, { limit: 10 })
179
+ assert.equal(out.ran, 1, 'only the unarchived session is consolidated')
180
+ assert.deepEqual(ctx.created.map((spec) => spec.meta.parentSession), ['issue4-live'], 'the archived session never becomes a fork and takes no budget slot')
181
+ })
182
+
183
+ test('issue #4/defect 3: a manual consolidation of an archived session is refused with a clear reason', async () => {
184
+ ensureIdle('issue4-arch-manual', { minutesAgo: 30 })
185
+ const ctx = fakeCtx({ live: ['issue4-arch-manual'], archived: ['issue4-arch-manual'] })
186
+ const result = await privateLib.requestPrivateConsolidation(ctx, 'issue4-arch-manual', { force: true })
187
+ assert.equal(result.ok, false)
188
+ assert.equal(result.reasonCode, 'session-archived')
189
+ assert.equal(ctx.created.length, 0, 'no doomed fork is created for an archived session')
190
+ })
191
+
192
+ // —— Issue #4 缺陷 1:snapshot-failed 熔断 ——
193
+
194
+ test('issue #4/defect 1: a frozen snapshot is not settled, keeps the error visible, and never advances the cursor', async () => {
195
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
196
+ ensureIdle('issue4-freeze', { minutesAgo: 60 })
197
+ const errorCtx = () => fakeCtx({ live: ['issue4-freeze'], receipts: 'error' })
198
+ // 两次真实失败 → 同一快照连击到上限(CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2)。
199
+ // 每次失败后的退避到期前不能重试,先把退避清掉模拟「退避过期」的时序。
200
+ await cycle.runSleepPass(errorCtx(), { limit: 10 })
201
+ clearBackoffs('issue4-freeze')
202
+ await cycle.runSleepPass(errorCtx(), { limit: 10 })
203
+ const frozenBinding = state.getSessionBinding('issue4-freeze')
204
+ assert.ok(frozenBinding.lastSleepError, 'the last real failure stays visible')
205
+
206
+ // 第三扫:命中熔断闸门。修复后 settled:false → deferred 路径:
207
+ // 游标不推平、lastSleepError 不清零。
208
+ clearBackoffs('issue4-freeze')
209
+ await cycle.runSleepPass(errorCtx(), { limit: 10 })
210
+ assert.equal(state.getLastSleepAt('issue4-freeze'), null, 'a frozen failure must not flatten the sleep cursor (was settled:true before the fix)')
211
+ assert.ok(state.getSessionBinding('issue4-freeze').lastSleepError, 'the failure is not erased by the frozen gate')
212
+
213
+ // 活动日志去重:同一份冻结记录只落一条 snapshot-failed-too-many。
214
+ const frozenEvents = () => activityLog.listEvents({ kind: 'consolidate', limit: 50 })
215
+ .filter((entry) => entry.detail?.reasonCode === 'snapshot-failed-too-many')
216
+ assert.equal(frozenEvents().length, 1, 'the freeze logs once')
217
+
218
+ clearBackoffs('issue4-freeze')
219
+ await cycle.runSleepPass(errorCtx(), { limit: 10 })
220
+ assert.equal(state.getLastSleepAt('issue4-freeze'), null, 'still frozen on the next sweep')
221
+ assert.equal(frozenEvents().length, 1, 'repeated sweeps inside the freeze do not spam activity.jsonl')
222
+ })
223
+
224
+ test('issue #4/defect 1: the freeze expires after its cooldown and a real retry is allowed', async () => {
225
+ // 沿用上一条冻结的 issue4-freeze:把冻结记录的 at 改到冷却期之外
226
+ //(failures 保持 2),下一扫应当清零连击并真的 fork 一次。
227
+ const frozen = ledger.loadLedger().sessions['issue4-freeze']
228
+ assert.ok(frozen, 'the ledger entry exists')
229
+ const failedKeys = Object.entries(frozen.operations || {})
230
+ .filter(([, op]) => op?.outcome === 'failed' && Number(op?.failures) >= 2)
231
+ assert.ok(failedKeys.length >= 1, 'the failed operation streak is recorded')
232
+ patchLedger('issue4-freeze', (entry) => {
233
+ for (const [key] of failedKeys) {
234
+ entry.operations[key].at = new Date(Date.now() - 7 * 60 * 60_000).toISOString()
235
+ }
236
+ entry.retryAt = null
237
+ })
238
+ state.setSessionBinding('issue4-freeze', { sleepRetryAt: null, sleepAttempts: 0 })
239
+
240
+ const ctx = fakeCtx({ live: ['issue4-freeze'], receipts: 'error' })
241
+ await cycle.runSleepPass(ctx, { limit: 10 })
242
+ assert.equal(ctx.created.length, 1, 'the cooldown expiry lets one real fork through (was frozen forever before the fix)')
243
+ })
244
+
245
+ // —— Issue #4 缺陷 2:多窗尾段 ——
246
+
247
+ test('issue #4/defect 2: a mid-window completion leaves the cursor behind and the tail is picked up by the next sweep', async () => {
248
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
249
+ ensureIdle('issue4-tail', { minutesAgo: 30 })
250
+ // 650 事件:头一段真人对话 + 644 条 todo/write 填充。第一窗切出约 500 条,
251
+ // 余数 < 200(CONSOLIDATION_BACKLOG_EVENTS),修复前会永久悬空。
252
+ const filler = Array.from({ length: privateLib.CONSOLIDATION_WINDOW_EVENTS + 144 }, (_, i) => ({
253
+ seq: 3 + i,
254
+ type: 'todo/write',
255
+ data: { todo: '填充事件 ' + i },
256
+ }))
257
+ const longEvents = [
258
+ { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '我们把整个记忆系统的整理链路从头到尾对一遍账。' }] } },
259
+ { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '好的,先从 sweep 的候选筛选开始。' }] } } },
260
+ { seq: 2, type: 'turn/end', data: { turn: 0, reason: { kind: 'completed' } } },
261
+ ...filler,
262
+ ]
263
+ const ctx = fakeCtx({ live: ['issue4-tail'], receipts: 'window', events: longEvents })
264
+
265
+ // 第一扫:fork 第一窗,回执只覆盖本窗(seed.lastSeq ≈ 502)→ remaining > 0。
266
+ const first = await cycle.runSleepPass(ctx, { limit: 10 })
267
+ assert.equal(first.ran, 1)
268
+ assert.ok(ctx.created.length, 1, 'the first window forked')
269
+ const checkedAfterFirst = ledger.sessionState('issue4-tail')?.checked
270
+ assert.ok(checkedAfterFirst?.throughSeq > 0, 'window 1 advanced the ledger cursor')
271
+ assert.ok(checkedAfterFirst.throughSeq < longEvents[longEvents.length - 1].seq, 'the receipt covered only window 1')
272
+ assert.equal(state.getLastSleepAt('issue4-tail'), null, 'the coarse cursor must NOT advance while remaining > 0 (before the fix it was flattened here and the tail stranded)')
273
+
274
+ // 第二扫:剩余尾段走 no-human-turn 终态跳过(skipRange),整段收口。
275
+ const second = await cycle.runSleepPass(fakeCtx({ live: ['issue4-tail'], receipts: 'window', events: longEvents }), { limit: 10 })
276
+ assert.equal(second.ran, 0, 'the tail sweep is a terminal policy skip, not a worker run')
277
+ const settled = ledger.sessionState('issue4-tail')?.checked
278
+ assert.equal(settled.throughSeq, longEvents[longEvents.length - 1].seq, 'the tail is fully checked — before the fix it stayed pending forever')
279
+ assert.equal(ledger.sessionState('issue4-tail')?.pending, null, 'no pending range left behind')
280
+ assert.ok(state.getLastSleepAt('issue4-tail'), 'the cursor advances once the whole transcript is settled')
281
+ })