dsh-memu-memory 1.3.15 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +49 -1
  3. package/README.md +4 -1
  4. package/README.zh.md +4 -1
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/host-adaptation.md +52 -36
  7. package/docs/host-versions.md +120 -0
  8. package/docs/memory-semantics.md +4 -2
  9. package/docs/pending-work.md +51 -0
  10. package/docs/troubleshooting.md +41 -2
  11. package/lib/auto-link/candidates.js +4 -1
  12. package/lib/auto-link/decide.js +1 -1
  13. package/lib/auto-link/normalize.js +2 -2
  14. package/lib/auto-link/terminology.js +31 -1
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +53 -6
  17. package/lib/consolidation-snapshot.js +7 -1
  18. package/lib/consolidation-worker.js +11 -3
  19. package/lib/curator.js +17 -5
  20. package/lib/cycle.js +75 -4
  21. package/lib/diagnostics.js +10 -0
  22. package/lib/entity-repair.js +285 -0
  23. package/lib/environment-check.js +72 -3
  24. package/lib/global-graph.js +11 -2
  25. package/lib/graph.js +32 -8
  26. package/lib/host-surface.js +30 -0
  27. package/lib/index.js +120 -3
  28. package/lib/inject.js +142 -8
  29. package/lib/memory.js +72 -0
  30. package/lib/private-links.js +12 -0
  31. package/lib/private.js +49 -13
  32. package/lib/prompts/private-consolidation.coding.md +3 -1
  33. package/lib/prompts/private-consolidation.md +2 -0
  34. package/lib/prompts/private-consolidation.mixed.md +2 -0
  35. package/lib/prompts/private-consolidation.rp.md +2 -0
  36. package/lib/prompts/system-guide.coding.md +8 -2
  37. package/lib/prompts/system-guide.md +6 -0
  38. package/lib/prompts/system-guide.mixed.md +11 -0
  39. package/lib/prompts/system-guide.rp.md +6 -0
  40. package/lib/rpc.js +48 -10
  41. package/lib/state.js +5 -1
  42. package/lib/turn-log.js +34 -11
  43. package/lib/worker-pool.js +11 -7
  44. package/package.json +16 -1
  45. package/scripts/chain-matrix.mjs +4 -0
  46. package/scripts/check-doc-drift.mjs +194 -0
  47. package/scripts/entity-dedupe.mjs +110 -0
  48. package/tests/auto-link-candidates.test.mjs +22 -9
  49. package/tests/auto-link-decide.test.mjs +59 -59
  50. package/tests/auto-link-migration.test.mjs +4 -4
  51. package/tests/client-render.test.mjs +112 -1
  52. package/tests/consolidation-fork.test.mjs +20 -1
  53. package/tests/curator-probe.test.mjs +19 -1
  54. package/tests/cycle.test.mjs +2 -2
  55. package/tests/diagnostics.test.mjs +21 -0
  56. package/tests/doc-drift.test.mjs +122 -2
  57. package/tests/entity-merge.test.mjs +17 -0
  58. package/tests/environment-check.test.mjs +28 -0
  59. package/tests/global-graph.test.mjs +16 -0
  60. package/tests/global-lifecycle.test.mjs +24 -4
  61. package/tests/graph-cascade.test.mjs +111 -0
  62. package/tests/hybrid-recall.test.mjs +1 -1
  63. package/tests/inject-guide.test.mjs +108 -1
  64. package/tests/managed-memory.test.mjs +7 -7
  65. package/tests/private-links.test.mjs +12 -0
  66. package/tests/prompts.test.mjs +30 -0
  67. package/tests/recall-corpus-eligibility.test.mjs +3 -3
  68. package/tests/salience-domain.test.mjs +34 -0
  69. package/tests/settings-plumbing.test.mjs +2 -0
  70. package/tests/stale-maintenance.test.mjs +131 -0
  71. package/tests/tools.test.mjs +1 -1
  72. package/tests/turn-log.test.mjs +13 -0
  73. package/tests/webui-auth.test.mjs +58 -0
@@ -52,6 +52,8 @@ WebUI 开着 GPU 占用高 / 时钟钉高档 → §3.28
52
52
  mac 一键安装引擎报 dlopen 签名错 / 事后引擎目录是空的 → §3.31
53
53
  插件内部报错要取证与一键修复 / 启动弹窗 → §3.45
54
54
  库从列表消失但仍在写入 / 召回正常 → §3.46
55
+ 同名新会话整段没有规则消息 / 锚点迟到很久 → §3.47
56
+ 欠账一直提醒却不结案 / 过期草稿越积越多 → §3.48
55
57
  ```
56
58
 
57
59
  ## 3. 出过的问题:症状 → 落点 → 守卫
@@ -760,7 +762,20 @@ grep tests 里的硬编码清单。守卫:全量 `npm test` 1676/1674 pass / 0
760
762
 
761
763
  **原因与修复**:旧候选提取把完整引号或名字引导后的文本再次拆成 n-gram,内部片段也继承表面证据。新候选只给完整称呼背书,并过滤没有独立边界的子片段。模型通过 `memu_private_link` 创建未知实体时,来源记忆本身必须包含完整引号、名字引导加右边界、或两侧分隔的名称,link note 不算来源证据;先校验来源、边类型、理由、置信度和数量限制,再创建 provisional 实体,普通参数错误不再遗留孤立节点。既有实体和别名仍可复用,手动创建与已确认实体的提及匹配保持原规则。
762
764
 
763
- **守卫与旧数据**:`tests/tools.test.mjs` 覆盖四种碎片、虚构理由、Latin 子串、完整姓名/昵称/别名与失败不留节点;`tests/auto-link-candidates.test.mjs` 覆盖完整表面、内部片段和派生缓存。不能仅按字符串把历史节点自动删除或归并——「主人一」也可能是真实昵称;先核对原始记忆,再在关系图中按证据改名、合并或删除。此修复不改写现有记忆或实体。
765
+ **守卫与旧数据**:`tests/tools.test.mjs` 覆盖四种碎片、虚构理由、Latin 子串、完整姓名/昵称/别名与失败不留节点;`tests/auto-link-candidates.test.mjs` 覆盖完整表面、内部片段和派生缓存,以及「窗口片段不提名、但整段就是两字的名字(`星港`)必须留下」。
766
+
767
+ **1.4.0 起,存量碎片按可证明性分两档处理**(此前本节写的是"不改写现有实体",那条口径作废):
768
+
769
+ - `attested`(可证明)——两种情形之一:同组片段能**首尾重叠**拼成一个更长的名字,且那个名字**在该库正文里真的出现过**;或短名在全库正文里的**每一次**出现都在某个更长名字里面。这类在升级后的第一次启动自动合并(写入前先做图备份),合并只走 `lib/graph.js mergeEntities` 那条既有级联:别名并集、`links[].to` 改指、`evidence.entityId` 改指、继承 confirmed、记忆正文一字不动。落点 `lib/entity-repair.js` + `lib/index.js:runEntityRepairPass`。
770
+ - `similar`(只是相似)——编辑距离 ≤2 或名字核重合。**一律不动**:`顾清欢` 与 `顾清悦` 就是被编辑距离撞到一起的两个不同称呼。这类只在诊断页报数,按钮标"需确认"(`MANUAL_REPAIRS` 里的 `merge-entity-fragments`,绝不进 `SAFE_REPAIRS`),或在关系图里逐个核对。
771
+
772
+ 三条必须记住的边界:
773
+
774
+ 1. 「主人一」「人一」这类**不能仅按字符串判定**——先要正文证据。所以判定用的是覆盖性(每一次出现都在长名里面),不是包含关系本身。
775
+ 2. `mergeEntities` 末尾的 `pruneOrphanEntities` 是**全库清扫**,会删掉任何没被引用的实体,包括本次修复没碰的。`entity-repair.js` 因此先读快照、合并后把计划外的行原样写回;守卫用例 `tests/graph-cascade.test.mjs`「the merge cascade never deletes an entity the repair did not plan to touch」。
776
+ 3. 备份失败就**一个字节都不写**,`state.cycle.entityRepairVersion` 保持未写,下次启动再试(诊断记 `ENTITY_REPAIR_DEFERRED`)。整轮只跑一次,第二次返回 `skipped:'done'`;关掉 `autoRepairEntityFragments` 则连可证明的也不动。跨库与全局↔私有的归并仍然不做(`docs/memory-semantics.md` §8.16)。
777
+
778
+ 命令行等价物:`node scripts/entity-dedupe.mjs`(默认 dry-run,`--apply` 先备份;`--include-similar` 才把相似候选一起交给人批量决定)。
764
779
 
765
780
  ### 3.45 诊断页:插件内部到底哪儿坏了(1.3.13 起)
766
781
 
@@ -793,9 +808,33 @@ grep tests 里的硬编码清单。守卫:全量 `npm test` 1676/1674 pass / 0
793
808
  **现在(1.3.14 起)**:
794
809
  - 归档前先看「有没有存活绑定」:`state.inUseLibraryIds()` 按 `sessionGone !== true` 的会话绑定判定;在用的库不归档,结果里给 `skippedInUse`,同一个库只提示一次。
795
810
  - 归档来源写入 `archivedBy`(`sweep` / `user`)。扫描遇到「已归档 + 仍有存活绑定 + 非用户归档」会**就地复活**;`ensureSession` 快路径同样复活误归档库。用户主动归档的不动。
796
- - 旧数据(1.3.13 及更早,没有 `archivedBy`)分不清是谁归档的,所以只复活**还热**的库:`lastUsedAt` 在 14 天内才算误归档;更早的保持归档(本机 `rp` / `ai中转站` 就属于这种「归档 + 旧绑定」的冷数据,升级后不会被突然翻出来)。
811
+ - 旧数据(1.3.13 及更早,没有 `archivedBy`)分不清是谁归档的,所以只复活**还热**的库:`lastUsedAt` 在 14 天内才算误归档;更早的保持归档(本机 `rp` / `另一个工作区库` 就属于这种「归档 + 旧绑定」的冷数据,升级后不会被突然翻出来)。
797
812
  - `deleteLibrary(id)` 只拒绝「危险归档 + 仍在用」这一类(判据 `archivedWhileInUse` 与自愈共用);用户主动归档、冷数据的旧归档照旧可删。RPC 只在 `confirmed` 时透传 `force`;`purgeArchivedAfterDays` 的候选排除在用库。
798
813
 
799
814
  **怎么确认**:`state.json` 里看 `archived` / `archivedBy` / `lastUsedAt` 三者是否自相矛盾;宿主日志搜 `archived library` 与 `kept library`。修好后旧数据在下一轮 sweep(启动后 8 秒或每 5 分钟)或下一条消息时自动复活。
800
815
 
801
816
  **守卫**:`tests/cycle.test.mjs` —— 在用库跨三轮 sweep 不归档且仍在列表、无人用的库照常归档并记 `archivedBy='sweep'`、误归档在用库被复活、用户归档不被复活、purge 不把在用库列入候选、删除在用库被拒(解绑后放行)、快路径复活。
817
+
818
+ ### 3.47 同名新会话整段没有规则消息 / 锚点迟到很久(通道复用会话 id)
819
+
820
+ **症状**:IM 通道(dsh-channel 等)的私聊/群聊里,回合首步有 `[open loop]` 与逐轮召回,却始终没有 `<memory-guide>`,`===== memory anchor =====` 也很久以后才偶然出现一次。`state.json` 里该会话的 `guideRulesKey` 有值、`guideMessageAt` 比宿主会话对象的 `createdAt` 还早,`lastInjectedTurn` 远大于当前转录的回合数。真机(2026-11-26,`qq-dm-1299772830`):新会话对象 16:22 建立,第 1 回合就有记忆块,规则消息直到第 25 回合 20:50 才出现。
821
+
822
+ **落点**:通道用确定性会话 id(`bridge.ts` 的 `qq-dm-<uid>`)跨重启复用,宿主重建同名新会话后转录是空的,而 memu 的 binding 按 id 持久,`guideRulesKey` / `anchorPushed` 还是上一代的。`guideAdmission` / `ensureUnifiedGuide` 的稳态判据只看 binding(`steady && guides.length === 0 → skip`),而 `agent/pre-step` 只给本步批次、看不见历史,于是新转录的首回合被当成「规则早就在」而永久跳过;只有压缩置 `guideLost`、规则/领域变了或回合失败回滚删 key 才会补投。同链缺陷:`ensureUnifiedGuide` 原先在 `injectForStep` 的 try 内,召回抛错(如 `inbound queue is full`)会把规则消息一起吞掉,那一回合记忆块与规则双双缺席。
823
+
824
+ **现在(1.4.1 起)**:`lib/inject.js:syncSessionIncarnation` 每次 pre-step 用宿主会话身份(`session.createdAt`,宿主不暴露时退回「回合号回到 1 + 首条消息 id」)比对 binding 上的 `sessionStamp`;换代就清掉 `guideRulesKey` / `guideMessageAt` / `anchorPushed` / `lastInjectedUserMessageId` 并置 `reinjectPending`,活动日志记一行「同名新会话:一次性投放已重置」。兜底戳只在同一代内稳定,宿主对同一首步重入不会重复重置。guide 的投放移出召回 try,召回故障只写 `lastRecallError` 与 warn,不再带走规则消息。同一入口的 `syncDomainDelivery` 处理**切域**:`injectedDomain` 与当前 `domainOf(binding)` 不一致时清 `guideRulesKey` / `guideMessageAt` / `anchorPushed` / `anniversariesShown` / `openLoopRemindedAt` / `textureKey` 并置 `reinjectPending`——纪念日与未了之事都按领域过滤,切到新领域后必须重投;guide 即使两个领域落到同一份基础稿也照样重投。
825
+
826
+ **怎么确认**:`state.json` 里看 `sessionStamp` 与当前转录是否同代(有 `createdAt` 时以它为准)、`injectedDomain` 与 `domainOf(binding)` 是否一致;活动日志搜「同名新会话」与「记忆领域切换」。规则/锚点恢复后,`guideMessageAt` 会被下一次接纳刷新。
827
+
828
+ **守卫**:`tests/inject-guide.test.mjs` —— 同名新会话重投规则与锚点、无 `createdAt` 时回合号复位只重置一次且重入不重复、召回抛错仍投 guide、切域重投规则/锚点并清掉纪念日与未了之事的记账。
829
+
830
+ ### 3.48 欠账一直提醒却不结案 / 过期草稿越积越多
831
+
832
+ **症状**:`[commitment]` 卡每天还在提示"已逾期 N 天",但库里那条 `commitment.status` 一直是 `open`;或者归档视图里的 `expired` 草稿越积越多,召回又永远看不到它们。
833
+
834
+ **落点**:这是两条"只提醒不结案"的链。承诺逾期只有注入提醒(`dueCommitments` 与 overdue 兜底腿),整理提示词只教"写 `commitment`",没教"按证据结案",于是欠账永远 open。短期草稿过期只改 `status=expired` 退出召回(`isMemoryEligible` 的即时拦截 + `expireShortTerm` 清扫),注释里的"保留供升级"没有期限——`expired` 草稿会永久占索引,只能人工删。
835
+
836
+ **现在(1.4.1 起)**:`[memory-catalog]` 后带**欠账单列**(`overdueOpenCommitments`,最多 8 条),整理页与 worker 任务书要求"先清欠账再查过时"——open 且已过 `due_at` 的承诺按本窗证据写 `done`/`cancelled`/`expired`,没有证据就保留并写明仍欠着;`valid_to` 已过或已被明确取代的旧条目改 `status=archived` 或补正窗口。周期兜底只提示:`runOverdueReviewPass` 对逾期 ≥7 天的 open 承诺写一条 `check` 活动日志(同一条 7 天内不重复,节流表在 `state.cycle.overdueReviewAt`),**不改 status**;过期草稿在 TTL 之后再留 30 天,由 `archiveExpiredDrafts` 改标 `archived`(不删除,正文仍可升回 `long_term`)。口径见 `docs/memory-semantics.md` §8.9。
837
+
838
+ **怎么确认**:活动日志搜「欠账待结案」「过期草稿归档」;`state.json` 的 `cycle.overdueReviewAt` 是节流表;承诺是否结案只看 `commitment.status`(应被整理改成 `done`/`cancelled`/`expired`,周期任务永远不动它)。想让某条提前结案,直接让 agent 调 `memu_private_update` 或整理一次。
839
+
840
+ **守卫**:`tests/stale-maintenance.test.mjs` —— 保留期归档(旧的归档、窗口内不动、legacy 回退 `expiresAt`、活草稿不碰)、逾期判定门槛(open/逾期天数/marginalized/done)、周期提示只写一次且不改状态、目录欠账单列包含 id/due/天数/对象。
@@ -15,7 +15,10 @@ import { buildTermStats, rankCandidates } from './terminology.js'
15
15
  import { normalizeForIndex } from './normalize.js'
16
16
 
17
17
  const CACHE = new Map()
18
- const CANDIDATE_VERSION = 2
18
+ // 3: nomination now drops a statistical term that only ever appears as a window of a
19
+ // longer, equally attested term (南宫晚 / 宫晚晴 out of 南宫晚晴), so the queues written
20
+ // by version 2 must rebuild instead of keeping those rows confirmable.
21
+ const CANDIDATE_VERSION = 3
19
22
 
20
23
  export function candidatesFile(libraryId) {
21
24
  if (!isSafeId(libraryId)) throw new Error('invalid library id')
@@ -58,7 +58,7 @@ function entitySurfaces(entity) {
58
58
  /**
59
59
  * Character-bigram postings over the COMPACT text (punctuation/space removed),
60
60
  * so the prefilter uses exactly the same normalization as `mentionCount`:
61
- * 「小·柚」、小 柚 and 星宫雲-yuike all remain findable. It is only a prefilter —
61
+ * 「小·檀」、小 檀 and 洛云澜-alex all remain findable. It is only a prefilter —
62
62
  * the authoritative boundary check is still `mentionCount` on the raw text.
63
63
  */
64
64
  export function buildMentionIndex(entries) {
@@ -29,7 +29,7 @@ export function hasCjk(token) {
29
29
  /**
30
30
  * Compact form plus each output code unit's position in the normalized source.
31
31
  * `firstMention` needs the raw offset, and the compact index alone is wrong as
32
- * soon as punctuation is removed (「小·柚」 -> 小柚 shifts by two).
32
+ * soon as punctuation is removed (「小·檀」 -> 小檀 shifts by two).
33
33
  */
34
34
  export function compactWithMap(text) {
35
35
  const normalized = String(text || '').normalize('NFKC').toLowerCase()
@@ -45,7 +45,7 @@ export function compactWithMap(text) {
45
45
  /**
46
46
  * Count occurrences of `name` in `text`.
47
47
  * - A name containing CJK is matched as a substring of the compact text, so
48
- * 「小·柚」, 小 柚 and 小柚 are the same surface (§8.1 NFKC + 去标点/空白).
48
+ * 「小·檀」, 小 檀 and 小檀 are the same surface (§8.1 NFKC + 去标点/空白).
49
49
  * - A Latin / identifier name is matched literally (dots, underscores and
50
50
  * hyphens are part of it) on word boundaries, so `yuike` never matches
51
51
  * `yuikeee`, while `yuike.dev` stays one identifier.
@@ -232,6 +232,7 @@ export function rankCandidates(entries, stats, { policy = AUTOLINK_POLICY_V3, le
232
232
  const size = Math.max(1, entries.length)
233
233
  const tier1 = []
234
234
  const tier2 = []
235
+ const rows = []
235
236
  for (const stat of stats.values()) {
236
237
  const term = stat.term
237
238
  if (stat.df < policy.minDf) continue
@@ -266,7 +267,36 @@ export function rankCandidates(entries, stats, { policy = AUTOLINK_POLICY_V3, le
266
267
  intro: isIntro,
267
268
  lexicon: lexiconTier1 ? 'user' : (lexiconModelHit ? 'model-proposal' : null),
268
269
  }
269
- if (isQuoted || isMixed || isIntro || lexiconTier1) tier1.push(row)
270
+ rows.push({ row, evidenced: isQuoted || isMixed || isIntro || lexiconTier1 })
271
+ }
272
+ // A sliding-window fragment is only noise while the longer surface it lives in
273
+ // is at least as well attested: `南宫晚` and `宫晚晴` carry exactly the documents
274
+ // `南宫晚晴` does, so the 4-char form wins and the two windows never reach the
275
+ // queue. A short name that also stands on its own (`星港`, whose 4-char neighbours
276
+ // appear in a single memory) keeps the higher df and survives. Terms with direct
277
+ // surface evidence (quote / identifier / name-intro / user lexicon) are never
278
+ // dropped here — that is evidence, not a statistic.
279
+ // Indexed by fragment instead of compared pairwise: a big library has tens of
280
+ // thousands of candidate n-grams and O(n²) `includes` does not belong in a sweep.
281
+ const statistical = rows.filter((item) => !item.evidenced)
282
+ const longestAttested = new Map()
283
+ for (const { row } of statistical) {
284
+ const chars = [...row.term]
285
+ for (let start = 0; start < chars.length; start += 1) {
286
+ for (let size = 1; start + size <= chars.length; size += 1) {
287
+ if (start === 0 && size === chars.length) continue // only proper substrings count as fragments
288
+ const fragment = chars.slice(start, start + size).join('')
289
+ const known = longestAttested.get(fragment)
290
+ if (known === undefined || row.df > known) longestAttested.set(fragment, row.df)
291
+ }
292
+ }
293
+ }
294
+ const subsumed = new Set(statistical
295
+ .filter(({ row }) => (longestAttested.get(row.term) || 0) >= row.df)
296
+ .map(({ row }) => row.term))
297
+ for (const { row, evidenced } of rows) {
298
+ if (subsumed.has(row.term)) continue
299
+ if (evidenced) tier1.push(row)
270
300
  else tier2.push(row)
271
301
  }
272
302
  const byScore = (a, b) => b.score - a.score || a.term.localeCompare(b.term)
@@ -54,9 +54,9 @@ 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:1040', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
57
+ { layer: 'temporary-map', file: 'lib/private.js:1075', 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
- { layer: 'cache', file: 'lib/state.js:1534', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
59
+ { layer: 'cache', file: 'lib/state.js:1538', 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' },
61
61
  ])
62
62
 
package/lib/client.js CHANGED
@@ -206,6 +206,8 @@ window.__ModuleLoader__.load({
206
206
  pageDiagnostics: '诊断',
207
207
  descDiagnostics: '插件内部的故障与修复记录(含 stderr、目录、修复动作),与活动日志分开存放',
208
208
  diagEnvTitle: '环境自检',
209
+ diagHostSurface: '宿主形状:',
210
+ diagHostSurfaceHint: '这些值来自本插件的宿主能力探测,用于核对 docs/host-versions.md 的台账行;插件不据此分支,也不读宿主版本号。',
209
211
  diagEnvDesc: '启动时与打开本页时各检查一次:数据目录、遗留锁、引擎、向量档案、运行时、模型文件',
210
212
  diagEventsTitle: '诊断记录',
211
213
  diagEventsDesc: '只放插件自己出错的信息,不进 WebUI 常规日志;同一条重复出现只累加次数',
@@ -283,6 +285,9 @@ window.__ModuleLoader__.load({
283
285
  wallFilterScope: '范围',
284
286
  wallFilterStatus: '状态',
285
287
  wallFilterLayer: '层级',
288
+ wallFilterDomain: '域',
289
+ wallDomainAll: '全部域',
290
+ wallDomainHint: '这条记忆属于哪个域。没有标记的旧私有条目按「通用」显示,全局条目按「未知」显示。',
286
291
  wallAllLayers: '全部层级',
287
292
  multiSelect: '多选',
288
293
  wallSelected: '已选 {n} 条',
@@ -301,6 +306,7 @@ window.__ModuleLoader__.load({
301
306
  entityMergeConflict: '({n} 条关系快照与主节点侧冲突,保留主节点侧)',
302
307
  mergeReasonContainment: '名称包含',
303
308
  mergeReasonDistance: '写法相近',
309
+ mergeReasonNameCore: '同一名字的不同写法',
304
310
  openMemu: '打开 MemU WebUI',
305
311
  openGraphStudio: '打开关系图谱',
306
312
  openGraphStudioHint: '在 WebUI 中打开完整关系图谱(浏览器拦下新标签页时在应用内打开)',
@@ -984,6 +990,8 @@ window.__ModuleLoader__.load({
984
990
  autoLinkDeterministic: '确定性写边',
985
991
  autoLinkOff: '关闭',
986
992
  autoLinkHint: '“只出候选”不会写任何边;“确定性写边”只写两类边:已确认实体的提及,以及 conflicts_with / supersedes / 同 fact_key 的字段证据。词面相似度与向量永远不建边。',
993
+ autoRepairEntityFragments: '升级后自动合并名字碎片',
994
+ autoRepairEntityFragmentsHint: '旧版本把中文名的滑窗片段当成了独立人物(两个节点其实是同一个人)。本版本首次启动会扫一遍并在**写入前备份**,但只合并可证明的那一类:片段能首尾重叠重建成一个在正文里出现过的完整名,或短名在正文里从未独立于长名出现。只是名字相近(编辑距离、共同字)的候选一律不动,只在「设置 · 诊断」里报数,由你点「需确认」的按钮处理。关闭此项 = 连可证明的也不动。',
987
995
  firstRunTitle: '先建一个记忆库',
988
996
  firstRunDesc: '还没有任何记忆库。新建一个私有库后,会话里的记忆才有地方落。',
989
997
  firstRunGoLibraries: '去新建库',
@@ -1187,6 +1195,8 @@ window.__ModuleLoader__.load({
1187
1195
  pageDiagnostics: 'Diagnostics',
1188
1196
  descDiagnostics: 'Internal faults and repairs (stderr, paths, repair actions), kept apart from the activity log',
1189
1197
  diagEnvTitle: 'Environment check',
1198
+ diagHostSurface: 'Host shapes:',
1199
+ diagHostSurfaceHint: 'These values come from this plugin\u2019s host capability probes and let you verify a row of the docs/host-versions.md ledger. The plugin never branches on them and never reads a host version.',
1190
1200
  diagEnvDesc: 'Runs at startup and when this page opens: data dir, stale locks, engine, vector profile, runtime, model files',
1191
1201
  diagEventsTitle: 'Diagnostic records',
1192
1202
  diagEventsDesc: 'Plugin-internal errors only, never in the regular WebUI log; repeats bump a counter instead of adding rows',
@@ -1264,6 +1274,9 @@ window.__ModuleLoader__.load({
1264
1274
  wallFilterScope: 'Scope',
1265
1275
  wallFilterStatus: 'Status',
1266
1276
  wallFilterLayer: 'Layer',
1277
+ wallFilterDomain: 'Domain',
1278
+ wallDomainAll: 'All domains',
1279
+ wallDomainHint: 'Which domain this memory belongs to. Older private entries with no stamp show as General, global ones as Unknown.',
1267
1280
  wallAllLayers: 'All layers',
1268
1281
  multiSelect: 'Multi-select',
1269
1282
  wallSelected: '{n} selected',
@@ -1282,6 +1295,7 @@ window.__ModuleLoader__.load({
1282
1295
  entityMergeConflict: '({n} relationship snapshots clashed with the target side and were dropped)',
1283
1296
  mergeReasonContainment: 'Name contained',
1284
1297
  mergeReasonDistance: 'Similar spelling',
1298
+ mergeReasonNameCore: 'Same name, different form',
1285
1299
  openMemu: 'Open MemU WebUI',
1286
1300
  openGraphStudio: 'Open relationship graph',
1287
1301
  openGraphStudioHint: 'Open the full relationship graph in the WebUI (opens in-app when the browser blocks a new tab)',
@@ -1964,6 +1978,8 @@ window.__ModuleLoader__.load({
1964
1978
  autoLinkDeterministic: 'Deterministic edges',
1965
1979
  autoLinkOff: 'Off',
1966
1980
  autoLinkHint: '"Candidates only" writes no edges. "Deterministic edges" writes exactly two kinds: mentions of confirmed entities, and field evidence from conflicts_with / supersedes / the same fact_key. Lexical similarity and vectors never create an edge.',
1981
+ autoRepairEntityFragments: 'Auto-merge name fragments after upgrade',
1982
+ autoRepairEntityFragmentsHint: 'Older versions turned sliding windows of a Chinese name into separate entities, so one person ended up as two nodes. On the first start after an upgrade the plugin scans once and backs up before writing, but merges only the provable class: fragments that overlap head-to-tail into a longer name which actually appears in a memory body, or a short name that never appears outside a longer one anywhere in the library. Merely similar names (edit distance, a shared character) are never touched - they are only counted on Settings / Diagnostics behind a "needs confirmation" button. Off means even the provable class waits for you.',
1967
1983
  firstRunTitle: 'Create a memory library first',
1968
1984
  firstRunDesc: 'There are no libraries yet. Memories from your conversations need one to land in.',
1969
1985
  firstRunGoLibraries: 'Create a library',
@@ -2979,6 +2995,8 @@ html[data-standalone]:has(.dshm-root.is-graph-navless) .stage{padding-left:28px;
2979
2995
  // memory quietly claiming to be a quote.
2980
2996
  const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred', imagined: 'sourceImagined', told: 'sourceTold' }
2981
2997
  const DOMAIN_LABELS = { general: 'dmGeneral', coding: 'dmCoding', rp: 'dmRp', mixed: 'dmMixed', universal: 'dmUniversal', personal: 'dmPersonal', other: 'dmOther', unknown: 'dmUnknown' }
2998
+ // suggestEntityMerges 的三种理由;新增理由必须同时加键,否则界面只显示英文原词。
2999
+ const MERGE_REASON_LABEL_KEYS = { containment: 'mergeReasonContainment', 'edit-distance': 'mergeReasonDistance', 'name-core': 'mergeReasonNameCore' }
2982
3000
  const INJECT_LABELS = { smart: 'modeSmart', 'anchor-only': 'modeAnchor', 'per-turn': 'modePerTurn', off: 'modeOff' }
2983
3001
 
2984
3002
  // Unknown values fall through verbatim: a newer host enum must stay readable
@@ -3524,7 +3542,8 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
3524
3542
  setError(failures.length ? t('gsLoadPartial') + failures.join(', ') : '')
3525
3543
  } else {
3526
3544
  const value = showGlobal
3527
- ? await call('getGraph', { scope: 'global', focusId: focus || null, depth: 2, limit: 200 })
3545
+ ? await call('getGraph', { scope: 'global', focusId: focus || null, depth: 2, limit: 200,
3546
+ domain: graphDomain || undefined })
3528
3547
  : await readLibrary(graphLibrary)
3529
3548
  if (!alive) return
3530
3549
  setGraph(value && Array.isArray(value.nodes)
@@ -3877,6 +3896,8 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
3877
3896
  h('div', { className: 'dshm-gs-tags' },
3878
3897
  h('span', { className: 'dshm-gs-tag' }, String(selected.kind || 'memory')),
3879
3898
  selected.layer ? h('span', { className: 'dshm-gs-tag neutral' }, String(selected.layer)) : null,
3899
+ // Memory nodes carry their domain from the server; entity nodes do not.
3900
+ selected.domain ? h('span', { className: 'dshm-gs-tag neutral' }, domainText(t, selected.domain)) : null,
3880
3901
  selected.status === 'provisional' ? h('span', { className: 'dshm-gs-tag warn' }, t('gsPending')) : null))),
3881
3902
  h('dl', { className: 'dshm-gs-kv' },
3882
3903
  h('dt', null, 'ID'), h('dd', null, String(selected.rawId || selected.id)),
@@ -4410,7 +4431,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4410
4431
  const key = 'merge:' + item.sourceId + '>' + item.targetId
4411
4432
  return h('div', { key, className: 'dshm-graph-tools' },
4412
4433
  h('span', { style: { minWidth: 0, overflowWrap: 'anywhere' } }, entityLabel(item.sourceId) + ' → ' + entityLabel(item.targetId)),
4413
- h(Tag, { tone: 'info' }, item.reason === 'containment' ? t('mergeReasonContainment') : t('mergeReasonDistance')),
4434
+ h(Tag, { tone: 'info' }, t(MERGE_REASON_LABEL_KEYS[item.reason] || 'mergeReasonDistance')),
4414
4435
  h(Button, {
4415
4436
  style: armed === key ? { ...S.btn, color: V.danger, borderColor: V.danger } : S.btn,
4416
4437
  title: t('entityMergeHint'),
@@ -4539,6 +4560,8 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4539
4560
  const [multiBlocked, setMultiBlocked] = React.useState(false)
4540
4561
  const [pool, setPool] = React.useState('active')
4541
4562
  const [layer, setLayer] = React.useState('all')
4563
+ // 域筛选交给服务端:browseWall 一次最多回 300 条,客户端筛完再看计数会骗人。
4564
+ const [wallDomain, setWallDomain] = React.useState('')
4542
4565
  const [query, setQuery] = React.useState('')
4543
4566
  const [error, setError] = React.useState('')
4544
4567
  const [version, setVersion] = React.useState(0)
@@ -4581,7 +4604,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4581
4604
  const current = () => alive && requestId === browseRequest.current
4582
4605
  const load = async () => {
4583
4606
  try {
4584
- const value = await call('browseWall', { libraryId: libraryId || null, limit: 300 })
4607
+ const value = await call('browseWall', { libraryId: libraryId || null, limit: 300, domain: wallDomain || undefined })
4585
4608
  if (!current()) return
4586
4609
  setData(value)
4587
4610
  setError('')
@@ -4593,7 +4616,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4593
4616
  // 不再整页空。用户可手动切换库;多库选项保留为禁用。
4594
4617
  if (!libraryId && firstLibraryId && /forbidden|403/i.test(message)) {
4595
4618
  try {
4596
- const value = await call('browseWall', { libraryId: firstLibraryId, limit: 300 })
4619
+ const value = await call('browseWall', { libraryId: firstLibraryId, limit: 300, domain: wallDomain || undefined })
4597
4620
  // A newer selection owns the wall now; do not force the reader
4598
4621
  // back to the first library from a fallback they did not ask for.
4599
4622
  if (!current()) return
@@ -4612,7 +4635,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4612
4635
  }
4613
4636
  void load()
4614
4637
  return () => { alive = false }
4615
- }, [call, libraryId, revision, stamp, version, firstLibraryId])
4638
+ }, [call, libraryId, revision, stamp, version, firstLibraryId, wallDomain])
4616
4639
  React.useEffect(() => {
4617
4640
  if (!detail) return undefined
4618
4641
  const onKey = (event) => { if (event.key === 'Escape') setDetail(null) }
@@ -4896,6 +4919,9 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4896
4919
  h(Tag, { tone: shown.source === 'imagined' ? 'warn' : (shown.source === 'user_said' ? 'info' : undefined) },
4897
4920
  enumText(t, SOURCE_LABELS, shown.source)),
4898
4921
  h(Tag, null, enumText(t, STATUS_LABELS, shown.status)),
4922
+ // 「这条记忆来自哪个域」是用户判断它为什么会出现在这里的第一线索;
4923
+ // 私有条目取 browseWall 的归一值,全局条目取 listGlobal 的 stamp 或 unknown。
4924
+ h(Tag, { title: t('wallDomainHint') }, domainText(t, shown.domain || detail.item?.domain || 'general')),
4899
4925
  // 这条记忆有没有进向量库,直接写在条目上(remember 提交成功后落盘)。
4900
4926
  shown.vector
4901
4927
  ? h(Tag, { tone: 'info' }, `${t('vectorIndexedTag')}${shown.vector.model ? ' · ' + shown.vector.model : ''}${shown.vector.generation ? ' · g' + shown.vector.generation : ''}`)
@@ -5007,6 +5033,17 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5007
5033
  h('option', { value: '', disabled: multiBlocked }, t('allLibraries')),
5008
5034
  libraries.map((lib) => h('option', { key: lib.id, value: lib.id }, libraryOptionLabel(lib, libraries))))
5009
5035
  : null
5036
+ // 域候选来自服务端的完整并集(不受当前筛选影响),所以选了某个域之后仍能换。
5037
+ const domainOptions = [...new Set([...(Array.isArray(data?.domains) ? data.domains : []), wallDomain].filter(Boolean))].sort()
5038
+ const domainSelect = h('select', {
5039
+ value: wallDomain,
5040
+ title: t('wallDomainHint'),
5041
+ 'aria-label': t('wallFilterDomain'),
5042
+ style: { ...S.input, flex: '0 1 150px', minWidth: 130, maxWidth: 220 },
5043
+ onChange: (event) => setWallDomain(event.target.value),
5044
+ },
5045
+ h('option', { value: '' }, t('wallDomainAll')),
5046
+ domainOptions.map(value => h('option', { key: value, value }, domainText(t, value))))
5010
5047
  const hasOptionControls = true
5011
5048
  const multiToggle = h(Button, {
5012
5049
  'aria-pressed': multi,
@@ -5057,7 +5094,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5057
5094
  multiBlocked && scope === 'private' ? h('span', { style: S.muted, role: 'status' }, t('wallAllBlocked')) : null,
5058
5095
  data?.total > items.length ? h('span', { style: S.muted }, t('wallLimit') + ` (${items.length}/${data.total})`) : null) : null,
5059
5096
  wallTabGroup(poolItems, pool, setPool, { label: t('wallFilterStatus'), marginTop: 12 }),
5060
- wallTabGroup(layerItems, layer, setLayer, { label: t('wallFilterLayer'), marginTop: 10 }),
5097
+ wallTabGroup(layerItems, layer, setLayer, { label: t('wallFilterLayer'), marginTop: 10, extra: domainSelect }),
5061
5098
  visible.length ? h('div', { className: 'dshm-wall-grid' }, visible.map(item =>
5062
5099
  h('button', {
5063
5100
  key: keyOf(item), type: 'button', className: 'dshm-wall-item' + (multi && selectedIds.has(keyOf(item)) ? ' is-selected' : ''),
@@ -5078,6 +5115,8 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5078
5115
  h('p', null, item.preview),
5079
5116
  h('div', { className: 'dshm-wall-tags' },
5080
5117
  h(Tag, null, enumText(t, SOURCE_LABELS, item.source)),
5118
+ // 域筛选关着时才在卡面出域;筛完每张卡同一个域,再写一遍只是噪音。
5119
+ !wallDomain ? h(Tag, { title: t('wallDomainHint') }, domainText(t, item.domain || 'general')) : null,
5081
5120
  item.status !== 'active' ? h(Tag, { tone: 'warn' }, enumText(t, STATUS_LABELS, item.status)) : null,
5082
5121
  item.openLoop ? h(Tag, null, t('openLoopTag')) : null,
5083
5122
  item.attachmentCount ? h(Tag, null, '▧ ' + item.attachmentCount) : null),
@@ -7435,6 +7474,9 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
7435
7474
  h('option', { value: 'deterministic' }, t('autoLinkDeterministic')),
7436
7475
  h('option', { value: 'off' }, t('autoLinkOff')))),
7437
7476
  h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('autoLinkHint')),
7477
+ // 升级后的一次性碎片自愈。默认开,但只合"可证明"的那一类;相似候选永远等人工确认。
7478
+ h(Field, { label: t('autoRepairEntityFragments') }, h(Toggle, { checked: settings.autoRepairEntityFragments !== false, label: t('autoRepairEntityFragments'), onChange: value => setSetting('autoRepairEntityFragments', value) })),
7479
+ h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('autoRepairEntityFragmentsHint')),
7438
7480
  h(Field, { label: h('span', { style: { color: V.danger } }, t('consolidationRunner'), h('span', { style: { marginLeft: 6, fontWeight: 600 } }, t('consolidationRunnerExperimental'))) },
7439
7481
  h('select', { style: S.input, value: settings.consolidationRunner || 'fork', onChange: (e) => setSetting('consolidationRunner', e.target.value) },
7440
7482
  h('option', { value: 'fork' }, t('consolidationRunnerFork')),
@@ -8527,6 +8569,11 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
8527
8569
  right: diagButtons,
8528
8570
  },
8529
8571
  diagNotice ? h('div', { style: { ...S.muted, marginBottom: 8, color: V.accent } }, diagNotice) : null,
8572
+ // docs/host-versions.md §13.6:把本机实际命中的宿主形状摆在页面上,核对台账一行只要看一眼。
8573
+ state?.hostSurface ? h('div', {
8574
+ style: { ...S.muted, marginBottom: 8, fontFamily: 'monospace', fontSize: 12, overflowWrap: 'anywhere' },
8575
+ title: t('diagHostSurfaceHint'),
8576
+ }, `${t('diagHostSurface')} ${Object.entries(state.hostSurface).map(([name, value]) => `${name}=${value}`).join(' ')}`) : null,
8530
8577
  diagEnvList)
8531
8578
  const diagEventRow = (entry) => h('div', { key: entry.id, style: S.item },
8532
8579
  h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'center' } },
@@ -1,6 +1,7 @@
1
1
  import crypto from 'node:crypto'
2
2
  import { stamp } from './paths.js'
3
3
  import { recordDiagnostic } from './diagnostics.js'
4
+ import { noteHostSurface } from './host-surface.js'
4
5
 
5
6
  // C 包:把「读一份会话」从一个隐式的整段读盘,变成一个显式的、有身份的固定快照。
6
7
  //
@@ -214,10 +215,15 @@ async function defaultLoadColdLogModule() {
214
215
  for (const spec of COLD_LOG_MODULES) {
215
216
  try {
216
217
  const mod = await import(spec)
217
- if (typeof mod?.readColdSessionLog === 'function') return mod
218
+ if (typeof mod?.readColdSessionLog === 'function') {
219
+ // §13.6 结构指纹:记下真正命中的模块,供真机核对台账的 coldLog 一项。
220
+ noteHostSurface('coldLog', COLD_LOG_MODULES.indexOf(spec) === 0 ? 'session-query' : 'session')
221
+ return mod
222
+ }
218
223
  tried.push(spec + ': no readColdSessionLog')
219
224
  } catch (error) { tried.push(spec + ': ' + (error?.code || error?.message || 'import failed')) }
220
225
  }
226
+ noteHostSurface('coldLog', 'none')
221
227
  noteColdLogGap({ modules: tried })
222
228
  return {}
223
229
  }
@@ -170,7 +170,8 @@ function rangeLine(snapshot) {
170
170
  * worker 的任务书:身份、范围、可用工具、回执契约。
171
171
  * 这不是「人格」,是职责——所以它不描述风格,只描述能做什么、不能做什么、怎么交差。
172
172
  */
173
- export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason = 'auto', jobId = null, mustCover = [], autoReceipt = false, singleOnly = false } = {}) {
173
+ export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason = 'auto', jobId = null, mustCover = [], autoReceipt = false, singleOnly = false, domain = 'general' } = {}) {
174
+ const coding = String(domain) === 'coding'
174
175
  const ptc = probe?.ptcObserved === true
175
176
  const sdkShape = singleOnly
176
177
  ? 'await tools.memu_private_remember({...}) / await tools.memu_private_update({...})'
@@ -193,11 +194,18 @@ export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason
193
194
  : '直接写,不要再检索:目录和召回命中已经给出。真正新增的条目合并成一次 memu_private_remember_batch({items:[...]}) 提交:每个窗口只发一次 batch,不要逐条 remember;只有本窗只写 1 条时才用 memu_private_remember。目录里已有的同一事实用 memu_private_update(用目录里的 id)合并,能合并的更新也放在同一轮里,不要一条一轮来回。',
194
195
  '时间锚点:每条用户消息前的 [事件时间 YYYY-MM-DD HH:mm] 是那一轮的发生时间;observed_at 填这个时间,今天/明天/下周X/月底按它算绝对日期;不要用整理时的入库时间,也不要用真实时钟。',
195
196
  '写库字段:speaker_id、source_kind、observed_at、absolute_date 必填;冲突用 conflicts_with,明确取代用 supersedes;助手说过的话用 source_kind=assistant_said;承诺写 commitment。',
196
- '按价值排序:约定/承诺 = 新人物首次出现/换人接手/称呼变化 > 日期/改口/冲突 > 身份/边界/第三方人物 > 偏好/计划 > 其他明确事实。前两类必须写;每窗最多新增 8 条,普通事实最多 3 条,必写候选不受限,总数仍不超过 8 条。',
197
+ coding
198
+ // 工程记忆的价值排序与写入形状和 RP 完全不同:中文工程结论落在 RP 排序的
199
+ // "其他明确事实"里会被"普通事实最多 3 条"挤掉,所以任务书按域分叉。
200
+ ? '按价值排序:根因与修复理由 = 接口/不变量变化 = 环境与版本约束 = 被否决方案及其失败条件 > 验证结论与测试范围 > 需求/验收变化 > 工作偏好 > 其余明确事实。前两类必须写,每窗最多新增 8 条;工程结论不受「普通事实最多 3 条」限制,必写候选不受限,总数仍不超过 8 条。'
201
+ : '按价值排序:约定/承诺 = 新人物首次出现/换人接手/称呼变化 > 日期/改口/冲突 > 身份/边界/第三方人物 > 偏好/计划 > 其他明确事实。前两类必须写;每窗最多新增 8 条,普通事实最多 3 条,必写候选不受限,总数仍不超过 8 条。',
197
202
  '同一件事有两种说法时各写一条,用 conflicts_with 互指;只有明确取代才用 supersedes,旧正文保留。承诺/约定写 commitment。',
203
+ '先清欠账再查过时:目录「欠账」里 open 且已过 due_at 的承诺,按本窗证据结案(done/cancelled/expired),没有证据就保留 open 并写明仍欠着谁;valid_to 已过或已被明确取代的旧条目用 memu_private_update 归档或补正窗口,旧正文保留。',
198
204
  // 2026-11-15:link 裁决步骤写进任务书——触发时机明示,模型不再靠读工具参数说明猜。
199
205
  '写完条目后用本轮创建/更新的 id 调一次 memu_private_link_suggest,返回的候选【逐条】裁决:有具体证据的用 memu_private_link 连(note 引用转录原句作依据),没有证据的明确放弃,不许全部留着不裁决。触发时机:同一事实的新版本→连到旧条(取代关系);同一个人的多条记忆→挂到命名实体 entity {name, kind};承诺/约定→commitment;两条互斥→conflict。相似≠相连,宁缺毋滥。',
200
- 'content 写 50–150 字,只保留人物、地点、时间、事情、原话/说话人;emotion 只在叙事确实有情绪瞬间时填写,普通事实省略;不要复述整段对话,不要写成行为日志。',
206
+ coding
207
+ ? 'content 写 150–350 字,按「结论 / 作用范围与定位(路径 + 符号,行号只作辅助)/ 条件与原因 / 验证状态」排;标题写结论本身(模块、符号、错误签名或命令),不要「修复了异步问题」这类空话;不写人物地点与原文模板,不复述整段对话。emotion 与 dominance 只属于人物侧条目,工程事实省略。'
208
+ : 'content 写 50–150 字,只保留人物、地点、时间、事情、原话/说话人;emotion 只在叙事确实有情绪瞬间时填写,普通事实省略;不要复述整段对话,不要写成行为日志。',
201
209
  ...(Array.isArray(mustCover) && mustCover.length > 0
202
210
  ? [
203
211
  '本窗必写候选(先写这些,再写其他;每条都必须落库,或在失败说明里写明为什么不写,不得静默跳过):',
package/lib/curator.js CHANGED
@@ -121,8 +121,20 @@ function eventCallId(event) {
121
121
  * 次调用的双写,以 tool/call 事件为准——块只在没有对应事件时保留(先按 callId
122
122
  * 配对;两侧都没有 id 时按 name+arguments 计数配对,支持重复调用)。字符预算
123
123
  * 保留原行为,另加可选 token 预算(累计 estTokens 超预算即停)。
124
+ * 工具行额度可按域覆盖:编码域的修改重点在命令/错误签名/参数里,300/400 只够开头。
124
125
  */
125
- export function condenseEvents(events, maxChars = MAX_SESSION_CHARS, { maxTokens = Infinity } = {}) {
126
+ export const CONDENSE_TOOL_RESULT_CHARS = 400
127
+ export const CONDENSE_TOOL_CALL_CHARS = 300
128
+ const CONDENSE_TOOL_RESULT_CHARS_CODING = 1_400
129
+ const CONDENSE_TOOL_CALL_CHARS_CODING = 700
130
+
131
+ export function condenseLimitsFor(domain) {
132
+ return String(domain) === 'coding'
133
+ ? { toolResultChars: CONDENSE_TOOL_RESULT_CHARS_CODING, toolCallChars: CONDENSE_TOOL_CALL_CHARS_CODING }
134
+ : { toolResultChars: CONDENSE_TOOL_RESULT_CHARS, toolCallChars: CONDENSE_TOOL_CALL_CHARS }
135
+ }
136
+
137
+ export function condenseEvents(events, maxChars = MAX_SESSION_CHARS, { maxTokens = Infinity, toolResultChars = CONDENSE_TOOL_RESULT_CHARS, toolCallChars = CONDENSE_TOOL_CALL_CHARS } = {}) {
126
138
  // 事件侧先收一遍:callId 集合 + (name, arguments) 计数,供块侧配对。
127
139
  const eventCallIds = new Set()
128
140
  const eventSignatures = new Map()
@@ -159,17 +171,17 @@ export function condenseEvents(events, maxChars = MAX_SESSION_CHARS, { maxTokens
159
171
  claimedSignatures.set(key, (claimedSignatures.get(key) || 0) + 1)
160
172
  continue
161
173
  }
162
- lines.push(`Tool call: ${b.name}${b.arguments ? ` ${truncate(argsText(b.arguments), 300)}` : ''}`)
174
+ lines.push(`Tool call: ${b.name}${b.arguments ? ` ${truncate(argsText(b.arguments), toolCallChars)}` : ''}`)
163
175
  }
164
176
  continue
165
177
  }
166
178
  if (type === 'tool/result') {
167
179
  const text = textOf(event.data?.message?.content)
168
- if (text) lines.push(`Tool result${event.data?.message?.isError ? ' (error)' : ''}: ${truncate(text, 400)}`)
180
+ if (text) lines.push(`Tool result${event.data?.message?.isError ? ' (error)' : ''}: ${truncate(text, toolResultChars)}`)
169
181
  continue
170
182
  }
171
183
  if (type === 'tool/call') {
172
- lines.push(`Tool call: ${event.data?.name || '?'} ${truncate(argsText(event.data?.arguments), 300)}`)
184
+ lines.push(`Tool call: ${event.data?.name || '?'} ${truncate(argsText(event.data?.arguments), toolCallChars)}`)
173
185
  }
174
186
  } catch {}
175
187
  }
@@ -1631,7 +1643,7 @@ export async function undoGlobalAbsorb({ id } = {}) {
1631
1643
  // 顶层,无 request 外层)同批在 SubagentService 上新增了树内省方法 rootOf/namesOf/
1632
1644
  // resolveName/waitForTreeWork(0.2.1-rc.5 与 0.2.2-rc.1 上四者均不存在)。用标记方法
1633
1645
  // 探测形态:真实宿主上一次命中,无多余字段、无异常噪音。
1634
- function activationUsesFlatSpec(subagents) {
1646
+ export function activationUsesFlatSpec(subagents) {
1635
1647
  return typeof subagents?.rootOf === 'function' || typeof subagents?.namesOf === 'function'
1636
1648
  }
1637
1649
 
package/lib/cycle.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  getCycleState, setCycleState, listLibrariesAll, archiveLibrary, setSessionBinding,
4
4
  deleteLibrary, restoreLibrary, normalizeCwd, inUseLibraryIds, archivedWhileInUse,
5
5
  } from './state.js'
6
- import { expireShortTerm } from './memory.js'
6
+ import { expireShortTerm, archiveExpiredDrafts, overdueOpenCommitments, EXPIRED_DRAFT_RETENTION_DAYS } from './memory.js'
7
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'
@@ -42,16 +42,86 @@ function older(a, b) {
42
42
  // Short-term expiry. Runs before the sleep pass on purpose: a draft that is already
43
43
  // past its deadline must not be offered to consolidation as something worth keeping,
44
44
  // and promoting a dead entry would resurrect text nobody asked for again.
45
+ // 过期之后的保留期也在同一趟里结算:超期草稿改标 archived(不删除),
46
+ // 免得"第二机会"变成永久占位。
45
47
  export function runShortTermPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
46
48
  try {
47
49
  const result = expireShortTerm({ now })
48
50
  if (result.expired.length > 0) {
49
51
  log(`expired ${result.expired.length} short-term memor${result.expired.length === 1 ? 'y' : 'ies'} in ${result.libraries.length} library(ies)`)
50
52
  }
51
- return result
53
+ let archived = { archived: [], libraries: [], skipped: 0 }
54
+ try {
55
+ archived = archiveExpiredDrafts({ now })
56
+ if (archived.archived.length > 0) {
57
+ log(`archived ${archived.archived.length} expired draft(s) past the retention window`)
58
+ record({
59
+ kind: 'check',
60
+ scope: 'private',
61
+ ok: true,
62
+ message: `过期草稿归档 · ${archived.archived.length} 条(保留期 ${EXPIRED_DRAFT_RETENTION_DAYS} 天,不删除正文)`,
63
+ detail: { ids: archived.archived.map((row) => row.id), libraries: archived.libraries },
64
+ })
65
+ }
66
+ } catch (error) {
67
+ log(`expired draft archiving failed: ${error?.message || error}`)
68
+ }
69
+ return { ...result, archived }
52
70
  } catch (error) {
53
71
  log(`short-term expiry failed: ${error?.message || error}`)
54
- return { expired: [], libraries: [], error: String(error?.message || error) }
72
+ return { expired: [], libraries: [], skipped: 0, archived: { archived: [], libraries: [], skipped: 0 }, error: String(error?.message || error) }
73
+ }
74
+ }
75
+
76
+ // 逾期承诺的周期提醒:只写一条活动日志提示"该结案了",绝不改 status。
77
+ // 承诺有没有兑现要靠转录证据(由整理任务书交给 worker),清理策略不替人裁决。
78
+ // 同一条承诺 7 天内只提示一次,避免每天刷屏。
79
+ const OVERDUE_REVIEW_DAYS = 7
80
+ const OVERDUE_REVIEW_REPEAT_MS = 7 * 86_400_000
81
+ const OVERDUE_REVIEW_KEYS = 500
82
+
83
+ export function runOverdueReviewPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
84
+ try {
85
+ const seen = { ...(getCycleState().overdueReviewAt || {}) }
86
+ const noted = []
87
+ const liveKeys = new Set()
88
+ for (const lib of listLibrariesAll()) {
89
+ if (lib.archived === true) continue
90
+ const rows = overdueOpenCommitments({ libraryId: lib.id, now, minOverdueDays: OVERDUE_REVIEW_DAYS })
91
+ for (const row of rows) liveKeys.add(`${lib.id}:${row.id}`)
92
+ const due = rows.filter((row) => {
93
+ const last = Date.parse(seen[`${lib.id}:${row.id}`] || '') || 0
94
+ return !last || now - last >= OVERDUE_REVIEW_REPEAT_MS
95
+ })
96
+ if (due.length === 0) continue
97
+ const at = new Date(now).toISOString()
98
+ for (const row of due) {
99
+ seen[`${lib.id}:${row.id}`] = at
100
+ noted.push({ libraryId: lib.id, id: row.id, daysOverdue: row.daysOverdue })
101
+ }
102
+ record({
103
+ kind: 'check',
104
+ scope: 'private',
105
+ libraryId: lib.id,
106
+ ok: true,
107
+ message: `欠账待结案 · ${due.length} 条承诺逾期 ≥${OVERDUE_REVIEW_DAYS} 天(整理时按证据结案)`,
108
+ detail: { ids: due.map((row) => row.id), daysOverdue: due.map((row) => row.daysOverdue) },
109
+ })
110
+ log(`overdue commitments in ${lib.id}: ${due.length} past ${OVERDUE_REVIEW_DAYS} days`)
111
+ }
112
+ // 标记表只留还欠着的 + 60 天内的记录,上限 500,避免无限长。
113
+ const cutoff = now - 60 * 86_400_000
114
+ const kept = Object.entries(seen)
115
+ .filter(([key, at]) => liveKeys.has(key) || (Date.parse(at) || 0) >= cutoff)
116
+ .sort((a, b) => (Date.parse(b[1]) || 0) - (Date.parse(a[1]) || 0))
117
+ .slice(0, OVERDUE_REVIEW_KEYS)
118
+ if (noted.length > 0 || kept.length !== Object.keys(seen).length) {
119
+ setCycleState({ overdueReviewAt: Object.fromEntries(kept) })
120
+ }
121
+ return { noted: noted.length, rows: noted }
122
+ } catch (error) {
123
+ log(`overdue commitment review failed: ${error?.message || error}`)
124
+ return { noted: 0, rows: [], error: String(error?.message || error) }
55
125
  }
56
126
  }
57
127
 
@@ -378,6 +448,7 @@ export function runLibraryHousekeeping(ctx, { now = Date.now(), log = () => {} }
378
448
 
379
449
  export async function runCyclePasses(ctx, options = {}) {
380
450
  const shortTerm = runShortTermPass(ctx, options)
451
+ const overdue = runOverdueReviewPass(ctx, options)
381
452
  // turn-log GC 挂在 sweep 顺带跑(§3.4),只做 stat/绑定表级别的便宜检查。
382
453
  const turnLogs = runTurnLogGcPass(ctx, options)
383
454
  const sleep = await runSleepPass(ctx, options)
@@ -394,7 +465,7 @@ export async function runCyclePasses(ctx, options = {}) {
394
465
  try { options.log?.(`salient wake pass failed: ${error?.message || error}`) } catch {}
395
466
  return { created: 0, cleaned: 0, skipped: 0, errors: 1 }
396
467
  })
397
- return { shortTerm, turnLogs, sleep, curate, libraries, migrated, salientWake }
468
+ return { shortTerm, overdue, turnLogs, sleep, curate, libraries, migrated, salientWake }
398
469
  }
399
470
 
400
471
  // DSH has no host scheduler a plugin can register a *global* job with