sage-mem 2.33.0 → 2.33.2

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/README.en.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  **Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.**
14
14
 
15
- **Current release: `2.33.0`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
15
+ **Current release: `2.33.2`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
16
16
  [frozen contract](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md).
17
17
 
18
18
  If it is useful to you, a Star is the most direct feedback.
@@ -29,8 +29,14 @@ If it is useful to you, a Star is the most direct feedback.
29
29
  - [Write Safety](#write-safety)
30
30
  - [Size Governance: What to Do When a Memory Grows Too Big](#size-governance-what-to-do-when-a-memory-grows-too-big)
31
31
  - [Autodream](#autodream)
32
- - [Initial memory](#initial-memory-scaffold-the-library-with-an-agent-2120)
33
32
  - [Migrating from Claude Code](#migrating-from-claude-code)
33
+ - [Memory Reminder Before Compaction](#memory-reminder-before-compaction-experimental--2170)
34
+ - [To-do Board](#to-do-board-experimental--since-2111-wrapped-up-in-2150)
35
+ - [Initial memory](#initial-memory-scaffold-the-library-with-an-agent-2120)
36
+ - [External access](#external-access-let-other-agents-read-a-copy-2250)
37
+ - [Incoming submissions](#incoming-submissions-other-agents-can-submit-only-you-let-them-in-2260)
38
+ - [Cross-device check](#cross-device-check-see-clearly-before-touching-anything-2270)
39
+ - [Cross-device pull](#cross-device-pull-fetch-it-in-one-ssh-round-trip-2280)
34
40
  - [Configuration Reference](#configuration-reference)
35
41
  - [Stability and Versioning Policy](#stability-and-versioning-policy)
36
42
  - [Permissions and Privacy](#permissions-and-privacy)
@@ -530,9 +536,9 @@ Each tier fires once per session and re-arms after a compaction; **subagent sess
530
536
 
531
537
  **Cost**: when off it does nothing at all — it does not even measure the context. When on, each step reads a switch and a window projection (cheap); only past half the window does it take one precise measurement (on the same waterfall as the compaction engine, where the cache is already warm). **It cannot make the model comply** — it is a reminder, not a guarantee.
532
538
 
533
- ## To-do Board (experimental · since 2.11.0; wrapped up in 2.15.0)
539
+ ## To-do Board (experimental · since 2.11.1; wrapped up in 2.15.0)
534
540
 
535
- `project_session-state.md` in the memory directory has always been a to-do list you keep for yourself: injected into every session, but you still have to open the file to see what is left. 2.11.0 puts it in the **right sidebar**: Settings → Memory management → Lab → enable "To-do board", and the sidebar's Start page gains a card that opens a tab.
541
+ `project_session-state.md` in the memory directory has always been a to-do list you keep for yourself: injected into every session, but you still have to open the file to see what is left. 2.11.1 puts it in the **right sidebar**: Settings → Memory management → Lab → enable "To-do board", and the sidebar's Start page gains a card that opens a tab.
536
542
 
537
543
  - **Ticking = moving**: a finished item is removed from its group and appended to the "Done, pending deletion" block (created at the end of the file on first use); un-ticking moves it back to the end of its original group. "Clear all" is what actually deletes rows.
538
544
  - **Edit it**: add an item at the end of a group, edit one in place, undo / redo **3–5 steps** (5 by default).
@@ -587,6 +593,14 @@ Triggering is a 45 second poll plus a 10 second debounce on directory events, so
587
593
  | `external.tags` | `[]` | Expose by `frontmatter.tags`; empty means no tag-based exposure |
588
594
  | `external.port` | `7461` (1024-65535) | Read-only endpoint port, bound to `127.0.0.1`. If it is taken the endpoint reports why instead of drifting to another port |
589
595
 
596
+ ### Integration snippet: tell other agents when to look things up
597
+
598
+ MCP is **client-driven**: an endpoint has no way at all to push memory into someone else's context, it can only answer when it is called. So the discipline of "when to look" has to be pasted into that agent's own rules file. The External access page has a **Copy integration snippet** button (since 2.31.0) that copies a ready-made block to the clipboard, through the same fallback path as "copy fix prompt" - so it also works over plain http on a LAN, where there is no secure context.
599
+
600
+ Paste it into `CLAUDE.md`, `AGENTS.md` or `.cursorrules`. The block states the endpoint URL, the four tools it offers, and **when to use them**: `memory_list` before starting work, `memory_search` when a proper noun comes up, `memory_submit` once a conclusion settles - plus the rule "if the library does not have it, say so; never invent content from a filename".
601
+
602
+ The `instructions` the endpoint returns on `initialize` now carries the same three rules (they are read on every connection). Those two are the **only** passive channels available - beyond them, whether to read at all is still the other model's call.
603
+
590
604
  **Out of scope on purpose**: the write side (an `intake/` area and a merger for incoming submissions) belongs to 2.26.0; there is no per-agent tiered permission model (ACLs are useless under one OS user, so visibility replaces permissions); there is no endpoint auth and no cross-machine access - use an SSH port forward if you need that.
591
605
 
592
606
  ## Incoming submissions: other agents can submit, only you let them in (2.26.0)
package/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  > File-based cross-session memory for DeepSeek Harness — every memory is a plain markdown file you can open, edit and delete. No database, no worker, no port.
16
16
 
17
- **当前发布版本:`2.33.0`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
17
+ **当前发布版本:`2.33.2`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
18
18
  [契约冻结](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md)。
19
19
 
20
20
  如果它对你有用,给个 Star 是最直接的反馈。
@@ -31,8 +31,14 @@
31
31
  - [写入安全](#写入安全)
32
32
  - [体积治理:超线了怎么办](#体积治理超线了怎么办)
33
33
  - [自动做梦](#自动做梦)
34
- - [初始记忆](#初始记忆让-agent-建个骨架2120)
35
34
  - [从 Claude Code 迁移](#从-claude-code-迁移)
35
+ - [压缩前记忆提醒](#压缩前记忆提醒实验性--2170)
36
+ - [待办清单看板](#待办清单看板实验性--2111-起2150-收尾)
37
+ - [初始记忆](#初始记忆让-agent-建个骨架2120)
38
+ - [外部访问](#外部访问让别的-agent-读一份副本2250)
39
+ - [外部来件](#外部来件别的-agent-能提交进不进库你说了算2260)
40
+ - [跨设备检查](#跨设备检查先看清楚再动手2270)
41
+ - [跨设备拉取](#跨设备拉取一次-ssh-搬回来2280)
36
42
  - [配置参考](#配置参考)
37
43
  - [稳定性与版本策略](#稳定性与版本策略)
38
44
  - [权限与隐私](#权限与隐私)
@@ -532,9 +538,9 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
532
538
 
533
539
  **代价**:开关关着时它什么都不做 —— 连上下文都不测。打开后每步读一次开关与窗口投影(便宜),压力过半才做一次精确测量(与压缩引擎排在同一条 waterfall 上,缓存是热的)。**它不能让模型一定照做** —— 这是提醒,不是保证。
534
540
 
535
- ## 待办清单看板(实验性 · 2.11.0 起;2.15.0 收尾)
541
+ ## 待办清单看板(实验性 · 2.11.1 起;2.15.0 收尾)
536
542
 
537
- 记忆目录里的 `project_session_state.md` 一直是「给自己看的代办清单」——每场会话都会注入,人却要打开文件才知道还剩什么。2.11.0 把它搬进**右侧栏**:设置 → 记忆管理 → 实验性 → 打开「待办清单看板」,右侧栏「开始」页就会多一张卡片,点开是一个页签。
543
+ 记忆目录里的 `project_session_state.md` 一直是「给自己看的代办清单」——每场会话都会注入,人却要打开文件才知道还剩什么。2.11.1 把它搬进**右侧栏**:设置 → 记忆管理 → 实验性 → 打开「待办清单看板」,右侧栏「开始」页就会多一张卡片,点开是一个页签。
538
544
 
539
545
  - **勾选 = 搬家**:完成项从原组删掉、搬进「已完成,待删除」块(文件里还没这一块就自动在末尾建),取消完成再搬回原组末尾;「清空全部」才真删。
540
546
  - **改得动**:每组底部加一条、点卡片行内改一句;撤销 / 重做 **3–5 步可配**(默认 5)。
@@ -589,6 +595,14 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
589
595
  | `external.tags` | `[]` | 按 frontmatter 的 `tags` 开放,留空表示不按标签开放 |
590
596
  | `external.port` | `7461`(1024–65535) | 只读端点端口,只绑 `127.0.0.1`;被占用时端点报错并说明原因,不自动漂移 |
591
597
 
598
+ ### 接入片段:让别的 agent 知道什么时候该查记忆
599
+
600
+ MCP 是**客户端驱动**的 —— 端点没有任何办法把记忆推进对方的上下文,它只能被调用时回答。所以「什么时候该查」这条纪律得由你贴进对方的规则文件。面板「外部访问」页上有一个**「复制接入片段」**按钮(2.31.0 起),点一下就把一段现成的文字复制到剪贴板(走与「复制修复提示词」同一条带降级的路,局域网 http 这种非安全上下文下也能用)。
601
+
602
+ 把它贴进 `CLAUDE.md` / `AGENTS.md` / `.cursorrules` 这类规则文件即可。片段里写的是:端点地址、它提供的四个工具,以及**什么时候该用** —— 开工前先 `memory_list`、听到专有名词先 `memory_search`、结论落定后再 `memory_submit`;并明确「库里没有就说没有,不要根据文件名编内容」。
603
+
604
+ 端点的 `initialize` 里那段 `instructions` 也补了同样三条纪律(每次连接都会被读到)。这两条是当前**仅有的**被动通道 —— 除此之外,读不读、什么时候读,仍由对方的模型自己决定。
605
+
592
606
  **明确不做**:写侧(外来提交的 `intake/` 与归并器)留给 2.26.0;不做「按 agent 分三档权限」(单用户同 SID 下 ACL 无效,改用「可见性」);不做端点鉴权和跨机器访问 —— 真要跨机器,走 SSH 端口转发。
593
607
 
594
608
  ## 外部来件:别的 agent 能提交,进不进库你说了算(2.26.0)
package/lib/client.js CHANGED
@@ -2650,8 +2650,9 @@ const StarmapRuntime = (function (require, _react) {
2650
2650
  ".smem-tool-panel--full{width:100%;align-self:stretch;box-sizing:border-box;}",
2651
2651
  // 已锁定的记忆:卡片上那个按钮要一眼看出「这条现在拒绝归档」,用警示色
2652
2652
  ".smem-btn-locked{border-color:var(--dsw-alias-state-warn-primary);color:var(--dsw-alias-state-warn-primary);}",
2653
- // 「自动归档」页签里的天数输入框:窄一点,别让三个数字各占一整行
2654
- ".smem-num{width:88px;}",
2653
+ // 「自动归档」页签里的天数输入框:窄一点,别让三个数字各占一整行。
2654
+ // ⚠️ 完整皮肤在下面 `.smem-num`(width:66px)—— 这里原先还有一条 `width:88px`,
2655
+ // 被后者整条覆盖,是死规则;删掉它,只留下面那处唯一真相(2.33.1 清理)。
2655
2656
  // 体检 / 候选是「翻清单」的面板:定高 + 内部滚动,列表不被顶出首屏。
2656
2657
  // 原样编辑器(.smem-ar-editor)不设上限 —— 那是专心改一份文件的界面,给它完整高度。
2657
2658
  ".smem-tool-panel--cap{max-height:320px;overflow-y:auto;}",
@@ -2765,7 +2766,11 @@ const StarmapRuntime = (function (require, _react) {
2765
2766
  ".smem-modcard-off{margin:6px 0 10px;padding:7px 10px;border-radius:8px;font-size:12px;line-height:1.6;color:var(--dsw-alias-state-warn-primary);background:var(--dsw-alias-bg-layer-2);}",
2766
2767
  ".smem-err{border:1px solid var(--dsw-alias-state-error-primary);color:var(--dsw-alias-state-error-primary);border-radius:8px;padding:6px 10px;font-size:12px;white-space:pre-wrap;overflow-wrap:anywhere;}",
2767
2768
  ".smem-ok{color:var(--dsw-alias-state-success-primary);font-size:12px;}",
2768
- ".smem-empty{border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-layer-2);padding:22px 14px;text-align:center;color:var(--dsw-alias-label-secondary);font-size:12.5px;}",
2769
+ // 空态:**唯一定义处**(2.33.1 合并)。原来有两条同名单类规则 —— 1.5.0 那条写
2770
+ // `display:flex;align-items:flex-start`,2.32.0 那条写 `text-align:center`,后者在文件里更早、
2771
+ // 单类同权重被前一条覆盖 → 实际渲染是靠左的,`text-align:center` 从来没生效过(flex 子项不吃它)。
2772
+ // 现在合成一条:多行空态(标题 + 引导按钮)竖排居中,与「空仓库引导页」的惯例一致。
2773
+ ".smem-empty{border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-layer-2);padding:22px 14px;color:var(--dsw-alias-label-secondary);font-size:12.5px;display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center;}",
2769
2774
  ".smem-tabs{display:flex;gap:20px;border-bottom:1px solid var(--dsw-alias-border-l2);margin-bottom:4px;}",
2770
2775
  ".smem-tab{background:none;border:0;padding:8px 2px 10px;font-size:13px;font-family:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;position:relative;}",
2771
2776
  '.smem-tab--on{color:var(--dsw-alias-label-primary);}',
@@ -2845,7 +2850,7 @@ const StarmapRuntime = (function (require, _react) {
2845
2850
  ".smem-clamp-2--open{-webkit-line-clamp:unset;display:block;}",
2846
2851
  ".smem-skeleton{display:flex;flex-direction:column;gap:10px;padding:6px 0;}",
2847
2852
  ".smem-skeleton-row{height:44px;border-radius:8px;background:var(--dsw-alias-bg-layer-2);opacity:.55;}",
2848
- ".smem-empty{display:flex;flex-direction:column;align-items:flex-start;gap:8px;}",
2853
+ // (`.smem-empty` 的定义在上面 1.5.0 那一组里,2.33.1 已合并为唯一一条,此处不再重复声明。)
2849
2854
  ".smem-tabs-sep{width:1px;align-self:stretch;margin:6px 2px;background:var(--dsw-alias-border-l2);}",
2850
2855
  // ── 切页签的进场动画(2.5.0,D39)──────────────────────────────────────
2851
2856
  // 只在**换页签**时播一次:`.smem-view` 带 key={tab},换页签=换 key=换 DOM 节点,
@@ -2929,22 +2934,37 @@ const StarmapRuntime = (function (require, _react) {
2929
2934
  // 所以根节点必须**自己吃满高度并滚**,不能指望宿主代滚。
2930
2935
  ".smem-todo{height:100%;max-height:100%;min-height:0;flex:1 1 auto;box-sizing:border-box;overflow-y:auto;overflow-x:hidden;display:flex;flex-direction:column;gap:8px;padding:0 10px 12px;font-size:12.5px;line-height:1.55;color:var(--dsw-alias-label-primary);}",
2931
2936
  // 顶部统计条吸顶:滚到第 20 条时仍然知道总数。
2932
- ".smem-todo-head{position:sticky;top:0;z-index:2;display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:11.5px;color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-bg-l1);backdrop-filter:blur(8px);padding:10px 0 8px;border-bottom:1px solid var(--dsw-alias-border-l1);}",
2937
+ // ⚠️ 吸顶底色用 `--dsw-alias-bg-layer-1`,**不是** `--dsw-alias-bg-l1`:后者宿主从未定义过
2938
+ // (宿主的 bg 族只有 base / layer-1..3 / mask-* / overlay / skeleton 等)。写错的声明会
2939
+ // 静默失效 → 计算值回落 transparent + backdrop-filter 模糊 → 正文从吸顶条后面穿过去(2.33.1 修)。
2940
+ ".smem-todo-head{position:sticky;top:0;z-index:2;display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:11.5px;color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-bg-layer-1);backdrop-filter:blur(8px);padding:10px 0 8px;border-bottom:1px solid var(--dsw-alias-border-l1);}",
2933
2941
  ".smem-todo-stat{font-variant-numeric:tabular-nums;}",
2934
2942
  ".smem-todo-head > span[data-spring]{flex:1;}",
2935
- ".smem-todo-mini{font-size:11.5px;background:none;border:0;padding:0;cursor:pointer;color:var(--dsw-alias-brand-primary);}",
2943
+ // `.smem-todo-mini` 只负责**字号与手型**,不负责「去掉按钮外观」。
2944
+ // 原来它自带 `background:none;border:0;padding:0`,而它在文件里的位置**晚于** `.smem-btn-primary`
2945
+ // 且同为单类权重 → 待办卡里的「保存」主按钮背景/边框/内距被整条抹掉,退化成一行文字(2.33.1 修)。
2946
+ // 「无框文字按钮」的语义收进 `.smem-link`(下面那条),有框的按钮继续由 `.smem-btn*` 管。
2947
+ ".smem-todo-mini{font-size:11.5px;cursor:pointer;}",
2936
2948
  ".smem-todo-mini:disabled{opacity:.45;cursor:default;}",
2949
+ // `.smem-link`:无框文字按钮(4 处引用:更多/收起、编辑、删除)。**之前根本没有定义**,
2950
+ // 全靠 `.smem-todo-mini` 里那串 reset 撑着;reset 一收窄就必须把它补上,否则那些按钮会变回带框的默认按钮。
2951
+ ".smem-link{background:none;border:0;padding:0;color:var(--dsw-alias-brand-primary);font-family:inherit;cursor:pointer;text-align:left;}",
2952
+ ".smem-link:hover:not(:disabled){text-decoration:underline;}",
2953
+ ".smem-link:disabled{opacity:.45;cursor:default;text-decoration:none;}",
2937
2954
  ".smem-todo-groups{display:flex;flex-direction:column;gap:10px;}",
2938
2955
  ".smem-todo-search-row{display:flex;align-items:center;gap:8px;padding:0 0 2px;}",
2939
2956
  ".smem-todo-search{flex:1;min-width:0;font-size:12px;}",
2940
2957
  ".smem-todo-group{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:8px 9px;display:flex;flex-direction:column;gap:6px;flex:0 0 auto;}",
2941
2958
  // 待删除块整块走红色系:它是**队列**不是结论,看得见的红提醒「这些该搬走了」。
2942
- ".smem-todo-group-done{border-color:var(--dsw-alias-state-danger-primary);}",
2943
- ".smem-todo-group-done .smem-todo-group-title{color:var(--dsw-alias-state-danger-primary);}",
2959
+ // ⚠️ 宿主的危险色叫 `--dsw-alias-state-**error**-primary`,没有 `state-danger-primary`
2960
+ // (宿主 state 族:business / done / error / idle / success / warn,无 danger)。
2961
+ // 写错的名字不会报错,只会让整条声明失效 → 「待删除块」的红边框 / 红标题 / 红按钮静默全灰(2.33.1 修)。
2962
+ ".smem-todo-group-done{border-color:var(--dsw-alias-state-error-primary);}",
2963
+ ".smem-todo-group-done .smem-todo-group-title{color:var(--dsw-alias-state-error-primary);}",
2944
2964
  // 2.11.1:标题行改成「行」—— 右侧要放「清空全部」,按钮不能套按钮。
2945
2965
  ".smem-todo-group-head{display:flex;align-items:center;gap:6px;width:100%;min-width:0;}",
2946
2966
  ".smem-todo-group-toggle{flex:1;min-width:0;display:flex;align-items:center;gap:6px;background:none;border:0;padding:0;cursor:pointer;color:inherit;text-align:left;}",
2947
- ".smem-todo-del{color:var(--dsw-alias-state-danger-primary);}",
2967
+ ".smem-todo-del{color:var(--dsw-alias-state-error-primary);}",
2948
2968
  ".smem-todo-chev{color:var(--dsw-alias-label-secondary);font-size:10px;width:10px;}",
2949
2969
  ".smem-todo-group-title{font-weight:600;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}",
2950
2970
  ".smem-todo-count{font-size:11px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary);}",
@@ -2956,7 +2976,12 @@ const StarmapRuntime = (function (require, _react) {
2956
2976
  ".smem-todo-item{display:flex;gap:8px;align-items:flex-start;border-radius:8px;padding:4px 2px;}",
2957
2977
  ".smem-todo-item:hover{background:var(--dsw-alias-bg-layer-2);}",
2958
2978
  ".smem-todo-box{flex:0 0 auto;width:16px;height:16px;margin-top:1px;border-radius:5px;border:1px solid var(--dsw-alias-border-l2);background:transparent;color:transparent;font-size:11px;line-height:1;display:flex;align-items:center;justify-content:center;cursor:pointer;padding:0;}",
2959
- ".smem-todo-box-on{background:var(--dsw-alias-brand-primary);border-color:transparent;color:#fff;}",
2979
+ // ⚠️ 勾选态的字色必须走 `--dsw-alias-label-primary-foreground`,**不许写死 `#fff`**。
2980
+ // `--dsw-alias-brand-primary` 是**反色语义**:浅色主题 = 近黑 rgb(15,17,21),深色主题 = 近白
2981
+ // rgb(249,250,251)。写死白字 → 深色下白底白勾,对比 1.02:1,`✓` 完全消失,勾选框看起来
2982
+ // 永远未勾选。这与 2.29.0 修的 `.smem-switch` 白底白滑块是同一个根因(那次只清了开关)。
2983
+ // `label-primary-foreground` 在深色下是近黑、浅色下是白,自动与 brand 反色 —— 就是为这个场景定义的。
2984
+ ".smem-todo-box-on{background:var(--dsw-alias-brand-primary);border-color:transparent;color:var(--dsw-alias-label-primary-foreground);}",
2960
2985
  ".smem-todo-body{min-width:0;flex:1;display:flex;flex-direction:column;gap:2px;}",
2961
2986
  ".smem-todo-title{font-weight:600;overflow-wrap:anywhere;}",
2962
2987
  ".smem-todo-text{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;white-space:pre-wrap;}",
@@ -2982,7 +3007,7 @@ const StarmapRuntime = (function (require, _react) {
2982
3007
  ".smem-todo-tab-title{display:inline-flex;align-items:center;gap:5px;}",
2983
3008
  // 2.15.5:确认条独占一行,与「搬进流水」那颗按钮不在同一位置(双击打不到它)。
2984
3009
  ".smem-todo-confirm{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:6px 0 2px;border-top:1px dashed var(--dsw-alias-border-l1);}",
2985
- ".smem-todo-confirm .smem-todo-archive{color:var(--dsw-alias-state-danger-primary);}",
3010
+ ".smem-todo-confirm .smem-todo-archive{color:var(--dsw-alias-state-error-primary);}",
2986
3011
  // 检查点聚合块:只读、来源是别的文件 —— 用虚线边框和正文色区分开。
2987
3012
  ".smem-todo-group-cp{border-style:dashed;}",
2988
3013
  ".smem-todo-cp-task{display:flex;flex-direction:column;gap:2px;padding:2px 0;}",
@@ -8546,6 +8571,26 @@ return h("div", { className: "smem-external smem-stack" }, [
8546
8571
  notice ? h("div", { className: "smem-ok", key: "ok" }, "✓ " + notice) : null,
8547
8572
  ]);
8548
8573
  }
8574
+ /**
8575
+ * `HH:mm:ss`(本地时区,格式与 locale 无关)。
8576
+ *
8577
+ * ⚠️ **不许用 `toLocaleTimeString()`**(2.33.1 改):它的输出同时依赖**时区**与**运行环境的
8578
+ * locale** —— 同一份数据在 zh-CN / en-US / C 下分别是 `14:23:05` / `2:23:05 PM` / `14:23:05`,
8579
+ * 于是「最后导出于几点」这句在界面上跨机器长得不一样,界面快照也永远没法跨平台稳定
8580
+ * (2026-12-04 实测:本地 Windows +08:00 与 CI ubuntu UTC 的 `ext` 屏哈希不同,
8581
+ * 而且两边都跑 UTC 时仍因 locale 不同而不同)。
8582
+ *
8583
+ * 自己拼是照 `79-todo-board.js` 的 `todoStamp` 的先例:那边早就用 `padStart` 拼
8584
+ * `YYYY-MM-DD HH:mm` 了,理由是「人读的本地时间,格式化不许随环境变」。这里是同一件事。
8585
+ * 时区仍是本地(用户想知道「我这边的几点」),跨时区的确定性由调用方保证 —— 快照测试
8586
+ * 会注入 `TZ=UTC` 再渲染。
8587
+ */
8588
+ function extClockOf(ms) {
8589
+ const d = new Date(ms);
8590
+ const p = function (n) { return String(n).padStart(2, "0"); };
8591
+ return p(d.getHours()) + ":" + p(d.getMinutes()) + ":" + p(d.getSeconds());
8592
+ }
8593
+
8549
8594
  /**
8550
8595
  * 端点状态那两行(2.32.0 从 68 搬出)。
8551
8596
  *
@@ -8566,7 +8611,7 @@ return h("div", { className: "smem-external smem-stack" }, [
8566
8611
  const lastLine = !status || !status.lastExportAt
8567
8612
  ? t("ext.lastExport.never")
8568
8613
  : t("ext.lastExport", {
8569
- time: new Date(status.lastExportAt).toLocaleTimeString(),
8614
+ time: extClockOf(status.lastExportAt),
8570
8615
  written: status.written, unchanged: status.unchanged, deleted: status.deleted,
8571
8616
  });
8572
8617
 
@@ -12403,19 +12448,29 @@ return h("div", { className: "smem-external smem-stack" }, [
12403
12448
  * 宿主的固定 remote 清单里,必须自己挂),再注册设置页签 / 侧栏入口。
12404
12449
  */
12405
12450
  /**
12406
- * 兜底红带(2.29.0)。
12451
+ * 兜底红带(2.29.0;2.33.2 修热替换)。
12407
12452
  *
12408
12453
  * React 的错误边界只认 class,而本插件的分片里不写 class —— 测试 harness 直接调用
12409
12454
  * 组件函数,class 组件在那里根本渲染不出来(2026-12-04 试过,`cannot be invoked without 'new'`)。
12410
12455
  * 所以退一步:挂 window 的未捕获异常,一旦渲染炸了,至少在页顶摊一条红带并写出错误原文,
12411
12456
  * 而不是让用户对着黑屏猜。
12457
+ *
12458
+ * ⚠️ **热替换必须换得掉旧监听器**(2.33.2)。原实现用 `window.__smemFatalHooked` 布尔守卫
12459
+ * 「只挂一次」,而 DSH 的 client-hmr 走的是**模块热替换**(`entries.reload()`,不重载页面):
12460
+ * 新模块再 apply 一遍时这个守卫直接 return,**上一版注册的闭包继续挂在 window 上**。
12461
+ * 后果是 2026-12-04 那次「代码已经改了、界面上还是旧文案」—— 2.30.0 的闭包一直报着
12462
+ * 「sage-mem 面板渲染失败:ResizeObserver loop…」,直到用户整机重启桌面版才换掉。
12463
+ * 现在把 handler 存进 `window.__smemFatalHandler`,先摘旧的再挂新的;顺带摘掉旧版留下的红带
12464
+ * (它写的是旧代码的错误,留着只会误导)。
12412
12465
  */
12413
12466
  function installFatalBanner() {
12414
12467
  if (typeof window === "undefined" || typeof document === "undefined") return;
12415
12468
  if (typeof window.addEventListener !== "function") return;
12416
- if (window.__smemFatalHooked) return;
12417
- window.__smemFatalHooked = true;
12418
- window.addEventListener("error", function (ev) {
12469
+ const prev = window.__smemFatalHandler;
12470
+ if (typeof prev === "function" && typeof window.removeEventListener === "function") {
12471
+ window.removeEventListener("error", prev);
12472
+ }
12473
+ const handler = function (ev) {
12419
12474
  try {
12420
12475
  const msg = String((ev && ev.message) || "");
12421
12476
  // **良性警告名单**(2.32.0)。这条红带本意是「渲染炸了别让用户对着黑屏」,
@@ -12432,11 +12487,19 @@ return h("div", { className: "smem-external smem-stack" }, [
12432
12487
  // 文案**不归因**给本插件:`window.onerror` 是全局的,抓到的是整个页面(宿主 +
12433
12488
  // 所有插件)的错误。写成「sage-mem 面板渲染失败」会把别人的锅扣在自己头上 ——
12434
12489
  // 2026-12-04 就是这么把宿主的 ResizeObserver 警告报成了「面板渲染失败」。
12490
+ // 处置建议也不能乱给:桌面版里「刷新页面」拿的是宿主**启动那一刻**的注入表
12491
+ // (Electron 主进程只收集一次),插件刚更新过时刷新反而可能拉不到旧批次的 bundle,
12492
+ // 让整批插件加载失败。真正可靠的是重开桌面版(新进程重新扫盘)。
12435
12493
  bar.textContent = "页面脚本报错:" + (msg || "未知错误")
12436
- + "(sage-mem 的全局兜底)—— 刷新页面可重试;与记忆面板无关的话可以忽略。";
12494
+ + "(sage-mem 的全局兜底)—— 关掉并重开 DSH 可重试;与记忆面板无关的话可以忽略。";
12437
12495
  if (document.body) document.body.appendChild(bar);
12438
12496
  } catch (e) { /* 兜底自己出错就不再兜 */ }
12439
- });
12497
+ };
12498
+ window.__smemFatalHandler = handler;
12499
+ window.addEventListener("error", handler);
12500
+ // 旧版本留下的红带一并摘掉(热替换后它描述的已不是当前代码)。
12501
+ const stale = document.getElementById("smem-fatal-banner");
12502
+ if (stale && stale.parentNode) stale.parentNode.removeChild(stale);
12440
12503
  }
12441
12504
 
12442
12505
  async function apply(ctx) {
package/lib/index.js CHANGED
@@ -7,26 +7,35 @@
7
7
  */
8
8
 
9
9
  import { AutodreamEngine, DEFAULT_CONFIG, auditMemoryDir } from './autodream.js'
10
- import { EXPERIMENTAL_SPECS, applyRuntimeExperimental, liveExperimental, STARTUP_EXPERIMENTAL_DIAGNOSTICS } from './memory/experimental.js'
11
- import { LIMIT_SPECS, MAX_BASELINE, MAX_CHARS_PER_FILE, MAX_FILE_BYTES, MAX_RESULTS, MAX_SESSION_BYTES, MEMORY_DIR, RECALL_DISCIPLINE, RESERVED_FILES, SESSIONS_ROOT, STALE_DAYS, STARTUP_LIMIT_DIAGNOSTICS, STATE_ROOT, resolveLimits } from './memory/config.js'
12
- import { INDEX_FILE_KEY, SESSION_LOG_KEY, isPlainMdName } from './shared/md-name.js'
13
- import { parseAliases, parseBaseline, parseBaselinePriority, parseFrontmatter, parseTags } from './memory/frontmatter.js'
14
- import { ageDays, bigrams, score, selectBaseline, selectRelevant } from './memory/retrieval.js'
10
+ // 2.33.x 删掉的三条 import。**都是「符号零引用」,不是搬家** —— 留痕是为了让下一个人
11
+ // (和下一个 agent)知道这里曾经有什么,不用去 git 里挖:
12
+ // · `./memory/experimental.js` —— EXPERIMENTAL_SPECS / applyRuntimeExperimental /
13
+ // liveExperimental / STARTUP_EXPERIMENTAL_DIAGNOSTICS,**4/4 全未用**:实验性开关的
14
+ // 读写在 `settings.js` 与 `assembly/precompact-mount.js`,组合根只负责转发。
15
+ // · `./shared/md-name.js` —— INDEX_FILE_KEY / SESSION_LOG_KEY / isPlainMdName,**3/3 全未用**:
16
+ // 名字判据收在 `memory/naming.js` 的 `safeName` 里,规范名常量只在下层模块用。
17
+ // · `./memory/retrieval.js` —— 整条只服务文件末尾的 `__testables`,那团东西已搬去
18
+ // `memory/testables.js`。删掉它同时把本地 import 从 20 条压到 17 条。
19
+ // config 这条同时瘦了身:`testables` 搬走之后,6 个上限常量与 5 个解析器在组合根里零引用。
20
+ import { MAX_FILE_BYTES, MEMORY_DIR, RESERVED_FILES, SESSIONS_ROOT, STATE_ROOT } from './memory/config.js'
21
+ import { parseFrontmatter } from './memory/frontmatter.js'
15
22
  import { isReserved, nameKey, safeName } from './memory/naming.js'
16
- import { MEMORY_ARCHIVE_DIR, addArchiveMeta, extractTitle, inspectDir, inspectMemoryEntry, readArchivedMeta, readVerified, listMemoryFiles, scanArchived, scanCheckpointOpen, scanMemoryFiles, scanStars, shadowsReserved } from './memory/scan.js'
23
+ import { MEMORY_ARCHIVE_DIR, addArchiveMeta, extractTitle, inspectDir, inspectMemoryEntry, readArchivedMeta, readVerified, listMemoryFiles, scanCheckpointOpen, scanStars, shadowsReserved } from './memory/scan.js'
17
24
  import { listConflicts, patchConflict, readConflict, removeConflict, summarizeConflict } from './memory/conflicts.js'
18
25
  import { invalidateMemory, undoMemoryInvalidation } from './memory/arbitrate.js'
19
- import { prepareWrite, readSnapshot, revisionOf, writeSnapshot } from './memory/write-protocol.js'
20
- import { archiveMemory, archivedRevisionOf, deleteArchivedMemory, restoreMemory } from './memory/archive.js'
21
- import { flushAccess, pickArchiveCandidates, readAccessLedger } from './memory/access.js'
22
- import { returnSource, retireTaken, serializeByKey, takeOverSource, warnLog, writeFileAtomic } from './memory/util.js'
23
- import { readLockState, setLocked as setLockedImpl } from './memory/lock.js'
26
+ import { deleteMemoryFile, prepareWrite, readSnapshot, writeSnapshot } from './memory/write-protocol.js'
27
+ import { archiveMemory, deleteArchivedMemory, listArchivedMemory, restoreMemory } from './memory/archive.js'
28
+ import { listArchiveCandidates } from './memory/access.js'
29
+ // 2.33.x 起 `takeOverSource` / `returnSource` / `retireTaken` 跟着 `deleteFile` 一起去
30
+ // `memory/write-protocol.js` 了 —— 组合根不再直接调用接管/归还/回收那三步。
31
+ import { serializeByKey, writeFileAtomic } from './memory/util.js'
32
+ import { setLockedInMemoryDir } from './memory/lock.js'
24
33
  import { openMemoryFolder } from './memory/open-folder.js'
25
34
  import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
26
- import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
35
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
27
36
  import { join } from 'node:path'
28
37
  import { checkUpdate as checkUpdateImpl } from './update.js'
29
- import { applySettingsPatch, autodreamConfigSnapshot, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readExternalSettings, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
38
+ import { applySettingsPatch, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readExternalSettings, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
30
39
  import { createRecallInjector, createSessionInjectState, readRecallDebug } from './recall/index.js'
31
40
  import { mountAutodream, mountMemoryTools, mountMirror, mountObserve, mountPreCompact, mountWriteGate } from './assembly/index.js'
32
41
 
@@ -167,93 +176,14 @@ export class MemoryGateway extends TypertRemoteService {
167
176
  }
168
177
 
169
178
  /**
170
- * 删除单个记忆文件:保留名一律拒绝(unlink 不可逆)。判定同 writeFile。
179
+ * 删除单个记忆文件(remote `memory/deleteFile`)。
171
180
  *
172
- * 2.21.0:新增可选 `opts.expectedRevision`。面板必须回传确认时看到的版本;
173
- * 宿主先原子接管该名字,再对**接管到手的实物**核内容身份。内容对不上或接管时
174
- * 已被换成别的版本,就用 link 还回,绝不删除没被用户确认过的那一版。
181
+ * 2.33.x:实现搬到 `memory/write-protocol.js` 的 `deleteMemoryFile()` —— 「先接管、
182
+ * 再核内容身份、最后才删」是写协议的一部分(与 `prepareWrite` / `writeSnapshot` 同族),
183
+ * 不该长在组合根里。**签名与回执形状一字未变**,这里只剩转发。
175
184
  */
176
185
  async deleteFile(name, opts) {
177
- if (isReserved(name)) {
178
- return { ok: false, error: `sage-mem: reserved file, refusing to delete: ${nameKey(name)}` }
179
- }
180
- const safe = safeName(name)
181
- if (!safe) return { ok: false, code: 'invalid_name', error: 'sage-mem: invalid file name' }
182
- const full = join(MEMORY_DIR, safe)
183
- // 同 writeFile:8.3 短名能绕过名字文本判据,删除保护也必须看文件身份。
184
- if (await shadowsReserved(full)) {
185
- return { ok: false, error: `sage-mem: reserved file (它的另一个名字是 ${safe}),拒绝删除` }
186
- }
187
- const expected = typeof opts?.expectedRevision === 'string' && opts.expectedRevision
188
- ? opts.expectedRevision
189
- : ''
190
- // 旧调用方兼容:仍按名字删,但必须留痕。新面板不会走这里。
191
- if (!expected) {
192
- warnLog(this.ctx, `deleteFile(${safe}) 未提供 expectedRevision,按旧协议删除(无法保证是你看见的那一版)`)
193
- await unlink(full)
194
- return { ok: true, file: safe }
195
- }
196
-
197
- const gate = await inspectMemoryEntry(full, { limitBytes: null })
198
- if (!gate.ok) {
199
- return {
200
- ok: false,
201
- code: gate.code === 'missing' ? 'missing' : 'read_failed',
202
- error: `sage-mem: 读不到 ${safe} 的当前版本(${gate.error}),没有删除`,
203
- }
204
- }
205
- let bytes
206
- try {
207
- bytes = await readVerified(full, gate, false)
208
- } catch (err) {
209
- return {
210
- ok: false,
211
- code: 'read_failed',
212
- error: `sage-mem: 读不到 ${safe} 的当前内容(${err?.code ?? err}),没有删除`,
213
- }
214
- }
215
-
216
- // 先接管、再核对:不留给「比对 → unlink」之间换版本的窗口。
217
- const taken = await takeOverSource(full, bytes, 'deleting')
218
- if (!taken.ok) {
219
- const code = taken.code === 'not_found'
220
- ? 'missing'
221
- : taken.code === 'changed' ? 'stale_revision' : 'delete_failed'
222
- const extra = taken.keptAt ? `;被移走的那份已保留在 ${taken.keptAt}` : ''
223
- return {
224
- ok: false,
225
- code,
226
- error: code === 'stale_revision'
227
- ? `sage-mem: ${safe} 在你确认之后已经被改写,没有删除${extra}`
228
- : `sage-mem: 删除 ${safe} 失败(${taken.cause?.code ?? taken.code}),没有删除${extra}`,
229
- ...(taken.keptAt ? { keptAt: taken.keptAt } : {}),
230
- }
231
- }
232
-
233
- let actual
234
- try {
235
- actual = revisionOf(await readFile(taken.taken))
236
- } catch (err) {
237
- const back = await returnSource(taken.taken, full)
238
- return {
239
- ok: false,
240
- code: 'read_failed',
241
- error: `sage-mem: 无法核对 ${safe} 的内容版本(${err?.code ?? err}),没有删除`,
242
- ...(back.ok ? {} : { keptAt: back.keptAt }),
243
- }
244
- }
245
- if (actual !== expected) {
246
- const back = await returnSource(taken.taken, full)
247
- return {
248
- ok: false,
249
- code: 'stale_revision',
250
- error: `sage-mem: ${safe} 在你确认之后已经被改写(当前版本 ${actual.slice(0, 12)}…),没有删除`,
251
- ...(back.ok ? {} : { keptAt: back.keptAt }),
252
- }
253
- }
254
-
255
- await retireTaken(taken.taken)
256
- return { ok: true, file: safe }
186
+ return await deleteMemoryFile(this.ctx, name, opts)
257
187
  }
258
188
 
259
189
  /**
@@ -302,29 +232,13 @@ export class MemoryGateway extends TypertRemoteService {
302
232
  }
303
233
 
304
234
  /**
305
- * 列出归档区的全部记忆(面板的「已归档」区)。与 `listFiles()` 分开、形状也不同:那个只列
306
- * 活动记忆(多一个字段都会破坏界面与断言依赖的形状);归档条目额外带 `archivedAt` /
307
- * `archivedReason` / `revision`。旧版 autodream 工具直接移文件、不写留痕,所以前两个可能是空串。
308
- * `revision` 是**内容身份**(2026-10-31 外部审查 Q07):归档代次 + 正文 revision,删除确认必须原样交回 ——
309
- * `archivedAt` 只是展示时间,同一分钟内不可区分,拿它当版本会让旧确认删掉新内容。
235
+ * 列出归档区的全部记忆(面板的「已归档」区)。
236
+ *
237
+ * 2.33.x:实现搬到 `memory/archive.js` 的 `listArchivedMemory()` —— 归档身份
238
+ * (`archivedRevisionOf`)与「只移不删」的承诺都在那个文件里。形状一字未改。
310
239
  */
311
240
  async listArchived() {
312
- const files = await scanArchived(this.ctx)
313
- const out = files.map(f => {
314
- const meta = parseFrontmatter(f.content)
315
- const archived = readArchivedMeta(f.content)
316
- return {
317
- file: f.name,
318
- type: meta.type || 'reference',
319
- description: meta.description || '',
320
- size: f.content.length,
321
- tags: meta.tags,
322
- archivedAt: archived.archivedAt,
323
- archivedReason: archived.archivedReason,
324
- revision: archivedRevisionOf(f.content),
325
- }
326
- })
327
- return { count: out.length, files: out }
241
+ return await listArchivedMemory(this.ctx)
328
242
  }
329
243
 
330
244
  /**
@@ -425,7 +339,8 @@ export class MemoryGateway extends TypertRemoteService {
425
339
  * 状态根不接受界面传入(跟 `openMemoryDir` 同一条纪律:别把「读任意路径」变成能力)。
426
340
  */
427
341
  async checkpoints() {
428
- return scanCheckpointOpen(STATE_ROOT)
342
+ // 2.33.2:带上 ctx —— `scanCheckpointOpen` 内部要用它打 warnLog(跳过某个坏检查点时出声)。
343
+ return scanCheckpointOpen(STATE_ROOT, this.ctx)
429
344
  }
430
345
 
431
346
  /**
@@ -439,50 +354,27 @@ export class MemoryGateway extends TypertRemoteService {
439
354
  }
440
355
 
441
356
  /**
442
- * 自动归档候选 + 当前策略与阈值(面板「执行归档」前先看清单)。
443
- *
444
- * 复用 `memory/access.js` 的台账与候选计算,与 autodream 引擎跑的是同一份逻辑。
445
- * 先强制 flush 台账:面板看到的候选不能比引擎少(内存里还压着的那批注入必须算进去)。
446
- */
447
- /**
448
- * 上锁 / 解锁一条记忆。锁上的记忆**拒绝归档**(自动与手动都不行)。
357
+ * 上锁 / 解锁一条记忆(remote `memory/setLocked`)。锁上的记忆**拒绝归档**(自动与手动都不行)。
449
358
  *
450
359
  * 落点是**状态目录**(`.sage-mem/locked.json`),不写进记忆自己的 frontmatter ——
451
360
  * 理由见 `lib/memory/lock.js` 的头注:frontmatter 会被「自动做梦」重写,锁写在里面
452
361
  * 可能被整理过程擦掉,而锁一丢那条记忆就重新进了自动归档候选(正是这功能要防的事)。
362
+ *
363
+ * 2.33.x:`locked === true` 的归一与默认记忆目录都搬进 `memory/lock.js` 的
364
+ * `setLockedInMemoryDir()`,这里只剩转发。语义没变:**只有严格的 `true` 才算上锁**。
453
365
  */
454
366
  async setLocked(name, locked) {
455
- return await setLockedImpl(MEMORY_DIR, name, locked === true)
367
+ return await setLockedInMemoryDir(name, locked)
456
368
  }
457
369
 
370
+ /**
371
+ * 自动归档候选 + 当前策略与阈值(面板「执行归档」前先看清单)。
372
+ *
373
+ * 2.33.x:整段搬到 `memory/access.js` 的 `listArchiveCandidates()` —— 台账、候选计算、
374
+ * 锁表、阈值本来就在那一层,组合根只留转发。回执形状一字未改。
375
+ */
458
376
  async archiveCandidates() {
459
- await flushAccess(MEMORY_DIR)
460
- const [ledger, files, lockState] = await Promise.all([
461
- readAccessLedger(),
462
- scanMemoryFiles(this.ctx, ''),
463
- readLockState(MEMORY_DIR),
464
- ])
465
- // Q05:锁表不可读时如实标记(候选清单仍可看,自动归档由 archiveMemory 直接拒绝)。
466
- if (lockState.status === 'unknown') warnLog(this.ctx, `锁表不可读,候选清单的锁定状态未知(自动归档会拒绝执行):${lockState.reason}`)
467
- const cfg = await autodreamConfigSnapshot()
468
- const thresholds = {
469
- project: cfg.archiveAfterDaysProject,
470
- reference: cfg.archiveAfterDaysReference,
471
- user: cfg.archiveAfterDaysUser,
472
- }
473
- // 锁表交给候选计算:锁上的记忆一个都不选(用户对**单条**记忆说的话优先于阈值)。
474
- const candidates = pickArchiveCandidates(files, ledger, { thresholds, locked: lockState.locked })
475
- return {
476
- count: candidates.length,
477
- candidates,
478
- autoArchive: cfg.autoArchive,
479
- thresholds,
480
- // 面板要显示「哪些锁着」,所以把锁表也带回去(已按 nameKey 归一)
481
- locked: [...lockState.locked],
482
- // Q05:保护状态未知时明确标出来,不把「不知道」渲染成「都没锁」。
483
- lockedUnknown: lockState.status === 'unknown',
484
- lockedError: lockState.reason,
485
- }
377
+ return await listArchiveCandidates(this.ctx)
486
378
  }
487
379
 
488
380
  /**
@@ -962,24 +854,14 @@ markRemote(AutodreamGateway, 'listModels', 'listModels')
962
854
  export default MemoryGateway
963
855
 
964
856
  /**
965
- * **仅供测试**的只读出口。
857
+ * **仅供测试**的只读出口(内容物在 `memory/testables.js`,2.33.x 搬走)。
858
+ *
859
+ * 组合根保留这一次转发的原因只有一个:**导出名不能变** —— `test/inject-test.mjs` /
860
+ * `test/retrieval-test.mjs` / `test/memory-tools-test.mjs` / `test/archive-test.mjs` 四个套件
861
+ * 从这里取 `__testables`。搬内容(顺带还回 `./memory/retrieval.js` 那条 import)与改名是两件事。
966
862
  *
967
- * 检索这条链(frontmatter 解析 → 双字打分 → 名额裁剪)没有任何对外可见的调用面:
968
- * 想验证「写了 aliases 之后换个说法能不能命中」,否则只能起一个真的 DSH 端到端跑一遍。
969
- * 把这些纯函数露出来是为了能写断言,**不是给外部用的 API**,别依赖。
863
+ * 它露出来的是 frontmatter 解析 / 双字打分 / 名额裁剪这些**纯函数**,为的是能写断言,
864
+ * 不是给外部用的 API,别依赖。
970
865
  */
971
- export const __testables = {
972
- bigrams,
973
- score,
974
- parseFrontmatter,
975
- parseAliases,
976
- parseBaselinePriority,
977
- parseBaseline,
978
- parseTags,
979
- ageDays,
980
- selectRelevant,
981
- selectBaseline,
982
- limits: { MAX_RESULTS, MAX_CHARS_PER_FILE, MAX_BASELINE, MAX_SESSION_BYTES, STALE_DAYS },
983
- recallDiscipline: RECALL_DISCIPLINE,
984
- }
866
+ export { testables as __testables } from './memory/testables.js'
985
867
 
@@ -35,7 +35,7 @@ export const SUBMIT_TYPES = Object.freeze(['project', 'reference'])
35
35
  export const SUBMIT_KINDS = Object.freeze(['new', 'patch'])
36
36
 
37
37
  /**
38
- * 内置保留名(索引 / 流水)。**用户自己声明的**保留名不在这里判 —— 那要读
39
- eserved.json,
38
+ * 内置保留名(索引 / 流水)。**用户自己声明的**保留名不在这里判 —— 那要读 reserved.json,
40
39
  * 属于 IO 层,由 merge.js 在真正落盘前再兜一道。这里只保证「外来提交永远占不到这两个名字」。
41
40
  */
42
41
  const RESERVED_BUILTIN = new Set([INDEX_FILE_KEY, SESSION_LOG_KEY])
@@ -13,10 +13,12 @@
13
13
  */
14
14
 
15
15
  import { MEMORY_DIR, STATE_ROOT } from './config.js'
16
- import { ARCHIVE_DIR_NAME } from './scan.js'
16
+ import { ARCHIVE_DIR_NAME, scanMemoryFiles } from './scan.js'
17
+ import { readLockState } from './lock.js'
17
18
  import { isMemoryEntry } from './naming.js'
18
19
  import { parseFrontmatter } from './frontmatter.js'
19
- import { createWriteQueue, writeFileAtomic } from './util.js'
20
+ import { createWriteQueue, warnLog, writeFileAtomic } from './util.js'
21
+ import { autodreamConfigSnapshot } from '../settings.js'
20
22
  import { mkdir, readFile, readdir, stat } from 'node:fs/promises'
21
23
  import { dirname, join } from 'node:path'
22
24
  import { nameKey } from './naming.js'
@@ -409,3 +411,54 @@ export function pickArchiveCandidates(files, ledger = {}, opts = {}, now = Date.
409
411
  }
410
412
  return out.sort((a, b) => b.days - a.days || a.file.localeCompare(b.file))
411
413
  }
414
+
415
+ /**
416
+ * 自动归档候选 + 当前策略与阈值(面板「执行归档」前先看清单)。
417
+ *
418
+ * ── 为什么在这里(2.33.x 从 `lib/index.js` 的 `MemoryGateway.archiveCandidates()` 搬来)──
419
+ * 它就是本文件那几件东西的组合:`flushAccess` / `readAccessLedger` / `pickArchiveCandidates`
420
+ * 全住在这里,锁表在 `lock.js`,阈值来自 `settings.js` 的 `autodreamConfigSnapshot()`。
421
+ * 组合根卡在 1000 行 / 20 条本地 import 的硬线上,而这段是**编排**不是接线 ——
422
+ * 搬过来之后组合根那一条 remote 只剩一行转发,回执形状**一字未改**。
423
+ *
424
+ * 复用 `memory/access.js` 的台账与候选计算,与 autodream 引擎跑的是同一份逻辑。
425
+ * 先强制 flush 台账:面板看到的候选不能比引擎少(内存里还压着的那批注入必须算进去)。
426
+ *
427
+ * ⚠️ `../settings.js` 这条上行依赖本层已经有了先例(`scan.js` 就是从这个文件读外部访问设置):
428
+ * 阈值只该有一个来源,为了「依赖方向好看」在这里再算一份默认阈值,等于让面板与引擎
429
+ * 对同一件事有两个答案。`structure-test` 的依赖方向守卫禁的是 memory 认识
430
+ * autodream / recall / assembly / 组合根,settings 不在其中。
431
+ *
432
+ * @param {object} ctx — 宿主上下文(`scanMemoryFiles` 与日志用)
433
+ * @returns {Promise<{count:number, candidates:Array<object>, autoArchive:boolean, thresholds:object,
434
+ * locked:string[], lockedUnknown:boolean, lockedError:string}>}
435
+ */
436
+ export async function listArchiveCandidates(ctx) {
437
+ await flushAccess(MEMORY_DIR)
438
+ const [ledger, files, lockState] = await Promise.all([
439
+ readAccessLedger(),
440
+ scanMemoryFiles(ctx, ''),
441
+ readLockState(MEMORY_DIR),
442
+ ])
443
+ // Q05:锁表不可读时如实标记(候选清单仍可看,自动归档由 archiveMemory 直接拒绝)。
444
+ if (lockState.status === 'unknown') warnLog(ctx, `锁表不可读,候选清单的锁定状态未知(自动归档会拒绝执行):${lockState.reason}`)
445
+ const cfg = await autodreamConfigSnapshot()
446
+ const thresholds = {
447
+ project: cfg.archiveAfterDaysProject,
448
+ reference: cfg.archiveAfterDaysReference,
449
+ user: cfg.archiveAfterDaysUser,
450
+ }
451
+ // 锁表交给候选计算:锁上的记忆一个都不选(用户对**单条**记忆说的话优先于阈值)。
452
+ const candidates = pickArchiveCandidates(files, ledger, { thresholds, locked: lockState.locked })
453
+ return {
454
+ count: candidates.length,
455
+ candidates,
456
+ autoArchive: cfg.autoArchive,
457
+ thresholds,
458
+ // 面板要显示「哪些锁着」,所以把锁表也带回去(已按 nameKey 归一)
459
+ locked: [...lockState.locked],
460
+ // Q05:保护状态未知时明确标出来,不把「不知道」渲染成「都没锁」。
461
+ lockedUnknown: lockState.status === 'unknown',
462
+ lockedError: lockState.reason,
463
+ }
464
+ }
@@ -15,8 +15,9 @@
15
15
  * 就是临时目录),拿模块级常量会写错地方 —— 那是会碰到真实记忆的危险错误。
16
16
  */
17
17
 
18
- import { ARCHIVE_DIR_NAME, addArchiveMeta, inspectDir, inspectMemoryEntry, localStamp, readArchivedMeta, shadowsReserved, stripArchiveMeta } from './scan.js'
18
+ import { ARCHIVE_DIR_NAME, addArchiveMeta, inspectDir, inspectMemoryEntry, localStamp, readArchivedMeta, scanArchived, shadowsReserved, stripArchiveMeta } from './scan.js'
19
19
  import { isReserved, nameKey, safeName } from './naming.js'
20
+ import { parseFrontmatter } from './frontmatter.js'
20
21
  import { revisionOf } from './chunks.js'
21
22
  import { retireTaken, returnSource, takeOverSource, writeFileAtomic, writeFileExclusive } from './util.js'
22
23
  import { readLockState } from './lock.js'
@@ -400,6 +401,49 @@ export function archivedRevisionOf(content) {
400
401
  return `${meta.archivedRev || ''}@${revisionOf(stripArchiveMeta(src))}`
401
402
  }
402
403
 
404
+ /**
405
+ * 列出归档区的全部记忆(面板的「已归档」区)。
406
+ *
407
+ * ── 为什么在这里(2.33.x 从 `lib/index.js` 的 `MemoryGateway.listArchived()` 搬来)──
408
+ * 组合根卡在 1000 行 / 20 条本地 import 的硬线上,这条已经没有余量。落点选 `archive.js`
409
+ * 而不是 `scan.js`(2.30.0 的 `listFiles` 搬去了 `scan.js`,那是另一个场景):
410
+ * 归档区的**身份公式**(`archivedRevisionOf` = 归档代次 + 正文 revision)与
411
+ * 「只移不删」的承诺都在本文件,`scanArchived` 只是它的读入口 —— 把列表挂在身份旁边,
412
+ * 语义上是同一件事。而且组合根**已经** import 了 `./memory/archive.js`,
413
+ * 搬过来不增加 import 条数;挂到 `scan.js` 则要反向 import 本文件,凭空造一个
414
+ * `scan ↔ archive` 模块环(两者互相 import,只为这一个函数)。
415
+ *
416
+ * 返回形状与搬出前**一字不差**(`{count, files:[{file,type,description,size,tags,archivedAt,archivedReason,revision}]}`)。
417
+ *
418
+ * 与 `listFiles()` 分开、形状也不同:那个只列活动记忆(多一个字段都会破坏界面与断言依赖的形状);
419
+ * 归档条目额外带 `archivedAt` / `archivedReason` / `revision`。旧版 autodream 工具直接移文件、
420
+ * 不写留痕,所以前两个可能是空串。
421
+ * `revision` 是**内容身份**(2026-10-31 外部审查 Q07):归档代次 + 正文 revision,
422
+ * 删除确认必须原样交回 —— `archivedAt` 只是展示时间,同一分钟内不可区分,
423
+ * 拿它当版本会让旧确认删掉新内容。
424
+ *
425
+ * @param {object} ctx — 宿主上下文(`scanArchived` 读目录用)
426
+ * @returns {Promise<{count:number, files:Array<object>}>}
427
+ */
428
+ export async function listArchivedMemory(ctx) {
429
+ const files = await scanArchived(ctx)
430
+ const out = files.map(f => {
431
+ const meta = parseFrontmatter(f.content)
432
+ const archived = readArchivedMeta(f.content)
433
+ return {
434
+ file: f.name,
435
+ type: meta.type || 'reference',
436
+ description: meta.description || '',
437
+ size: f.content.length,
438
+ tags: meta.tags,
439
+ archivedAt: archived.archivedAt,
440
+ archivedReason: archived.archivedReason,
441
+ revision: archivedRevisionOf(f.content),
442
+ }
443
+ })
444
+ return { count: out.length, files: out }
445
+ }
446
+
403
447
  /**
404
448
  * 从归档区**彻底删除**一条记忆(不可恢复)。
405
449
  *
@@ -22,7 +22,7 @@
22
22
  import { readFile } from 'node:fs/promises'
23
23
  import { dirname, join } from 'node:path'
24
24
  import { nameKey } from './naming.js'
25
- import { resolveStateRoot } from './config.js'
25
+ import { MEMORY_DIR, resolveStateRoot } from './config.js'
26
26
  import { createWriteQueue, writeFileAtomic } from './util.js'
27
27
  import { createFileLease } from '../shared/file-lease.js'
28
28
 
@@ -169,3 +169,22 @@ export async function setLocked(memoryDir, name, locked) {
169
169
  }
170
170
  })
171
171
  }
172
+
173
+ /**
174
+ * 组合根「上锁 / 解锁」那条 remote 的落点(2.33.x 从 `lib/index.js` 的
175
+ * `MemoryGateway.setLocked(name, locked)` 薄壳搬来)。
176
+ *
177
+ * 搬的是两条**归一**,不是逻辑:
178
+ * 1. 记忆目录用插件默认目录(`MEMORY_DIR`),不接受界面传入 —— 跟 `openMemoryDir` 同一条纪律;
179
+ * 2. `locked === true` 严格归一:界面传 `'true'` / `1` / `{locked:true}` 一律当作**没勾**,
180
+ * 与搬出前一字不差(放宽成真值会让「取消锁定」的请求变成上锁)。
181
+ * 组合根现在只剩一行转发,行数护栏多出来一格给下一个功能。
182
+ *
183
+ * @param {string} name — 记忆文件名(`setLocked` 内部按 `nameKey` 归一)
184
+ * @param {boolean} locked — 只有严格的 `true` 才算上锁
185
+ * @returns {Promise<{ok:true, file:string, locked:boolean}
186
+ * | {ok:false, code:string, error:string}>}
187
+ */
188
+ export async function setLockedInMemoryDir(name, locked) {
189
+ return await setLocked(MEMORY_DIR, name, locked === true)
190
+ }
@@ -673,7 +673,7 @@ const CHECKPOINT_READ_LIMIT = 256 * 1024
673
673
  * @returns {Promise<{ok: boolean, tasks: Array<{taskId: string, project: string, revision: number, items: string[]}>,
674
674
  * truncated: boolean, error?: string}>} **绝不抛**
675
675
  */
676
- export async function scanCheckpointOpen(stateRoot) {
676
+ export async function scanCheckpointOpen(stateRoot, ctx) {
677
677
  const dir = join(typeof stateRoot === 'string' && stateRoot !== '' ? stateRoot : '.', TASKS_DIR_NAME)
678
678
  let entries = []
679
679
  try {
@@ -699,9 +699,12 @@ export async function scanCheckpointOpen(stateRoot) {
699
699
  const gate = await inspectMemoryEntry(full, { limitBytes: CHECKPOINT_READ_LIMIT })
700
700
  if (!gate.ok) {
701
701
  // 「这个任务没有 WORKING.md」是正常状态;别的失败要出声,否则面板会说「没有欠活」。
702
+ // ⚠️ 2.33.2:`warnLog(ctx, msg, sessionId)` 是**三个参数**,原来只传了一个字符串 ——
703
+ // `ctx` 收到消息、`msg` 是 undefined,日志里永远是 `sage-mem: undefined`。
704
+ // 待办看板「某个检查点坏了」这条信息从 2.15.2 加闸门起就没打出来过。
702
705
  if (gate.code !== 'missing') {
703
706
  skipped += 1
704
- warnLog(`checkpoints: skip ${id}: ${gate.error}`)
707
+ warnLog(ctx, `checkpoints: skip ${id}: ${gate.error}`)
705
708
  }
706
709
  continue
707
710
  }
@@ -710,7 +713,7 @@ export async function scanCheckpointOpen(stateRoot) {
710
713
  text = await readVerified(full, gate, 'utf8')
711
714
  } catch (err) {
712
715
  skipped += 1
713
- warnLog(`checkpoints: skip ${id}: ${(err && err.message) || err}`)
716
+ warnLog(ctx, `checkpoints: skip ${id}: ${(err && err.message) || err}`)
714
717
  continue
715
718
  }
716
719
  const parsed = parseCheckpoint(text)
@@ -0,0 +1,35 @@
1
+ /**
2
+ * **仅供测试**的只读出口(2.33.x 从 `lib/index.js` 末尾的 `export const __testables` 整段搬来)。
3
+ *
4
+ * 为何搬:组合根卡在 1000 行 / 20 条本地 import 两条硬线上,而这个对象的内容物
5
+ * 全部来自 `memory/` 下层(`frontmatter.js` 的解析器、`retrieval.js` 的双字打分与名额裁剪、
6
+ * `config.js` 的上限常量)—— 它本来就不该让组合根替它 import 一遍那三份模块。
7
+ * 搬过来顺带还回一条 import 名额(`./memory/retrieval.js` 原来只服务这一个对象)。
8
+ *
9
+ * ⚠️ 组合根仍然 `export { testables as __testables }` 转发一次,**导出名不变**:
10
+ * 消费方是四个测试套件(`test/inject-test.mjs` / `test/retrieval-test.mjs` /
11
+ * `test/memory-tools-test.mjs` / `test/archive-test.mjs`),它们读的是 `lib/index.js` 上的
12
+ * `__testables`。搬迁与改名是两件事,不该混在同一个改动里。
13
+ *
14
+ * 检索这条链(frontmatter 解析 → 双字打分 → 名额裁剪)没有任何对外可见的调用面:
15
+ * 想验证「写了 aliases 之后换个说法能不能命中」,否则只能起一个真的 DSH 端到端跑一遍。
16
+ * 把这些纯函数露出来是为了能写断言,**不是给外部用的 API**,别依赖。
17
+ */
18
+ import { parseAliases, parseBaseline, parseBaselinePriority, parseFrontmatter, parseTags } from './frontmatter.js'
19
+ import { ageDays, bigrams, score, selectBaseline, selectRelevant } from './retrieval.js'
20
+ import { MAX_BASELINE, MAX_CHARS_PER_FILE, MAX_RESULTS, MAX_SESSION_BYTES, RECALL_DISCIPLINE, STALE_DAYS } from './config.js'
21
+
22
+ export const testables = {
23
+ bigrams,
24
+ score,
25
+ parseFrontmatter,
26
+ parseAliases,
27
+ parseBaselinePriority,
28
+ parseBaseline,
29
+ parseTags,
30
+ ageDays,
31
+ selectRelevant,
32
+ selectBaseline,
33
+ limits: { MAX_RESULTS, MAX_CHARS_PER_FILE, MAX_BASELINE, MAX_SESSION_BYTES, STALE_DAYS },
34
+ recallDiscipline: RECALL_DISCIPLINE,
35
+ }
@@ -24,13 +24,15 @@
24
24
  */
25
25
 
26
26
  import { createHash } from 'node:crypto'
27
- import { mkdir } from 'node:fs/promises'
27
+ import { mkdir, readFile, unlink } from 'node:fs/promises'
28
28
  import { dirname, join } from 'node:path'
29
- import { readVerified } from './scan.js'
29
+ import { MEMORY_DIR } from './config.js'
30
+ import { isReserved, nameKey, safeName } from './naming.js'
31
+ import { inspectMemoryEntry, readVerified, shadowsReserved } from './scan.js'
30
32
  // 2.10.1:软线体积提醒。判据只有一份(`size-policy.js`),这里只负责「写成功之后
31
33
  // 把等级放进回执、并落一行日志」,不自己写阈值 —— 阈值写两处,迟早两处对不上。
32
34
  import { adviceText, classifySize, kindOfName } from './size-policy.js'
33
- import { warnLog, writeFileAtomic, writeFileExclusive } from './util.js'
35
+ import { retireTaken, returnSource, takeOverSource, warnLog, writeFileAtomic, writeFileExclusive } from './util.js'
34
36
 
35
37
  /** 冲突码:内容在「读快照」之后被改过。固定字符串,界面与测试都只认它。 */
36
38
  export const ERR_STALE_REVISION = 'stale_revision'
@@ -247,3 +249,104 @@ export async function writeSnapshot(target, content, gate, opts, meta) {
247
249
  }
248
250
  return { ok: true, file: name, revision: revisionOf(Buffer.from(content, 'utf8')) }
249
251
  }
252
+
253
+ /**
254
+ * 删除单个记忆文件:保留名一律拒绝(unlink 不可逆)。判定同 `writeFile`。
255
+ *
256
+ * ── 为什么在这里(2.33.x 从 `lib/index.js` 的 `MemoryGateway.deleteFile()` 整段搬来)──
257
+ * 它不属于「远程方法接线」,它属于**写协议**:先接管、再核对内容身份、最后才删 ——
258
+ * 与上面的 `prepareWrite`(三道闸)和 `writeSnapshot`(revision 守卫)是同一族动作,
259
+ * 差别只在结尾那一步是 `retireTaken` 而不是 `writeFileAtomic`。留在组合根上只会让
260
+ * 那条 1000 行的结构守卫更紧;搬过来之后组合根那一条 remote 只剩一行转发。
261
+ * 签名与回执形状**一字未改**(`{ok:true,file}` / `{ok:false,code,error[,keptAt]}`)。
262
+ *
263
+ * 2.21.0:新增可选 `opts.expectedRevision`。面板必须回传确认时看到的版本;
264
+ * 宿主先原子接管该名字,再对**接管到手的实物**核内容身份。内容对不上或接管时
265
+ * 已被换成别的版本,就用 link 还回,绝不删除没被用户确认过的那一版。
266
+ *
267
+ * @param {object} ctx — 插件上下文(只用于 `warnLog` 的日志出口,不读服务)
268
+ * @param {string} name — 记忆文件名(走 `safeName`,不接受路径)
269
+ * @param {{expectedRevision?:string}} [opts]
270
+ */
271
+ export async function deleteMemoryFile(ctx, name, opts) {
272
+ if (isReserved(name)) {
273
+ return { ok: false, error: `sage-mem: reserved file, refusing to delete: ${nameKey(name)}` }
274
+ }
275
+ const safe = safeName(name)
276
+ if (!safe) return { ok: false, code: 'invalid_name', error: 'sage-mem: invalid file name' }
277
+ const full = join(MEMORY_DIR, safe)
278
+ // 同 writeFile:8.3 短名能绕过名字文本判据,删除保护也必须看文件身份。
279
+ if (await shadowsReserved(full)) {
280
+ return { ok: false, error: `sage-mem: reserved file (它的另一个名字是 ${safe}),拒绝删除` }
281
+ }
282
+ const expected = typeof opts?.expectedRevision === 'string' && opts.expectedRevision
283
+ ? opts.expectedRevision
284
+ : ''
285
+ // 旧调用方兼容:仍按名字删,但必须留痕。新面板不会走这里。
286
+ if (!expected) {
287
+ warnLog(ctx, `deleteFile(${safe}) 未提供 expectedRevision,按旧协议删除(无法保证是你看见的那一版)`)
288
+ await unlink(full)
289
+ return { ok: true, file: safe }
290
+ }
291
+
292
+ const gate = await inspectMemoryEntry(full, { limitBytes: null })
293
+ if (!gate.ok) {
294
+ return {
295
+ ok: false,
296
+ code: gate.code === 'missing' ? 'missing' : 'read_failed',
297
+ error: `sage-mem: 读不到 ${safe} 的当前版本(${gate.error}),没有删除`,
298
+ }
299
+ }
300
+ let bytes
301
+ try {
302
+ bytes = await readVerified(full, gate, false)
303
+ } catch (err) {
304
+ return {
305
+ ok: false,
306
+ code: 'read_failed',
307
+ error: `sage-mem: 读不到 ${safe} 的当前内容(${err?.code ?? err}),没有删除`,
308
+ }
309
+ }
310
+
311
+ // 先接管、再核对:不留给「比对 → unlink」之间换版本的窗口。
312
+ const taken = await takeOverSource(full, bytes, 'deleting')
313
+ if (!taken.ok) {
314
+ const code = taken.code === 'not_found'
315
+ ? 'missing'
316
+ : taken.code === 'changed' ? 'stale_revision' : 'delete_failed'
317
+ const extra = taken.keptAt ? `;被移走的那份已保留在 ${taken.keptAt}` : ''
318
+ return {
319
+ ok: false,
320
+ code,
321
+ error: code === 'stale_revision'
322
+ ? `sage-mem: ${safe} 在你确认之后已经被改写,没有删除${extra}`
323
+ : `sage-mem: 删除 ${safe} 失败(${taken.cause?.code ?? taken.code}),没有删除${extra}`,
324
+ ...(taken.keptAt ? { keptAt: taken.keptAt } : {}),
325
+ }
326
+ }
327
+
328
+ let actual
329
+ try {
330
+ actual = revisionOf(await readFile(taken.taken))
331
+ } catch (err) {
332
+ const back = await returnSource(taken.taken, full)
333
+ return {
334
+ ok: false,
335
+ code: 'read_failed',
336
+ error: `sage-mem: 无法核对 ${safe} 的内容版本(${err?.code ?? err}),没有删除`,
337
+ ...(back.ok ? {} : { keptAt: back.keptAt }),
338
+ }
339
+ }
340
+ if (actual !== expected) {
341
+ const back = await returnSource(taken.taken, full)
342
+ return {
343
+ ok: false,
344
+ code: 'stale_revision',
345
+ error: `sage-mem: ${safe} 在你确认之后已经被改写(当前版本 ${actual.slice(0, 12)}…),没有删除`,
346
+ ...(back.ok ? {} : { keptAt: back.keptAt }),
347
+ }
348
+ }
349
+
350
+ await retireTaken(taken.taken)
351
+ return { ok: true, file: safe }
352
+ }
package/lib/settings.js CHANGED
@@ -208,17 +208,64 @@ export function parseExperimentalPatch(experimental) {
208
208
  return { ok: true, patch: Object.keys(patch).length ? patch : null }
209
209
  }
210
210
 
211
- /** 读 `<状态根>/reserved.json`(用户声明的保护名单)。**保留原始大小写**,好让 get 读回一致。 */
212
- export async function readReservedFile() {
211
+ /**
212
+ * 读 `<状态根>/reserved.json`(用户声明的保护名单)。**保留原始大小写**,好让 get 读回一致。
213
+ *
214
+ * ⚠️ **2.33.2 起 fail-open 改为「失败必须出声」**。原来这里任何异常都 `return []`,于是
215
+ * `reserved.json` 坏一个字节就等于「用户额外声明的保护名单整份消失」,而 `writeFile` /
216
+ * `deleteFile` / autodream 的保护判据全部照常放行 —— 没有任何日志、没有任何诊断,用户
217
+ * 直到某条「本该保护」的记忆被自动整理删掉才会发现。同一个坑 `memory/lock.js:18-20`
218
+ * 已经改成 `status:'unknown'` 并 fail-closed,这里只修了一半。
219
+ *
220
+ * 现在的语义(与 `lock.js` 同一口径):
221
+ * - **ENOENT** → `[]` 且无诊断(从没设过额外保护名,正常状态);
222
+ * - **文件坏了 / 不是数组 / 含非法项** → 仍然返回能用的那部分(一个字节都不丢),
223
+ * 但**同时给一句人话诊断**,由 `readSettingsSnapshot` 拼进 `limitDiagnostics` 上屏。
224
+ *
225
+ * 为什么不是「坏了就拒绝启动」:两个内置保护名(`MEMORY.md` / `session-log.md`)来自
226
+ * `memory/config.js` 的 `RESERVED_FILES`,是模块加载时读的常量,不依赖这个文件 ——
227
+ * 最核心的保护并不会因为它坏而失效。所以正确的处置是「降级 + 明说」,不是「拒绝服务」。
228
+ *
229
+ * @returns {Promise<{names: string[], error: string|null}>}
230
+ */
231
+ export async function readReservedFileDetailed() {
232
+ let text
233
+ try {
234
+ text = await readFile(RESERVED_FILE, 'utf8')
235
+ } catch (err) {
236
+ if (err && err.code === 'ENOENT') return { names: [], error: null }
237
+ return {
238
+ names: [],
239
+ error: `保护名单 reserved.json 读不出来(${(err && err.message) || err}):本次按「没有额外保护名」处理,内置保护仍在`,
240
+ }
241
+ }
242
+ let parsed
213
243
  try {
214
- const arr = JSON.parse(await readFile(RESERVED_FILE, 'utf8'))
215
- if (!Array.isArray(arr)) return []
216
- return arr
217
- .map((s) => String(s).trim())
218
- .filter((s) => s.endsWith('.md') && !s.includes('/') && !s.includes('\\') && !s.startsWith('..'))
219
- } catch {
220
- return []
244
+ parsed = JSON.parse(text)
245
+ } catch (err) {
246
+ return {
247
+ names: [],
248
+ error: `保护名单 reserved.json 不是合法 JSON(${(err && err.message) || err}):本次按「没有额外保护名」处理,内置保护仍在`,
249
+ }
250
+ }
251
+ if (!Array.isArray(parsed)) {
252
+ return { names: [], error: '保护名单 reserved.json 不是数组:本次按「没有额外保护名」处理,内置保护仍在' }
221
253
  }
254
+ const names = parsed
255
+ .map((s) => String(s).trim())
256
+ .filter((s) => s.endsWith('.md') && !s.includes('/') && !s.includes('\\') && !s.startsWith('..'))
257
+ const dropped = parsed.length - names.length
258
+ return {
259
+ names,
260
+ error: dropped > 0
261
+ ? `保护名单 reserved.json 有 ${dropped} 项不是「单段 .md 名」,已忽略(其余 ${names.length} 项照常生效)`
262
+ : null,
263
+ }
264
+ }
265
+
266
+ /** 兼容出口:只要名单、不要诊断的调用方(目前无内部调用方,保留给外部脚本)。 */
267
+ export async function readReservedFile() {
268
+ return (await readReservedFileDetailed()).names
222
269
  }
223
270
 
224
271
  /**
@@ -267,17 +314,20 @@ export async function readSettingsSnapshot(ctx) {
267
314
  // 2.17.0:从 `EXPERIMENTAL_SPECS` 派生(原先手写 mmr/todoBoard 两份,加开关就得来改第三次)。
268
315
  const experimental = Object.fromEntries(Object.keys(EXPERIMENTAL_SPECS).map((k) => [k, liveExperimental(k)]))
269
316
  const pendingLab = pendingExperimental(fileRead.data)
317
+ // 2.33.2:保护名单的读取**先于**诊断汇总(原来静默回落空名单,等于「用户声明的保护被悄悄撤掉」)。
318
+ const reservedRead = await readReservedFileDetailed()
270
319
  // 坏设置给明确诊断、不静默回默认:启动期那份 + 这次读文件的问题 + 逐项非法/越界说明,去重后一起给。
271
320
  const limitDiagnostics = [...new Set([
272
321
  ...STARTUP_LIMIT_DIAGNOSTICS,
273
322
  ...STARTUP_EXPERIMENTAL_DIAGNOSTICS,
274
323
  ...(fileRead.error ? [fileRead.error] : []),
275
324
  ...pending.diagnostics,
325
+ ...(reservedRead.error ? [reservedRead.error] : []),
276
326
  ])]
277
327
  if (limitDiagnostics.length > 0) {
278
328
  warnLog(ctx, `上限设置有问题(本次仍按环境变量/默认值生效):${limitDiagnostics.join(';')}`)
279
329
  }
280
- const reservedExtra = await readReservedFile()
330
+ const reservedExtra = reservedRead.names
281
331
  // 2.25.0:外部访问(读侧)。与 limits 不同 —— 它**不进 restartRequired**:
282
332
  // 挂载层每次导出前现读,面板保存后立刻生效。
283
333
  const externalRead = resolveExternal(fileRead.data?.external)
@@ -321,6 +321,14 @@ export const settingsExternalSchema = z.object({
321
321
  'port': z.number().readonly(),
322
322
  'pollSeconds': z.number().readonly(),
323
323
  }).readonly()
324
+ // 2.27.0:跨设备同步(`sync`)的**设置段**。判据在 `lib/sync/policy.js`(`resolveSync` /
325
+ // `parseSyncPatch`),这里只声明传输形状,逐字段对齐 `resolveSync()` 的实际返回:
326
+ // `{ host: string, remotePath: string }` —— 两个都是**去空白后的字符串**,坏值被清成空串
327
+ // (不是 null / undefined),所以这里不能用 nullable / optional 的内部字段。
328
+ export const settingsSyncSchema = z.object({
329
+ 'host': z.string().readonly(),
330
+ 'remotePath': z.string().readonly(),
331
+ }).readonly()
324
332
  export const settingsSchema = z.object({
325
333
  'limits': settingsLimitsSchema,
326
334
  'pendingLimits': settingsLimitsSchema,
@@ -338,6 +346,16 @@ export const settingsSchema = z.object({
338
346
  // 2.25.0:外部访问(读侧)的生效值与诊断。**不进** restartRequired(挂载层现读现用)。
339
347
  'external': settingsExternalSchema,
340
348
  'externalDiagnostics': z.array(z.string()).readonly(),
349
+ // 从 2.27.0 起就漏声明:跨设备同步的生效值与诊断。`readSettingsSnapshot`(lib/settings.js 末尾)
350
+ // **无条件**返回这两项,而这里原先一条都没声明 —— zod 的 object 剥掉未声明的键,于是
351
+ // 「远端填好了、面板读回来是空的」:工具 `memory_sync_check` 拿 sync 当默认远端,也跟着拿不到。
352
+ //
353
+ // ⚠️ 为什么写成 optional 而不是必填:这是 additive 契约(只加不改)—— 宿主侧总是给,
354
+ // 但旧版本宿主 / 手写夹具没有这两项,写成必填会把「旧快照」整条判成坏结果(
355
+ // `{ok:true, settings}` 变成 transport error),那比缺一个字段更糟。
356
+ // **声明**才是这一条的关键:声明了 strict 就不会剥,读回的值才到得了界面。
357
+ 'sync': settingsSyncSchema.optional(),
358
+ 'syncDiagnostics': z.array(z.string()).readonly().optional(),
341
359
  }).readonly()
342
360
  export const settingsPatchSchema = z.object({
343
361
  'limits': z.object({
@@ -365,6 +383,18 @@ export const settingsPatchSchema = z.object({
365
383
  'port': z.number().optional(),
366
384
  'pollSeconds': z.number().optional(),
367
385
  }).readonly().optional(),
386
+ // 2026-12-04 修:跨设备同步补丁 —— 从 2.27.0 起就漏了。`lib/settings.js` 的
387
+ // `applySettingsPatch` 从 2.27.0 起就在处理 `p.sync`(`parseSyncPatch` → 合并落盘),
388
+ // 但补丁这一侧没声明 `sync`,于是 zod 在**到宿主之前**就把它整段剥掉:
389
+ // `p.sync` 永远是 undefined → 校验全过 → 落到最后判成 `empty patch` 并回 `{ok:false}`。
390
+ // 症状是「设置面板保存失败,报错说没改任何东西」,而不是「同步设置存不进去」。
391
+ //
392
+ // 两个字段都可选:`parseSyncPatch` 允许只给 host 或只给 remotePath,
393
+ // 没给的那一项不该被旧值覆盖(与 limits / ui / external 同一套语义)。
394
+ 'sync': z.object({
395
+ 'host': z.string().optional(),
396
+ 'remotePath': z.string().optional(),
397
+ }).readonly().optional(),
368
398
  }).readonly()
369
399
  export const settingsResultSchema = z.object({
370
400
  'ok': z.boolean().readonly(),
@@ -282,7 +282,13 @@ export const TYPERT = {
282
282
  invocation: { kind: 'direct' },
283
283
  parameters: [
284
284
  { name: 'id', wire: 'id', source: 'json', codec: { mode: 'strict', typeSymbol: 'sage-mem/types#SubId', schema: subIdSchema, create: () => subIdSchema } },
285
- { name: 'reason', wire: 'reason', source: 'json', acceptsUndefined: true, codec: { mode: 'strict', typeSymbol: 'sage-mem/types#SubReason', schema: subIdSchema, create: () => subIdSchema } },
285
+ // 2026-12-04 修:`reason` 挂 **subReasonSchema**(max 1000),不是 `subIdSchema`(max 80)。
286
+ // 这里原先两条参数挂的是同一个 `subIdSchema` —— 长得像,但一个装 id、一个装人话。
287
+ // 后果:理由超过 80 字就在**传输层**被拒,而 `lib/intake/policy.js` 侧是按 1000 设计的
288
+ // (`String(raw.reason).trim().slice(0, 1000)`),于是「拒绝理由写详细一点」这条路
289
+ // 永远走不通,且报错来自网关、跟业务毫无关系。
290
+ // ⚠️ `id` 那一条仍然必须是 `subIdSchema`(80)—— 别跟着一起放宽。
291
+ { name: 'reason', wire: 'reason', source: 'json', acceptsUndefined: true, codec: { mode: 'strict', typeSymbol: 'sage-mem/types#SubReason', schema: subReasonSchema, create: () => subReasonSchema } },
286
292
  ],
287
293
  result: { mode: 'strict', typeSymbol: 'sage-mem/types#IntakeRejectResult', schema: intakeRejectResultSchema, create: () => intakeRejectResultSchema },
288
294
  sourceLocation: { "file": "lib/index.js", "line": 1, "column": 1 },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "sage-mem",
3
3
  "description": "Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.",
4
- "version": "2.33.0",
4
+ "version": "2.33.2",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "icon": "./icon.png",