dsh-memory-palace 1.7.0 → 1.7.2-alpha.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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  把 WorkBuddy 的文件式记忆系统移植进 [DeepSeek Harness](https://www.deepseek.com/harness/) —— 为 Harness 提供**跨会话持久化、人类可直接编辑的 Markdown 记忆**。
4
4
 
5
- [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE) [![Awesome DSH Plugin](https://awesome-dsh-plugin.com/badge.svg)](https://awesome-dsh-plugin.com) [![npm](https://img.shields.io/npm/v/dsh-memory-palace.svg?label=npm&labelColor=000000&color=ff4b01)](https://www.npmjs.com/package/dsh-memory-palace) [![DeepSeek Harness:0.1.2-rc.1](https://img.shields.io/badge/DeepSeek%20Harness-0.1.2--rc.1-success.svg?labelColor=4D6BFE)](https://github.com/deepseek-ai/deepseek-harness)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE) [![Awesome DSH Plugin](https://awesome-dsh-plugin.com/badge.svg)](https://awesome-dsh-plugin.com) [![npm](https://img.shields.io/npm/v/dsh-memory-palace.svg?label=npm&labelColor=000000&color=ff4b01)](https://www.npmjs.com/package/dsh-memory-palace) [![DeepSeek Harness:0.1.6-alpha.2](https://img.shields.io/badge/DeepSeek%20Harness-0.1.6--alpha.2-success.svg?labelColor=4D6BFE)](https://github.com/deepseek-ai/deepseek-harness)
6
6
 
7
7
  ## 特性
8
8
 
@@ -12,10 +12,11 @@
12
12
  - **WorkBuddy / CodeBuddy 桥接**:项目已有对应记忆目录时直接读写,无需重复维护。
13
13
  - **记忆工具**:AI 可主动写入、聚合读取、按内容删除(删除需人工确认),写入自带去重。
14
14
  - **手动蒸馏**:会话标题栏一键把当前对话或项目记忆提炼成长期记忆。
15
- - **设置页集成**:全部配置均可在 DSH 设置面板中图形化调整,无需改配置文件。
15
+ - **设置页集成**:全部配置均可在 DSH 设置面板中图形化调整(按板块折叠),无需改配置文件。
16
+ - **自定义指令**:不适合写进记忆的特殊指令可在设置页配置,插件经系统提示词注入。
16
17
  - **主动记忆(插件模式)**:以指令引导 AI 在完成任务、修复问题、确定决策、获知偏好时主动落档。
17
18
  - **智能模式**:由模型自动提炼每轮新增内容,摘要进日志、长期事实进记忆。
18
- - **记忆注入**:长期记忆全程常驻、每个步骤都可见;今日日志按轮次注入,避免上下文膨胀。
19
+ - **记忆注入**:长期记忆与今日日志以「会话起始快照」常驻上下文、按文件身份各只注入一次 —— 既保证每个步骤都可见,又不破坏前缀缓存、不堆积冗余快照。
19
20
  - **混合模式(🔥推荐)**:子代理每轮自动整理日志并去重,长期记忆由主 AI 主动维护,兼顾自动化与可控性。
20
21
  - **标准插件包**:经官方插件机制一键安装,无需改动 harness。
21
22
 
@@ -41,10 +42,12 @@
41
42
  **读取(每轮对话)**——两条通道并行:
42
43
 
43
44
  ```
44
- ① 长期记忆:全程常驻,每个步骤都可见;内容未变只写一次,压缩后自动重注
45
- ② 今日日志:随系统提示词按轮次注入(高频变化,不进对话历史以免膨胀)
45
+ ① 系统提示词(恒定):记忆公民指令 / 自定义指令等固定内容,前缀缓存友好
46
+ ② 对话历史投影(易变):用户级 + 项目级长期记忆、今日日志——按文件身份各注入一次,压缩后自动重注最新版
46
47
  ```
47
48
 
49
+ > **极简模式(静默预设)**:宿主的「模式」= agent 平面预设(`presets/*/agent.cordis.yml`),官方 minimal 用 persona `complete: true` 独占系统提示词,是刻意留白的「裸测环境」(跑分口径)。但本插件注册在 host 平面,各通道对**每个会话**都生效(`complete` 只吞 system 提示词、**不裁工具**),所以必须按会话自行静默。默认 `silentPresets = ["minimal"]` 已覆盖官方极简模式:命中预设的会话里,系统提示词、记忆投影、7 个记忆工具(**schema 一并隐身,零 token 足迹**)、turn-end 自动写入与 hybrid 记忆子代理**全部关闭**,语义等价于该会话没装本插件,不留半注入状态。判据取会话创建头 `agentPreset`(含未显式指定时的部署默认)与预设切换事件;判据缺失一律 fail-open(不静默),不会因识别不到而丢记忆。要静默其它预设,在设置页「静默预设」里加 id(逗号分隔)。
50
+
48
51
  **写入(每轮结束)**——经「防闲聊闸门」判定后异步追加:
49
52
 
50
53
  ```
@@ -63,7 +66,7 @@
63
66
  |---|---|---|
64
67
  | `memory_note` | 项目级 | 把约定/偏好写入当前项目全部目标 `MEMORY.md`(去重) |
65
68
  | `memory_note_user` | 用户级 | 把跨项目偏好写入 `~/.deepseek-harness/MEMORY.md`(去重) |
66
- | `memory_read` | 聚合 | 一次性读取用户级 + 项目级记忆、今日日志与最近 3 份历史日志 |
69
+ | `memory_read` | 按需 | 读取记忆。`scope` 默认 `memory`(用户级 + 项目级);可选 `project`(仅项目级,与 `memory_write` 的写侧 scope 同名)/ `today` / `yesterday` / `daily`(近三天日志)/ `all`(长期记忆 + 日志) |
67
70
  | `memory_delete` | 用户级/项目级/每日级 | 按内容删除记忆条目(两阶段确认:先预览匹配位置与内容,用户确认后再删;删除动作经 harness 原生确认弹窗硬闸门,真人点允许才真正执行) |
68
71
  | `memory_write`(hybrid) | 项目级/用户级 | 章节化写入:章节存在则末尾追加,不存在则新建章节(章节化格式规范) |
69
72
  | `memory_update_section`(hybrid) | 项目级/用户级 | 整章节精确替换/单条标记删除:oldText 归一化精确匹配防 stale,失败拒绝并回显实际内容 |
@@ -71,13 +74,13 @@
71
74
 
72
75
  ## 安装
73
76
 
74
- 前置要求:已安装 DeepSeek Harness 及其 CLI(`dsh` 命令可用)。
77
+ 前置要求:已安装 DeepSeek Harness 及其 CLI(`dsh` 命令可用)。插件声明的 **dsh 下限为 `0.1.5-rc.1`**(写进 `peerDependencies` 门禁,低于此版本装载期即挡),**已核验至 `0.1.6-alpha.2`**(契约 1–12 与插件占用的宿主面全部通过)。
75
78
 
76
79
  方式一:直接通过 GitHub 安装(推荐,`lib/` 构建产物已随仓库分发,装即用)
77
80
 
78
81
  ```bash
79
82
  dsh plugin --profile web add github:lovezi0/dsh-memory-palace
80
- # 锁定版本:dsh plugin --profile web add github:lovezi0/dsh-memory-palace#v1.7.0
83
+ # 锁定版本:dsh plugin --profile web add github:lovezi0/dsh-memory-palace#v1.7.2-alpha.1
81
84
  ```
82
85
 
83
86
  方式二:clone 后本地安装(开发 / 修改源码场景)
@@ -109,7 +112,7 @@ dsh plugin --profile web remove dsh-memory-palace
109
112
 
110
113
  ## 配置
111
114
  *面板路径为 DSH 设置 →「记忆」*
112
- 所有配置项(基础 / 自动记录 / 开发 三张卡片的字段、默认值与说明)已整理至 [CONFIG.md](./CONFIG.md)
115
+ 所有配置项(核心 / 自定义指令 / 自动记录 / 存储路径与预算 / 开发 五张卡片的字段、默认值与说明)已整理至 [CONFIG.md](./CONFIG.md)
113
116
 
114
117
  ## 开发
115
118
 
@@ -118,12 +121,19 @@ dsh plugin --profile web remove dsh-memory-palace
118
121
 
119
122
  ## 版本历史
120
123
 
124
+ - **1.7.2**
125
+ - **1.7.2-alpha.1**
126
+ - 💪dsh Agent 预设[极简模式]时禁用记忆注入、记忆生成、记忆工具
127
+ - **1.7.1**
128
+ - 💪移除日志重注机制优化缓存命中降低堆积冗余
129
+ - 💪记忆设置UI优化
130
+ - 🔥增加自定义指令 prompt 配置与注入
131
+ - 💪memory_read 增加 scope 参数
121
132
  - **1.7.0**
122
- - **1.7.0.alpha.1**
123
- - 🔥新增独立通道注入记忆文件
124
- - 🐛修复存在多种记忆路径时读取冲突的问题
125
- - 💪优化记忆子 agent 投影消息节省 token
126
- - 💪优化 SUBAGENT_SYSTEM 记忆输出格式
133
+ - 🔥新增独立通道注入记忆文件
134
+ - 🐛修复存在多种记忆路径时读取冲突的问题
135
+ - 💪优化记忆子 agent 投影消息节省 token
136
+ - 💪优化 SUBAGENT_SYSTEM 记忆输出格式
127
137
  - **1.6.3**
128
138
  - npm publish
129
139
  - **1.6.3.alpha.4**
package/lib/client.js CHANGED
@@ -16,12 +16,19 @@ window.__ModuleLoader__.load({
16
16
  title: "记忆",
17
17
  intro: "memory-palace 记忆宫殿:跨会话持久化的 Markdown 记忆。",
18
18
  core: "核心",
19
+ coreDesc: "buddy 记忆桥接与项目记忆目录",
20
+ custom: "自定义指令",
21
+ customDesc: "不适合写进用户记忆的特殊指令,经系统提示词注入",
19
22
  smartSummary: "自动记录",
23
+ smartSummaryDesc: "记忆模式、自动记录与模型参数",
20
24
  storage: "存储路径与预算",
25
+ storageDesc: "记忆文件路径、日志保留与注入预算",
21
26
  bridgeLabel: "桥接 buddy 项目记忆",
22
27
  bridgeHint: "项目已存在 .workbuddy / .codebuddy 记忆目录时直接读写,不再建 .deepseek-harness/memory/",
23
28
  dirsLabel: "buddy 记忆目录(逗号分隔,按序优先)",
24
29
  dirsHint: "例如:.workbuddy/memory, .codebuddy/memory",
30
+ silentPresetsLabel: "静默预设(逗号分隔)",
31
+ silentPresetsHint: "这些 agent 预设下本插件整体隐身:不注入系统提示词与记忆投影、记忆工具不对模型暴露、不写日志、不跑记忆子代理(官方极简模式即「裸测环境」跑分口径)。默认 minimal;留空=关闭该机制。切换预设需新建会话生效。",
25
32
  userPathLabel: "用户级记忆文件",
26
33
  userPathHint: "跨项目个人偏好记忆,默认 ~/.deepseek-harness/MEMORY.md",
27
34
  wsDirLabel: "工作区记忆目录(回退)",
@@ -47,6 +54,8 @@ window.__ModuleLoader__.load({
47
54
  subagentLogBudgetHint: "记忆子代理回喂今日工作日志的字符上限;超出时仅回喂章节目录,子代理按需读取章节。默认 20000。",
48
55
  summaryModelLabel: "模型",
49
56
  summaryModelHint: "记忆插件当前使用的模型(智能模式会话摘要 / 手动蒸馏 / hybrid 记忆子代理共用)。留空=复用当前会话的 provider/model;也可固定廉价小模型省 token。",
57
+ expand: "展开",
58
+ collapse: "收起",
50
59
  save: "保存",
51
60
  saving: "保存中…",
52
61
  discard: "放弃",
@@ -73,6 +82,7 @@ window.__ModuleLoader__.load({
73
82
  distillDebugLogLabel: "蒸馏调试日志",
74
83
  distillDebugLogHint: "开启后向 dsh 服务端控制台(stderr)输出蒸馏 LLM 调用诊断。info 级别仅输出元数据(不含文本);配合 distillLogLevel=debug 会额外打印 LLM 原始响应(分隔符包裹),仅限受信本地排障。",
75
84
  dev: "开发",
85
+ devDesc: "蒸馏调试日志与超时",
76
86
  distillTimeoutLabel: "蒸馏超时(秒)",
77
87
  distillTimeoutHint: "单次蒸馏 LLM 调用的超时上限(秒);超时视为失败并降级。覆盖智能模式摘要与手动蒸馏,默认 60 秒。",
78
88
  summaryMaxTokensLabel: "会话摘要最大 Token",
@@ -80,7 +90,10 @@ window.__ModuleLoader__.load({
80
90
  projectMaxTokensLabel: "项目蒸馏最大 Token",
81
91
  projectMaxTokensHint: "最终输出软预算(prompt 约束,思考不受限;实际硬上限由模型自身 maxTokens 决定)。默认 8000。",
82
92
  feedbackEnabledLabel: "回喂存量记忆",
83
- feedbackEnabledHint: "每次蒸馏时附带项目级 + 用户级记忆作为参考,使其能基于既有记忆做增量维护(delete 仅手动蒸馏开放)。混合模式下仅手动触发蒸馏受影响(自动路径走记忆子代理,自带日志回喂)。默认关。"
93
+ feedbackEnabledHint: "每次蒸馏时附带项目级 + 用户级记忆作为参考,使其能基于既有记忆做增量维护(delete 仅手动蒸馏开放)。混合模式下仅手动触发蒸馏受影响(自动路径走记忆子代理,自带日志回喂)。默认关。",
94
+ customLabel: "自定义指令内容",
95
+ customHint: "非空时注入系统提示词,位置在记忆插件与分工说明之后。对全部会话生效;留空则不注入。",
96
+ customPlaceholder: "例如:回答用中文;代码注释用英文;提交信息用祈使句…"
84
97
  };
85
98
 
86
99
  const en = {
@@ -88,12 +101,19 @@ window.__ModuleLoader__.load({
88
101
  title: "Memory",
89
102
  intro: "memory-palace: persistent, human-readable Markdown memory across sessions.",
90
103
  core: "Core",
104
+ coreDesc: "Buddy memory bridging and workspace memory dirs",
105
+ custom: "Custom instructions",
106
+ customDesc: "Special instructions that do not belong in user memory, injected via the system prompt",
91
107
  smartSummary: "Auto-record",
108
+ smartSummaryDesc: "Memory mode, auto-record and model parameters",
92
109
  storage: "Storage & budgets",
110
+ storageDesc: "Memory file paths, log retention and injection budgets",
93
111
  bridgeLabel: "Bridge buddy project memory",
94
112
  bridgeHint: "Read/write directly into existing .workbuddy / .codebuddy memory dirs instead of creating .deepseek-harness/memory/",
95
113
  dirsLabel: "Buddy memory dirs (comma-separated, first wins)",
96
114
  dirsHint: "e.g. .workbuddy/memory, .codebuddy/memory",
115
+ silentPresetsLabel: "Silent presets (comma-separated)",
116
+ silentPresetsHint: "Under these agent presets the plugin goes fully invisible: no system-prompt or memory projection injection, memory tools hidden from the model, no logging, no memory sub-agent (the official minimal mode is the bare-benchmark preset). Default: minimal; leave empty to disable this rule. Switching presets takes effect in a new session.",
97
117
  userPathLabel: "User memory file",
98
118
  userPathHint: "Cross-project preferences, default ~/.deepseek-harness/MEMORY.md",
99
119
  wsDirLabel: "Workspace memory dir (fallback)",
@@ -119,6 +139,8 @@ window.__ModuleLoader__.load({
119
139
  subagentLogBudgetHint: "Max chars of today's daily log fed back to the memory sub-agent; beyond this only the chapter TOC is fed and the sub-agent reads sections on demand. Default 20000.",
120
140
  summaryModelLabel: "Model",
121
141
  summaryModelHint: "The model currently used by the memory plugin (shared by smart-mode session summarization / manual distillation / the hybrid memory sub-agent). Leave empty to reuse the current session's provider/model, or pin a cheap model (provider/model) to save tokens.",
142
+ expand: "Expand",
143
+ collapse: "Collapse",
122
144
  save: "Save",
123
145
  saving: "Saving…",
124
146
  discard: "Discard",
@@ -145,6 +167,7 @@ window.__ModuleLoader__.load({
145
167
  distillDebugLogLabel: "Distill debug log",
146
168
  distillDebugLogHint: "When on, prints distill LLM call diagnostics to the dsh server console (stderr). info level prints metadata only (no text); with distillLogLevel=debug it additionally prints the raw LLM response (wrapped in delimiters), for trusted local troubleshooting only.",
147
169
  dev: "Developer",
170
+ devDesc: "Distill debug log and timeout",
148
171
  distillTimeoutLabel: "Distill timeout (s)",
149
172
  distillTimeoutHint: "Timeout (in seconds) for a single distill LLM call; on timeout it fails and degrades. Covers both smart-mode summary and manual distillation. Default 60s.",
150
173
  summaryMaxTokensLabel: "Session summary max tokens",
@@ -152,7 +175,10 @@ window.__ModuleLoader__.load({
152
175
  projectMaxTokensLabel: "Project distill max tokens",
153
176
  projectMaxTokensHint: "Final output soft budget (prompt constraint, thinking not limited; actual hard cap is the model's own maxTokens). Default 8000.",
154
177
  feedbackEnabledLabel: "Feed existing memory into distillation",
155
- feedbackEnabledHint: "Feed the project-level + user-level memory in as reference on every distillation so the LLM can maintain existing memory incrementally (delete is only allowed via manual distillation). In hybrid mode only manual distillation is affected (the automatic path runs through the memory sub-agent, which feeds the log itself). Off by default."
178
+ feedbackEnabledHint: "Feed the project-level + user-level memory in as reference on every distillation so the LLM can maintain existing memory incrementally (delete is only allowed via manual distillation). In hybrid mode only manual distillation is affected (the automatic path runs through the memory sub-agent, which feeds the log itself). Off by default.",
179
+ customLabel: "Custom instruction text",
180
+ customHint: "When non-empty it is injected into the system prompt right after the memory-plugin and memory-roles instructions. Applies to every session; leave empty to inject nothing.",
181
+ customPlaceholder: "e.g. Answer in Chinese; write code comments in English; use imperative commit subjects…"
156
182
  };
157
183
 
158
184
 
@@ -164,6 +190,8 @@ window.__ModuleLoader__.load({
164
190
  return {
165
191
  bridgeBuddyMemory: v.bridgeBuddyMemory === false ? "false" : "true",
166
192
  buddyWorkspaceMemoryDirs: Array.isArray(v.buddyWorkspaceMemoryDirs) ? v.buddyWorkspaceMemoryDirs.join(", ") : ".workbuddy/memory, .codebuddy/memory",
193
+ // v1.7.2:静默预设名单(数组 ↔ 逗号串,与 buddyWorkspaceMemoryDirs 同款约定)
194
+ silentPresets: Array.isArray(v.silentPresets) ? v.silentPresets.join(", ") : "minimal",
167
195
  userMemoryPath: v.userMemoryPath || "~/.deepseek-harness/MEMORY.md",
168
196
  workspaceMemoryDir: v.workspaceMemoryDir || ".deepseek-harness/memory",
169
197
  dailyLogRetentionDays: v.dailyLogRetentionDays != null ? String(v.dailyLogRetentionDays) : "30",
@@ -179,7 +207,8 @@ window.__ModuleLoader__.load({
179
207
  projectMaxTokens: v.projectMaxTokens != null ? String(v.projectMaxTokens) : "8000",
180
208
  reorgCooldownDays: v.reorgCooldownDays != null ? String(v.reorgCooldownDays) : "7",
181
209
  subagentLogBudget: v.subagentLogBudget != null ? String(v.subagentLogBudget) : "20000",
182
- feedbackEnabled: v.feedbackEnabled === false ? "false" : "true"
210
+ feedbackEnabled: v.feedbackEnabled === false ? "false" : "true",
211
+ customInstructions: v.customInstructions || ""
183
212
  };
184
213
  }
185
214
 
@@ -250,6 +279,9 @@ window.__ModuleLoader__.load({
250
279
  const [failed, setFailed] = react.useState(false);
251
280
  const [validation, setValidation] = react.useState(null);
252
281
  const [modelOptions, setModelOptions] = react.useState([]);
282
+ // v1.7.1(特性2):折叠卡片的展开态(key → bool)。照抄宿主 ui-settings-plugins/PluginCard
283
+ // 的语义 —— 纯前端临时状态、**不持久化**:「用户打开哪张卡」是一次阅读手势,不是配置。
284
+ const [openCards, setOpenCards] = react.useState({});
253
285
 
254
286
  // 初始加载(从自有 route 读真实值)。
255
287
  react.useEffect(() => {
@@ -326,6 +358,9 @@ window.__ModuleLoader__.load({
326
358
  }
327
359
  } else if (field === "buddyWorkspaceMemoryDirs") {
328
360
  section[field] = text.split(",").map((s) => s.trim()).filter(Boolean);
361
+ } else if (field === "silentPresets") {
362
+ // v1.7.2:数组型配置(同 buddyWorkspaceMemoryDirs)。空串 → 空数组 = 关闭该机制。
363
+ section[field] = text.split(",").map((s) => s.trim()).filter(Boolean);
329
364
  } else {
330
365
  if (text !== "") section[field] = text;
331
366
  }
@@ -334,6 +369,8 @@ window.__ModuleLoader__.load({
334
369
  // 保存成功后同步 remote(真实返回值),保留当前 draft(= 用户保存的目标值)。
335
370
  setRemote({ value: full.value, user: full.user, revision: full.revision, loaded: true });
336
371
  setDirty(false);
372
+ // 保存完成 = 这一轮编辑动作结束 → 收起全部卡片回到总览态(对齐宿主 PluginCard 行为)。
373
+ setOpenCards({});
337
374
  } catch (e) {
338
375
  setFailed(true);
339
376
  } finally {
@@ -423,19 +460,68 @@ window.__ModuleLoader__.load({
423
460
  borderTop: "1px solid var(--dsw-alias-border-l2, #e5e7eb)"
424
461
  };
425
462
 
463
+ // ---- v1.7.1(特性2):折叠卡片样式 —— 逐值照抄宿主 ui-settings-plugins 的 PluginCard.module.css ----
464
+ // 竖向「name 叠在 description 上」的卡片宿主无可复用组件(它导出的 DisclosureRow 是横向 24px
465
+ // 紧凑行,布局不同,宿主 README 亦明确区分二者),故手写;chevron 用 data URI 内联 SVG
466
+ // (本项目 client 只能 require("react"),不引宿主图标包)。
426
467
  const cardStyle = {
427
- border: "1px solid var(--dsw-alias-border-l2, #e5e7eb)",
428
- borderRadius: "12px",
429
- padding: "14px 16px",
468
+ border: "0.5px solid var(--dsw-alias-border-l4, #e5e7eb)",
469
+ // ⚠️ 必须显式写 borderColor:展开/收起靠 React diff 增删 cardOpenStyle 的 borderColor。
470
+ // 若只依赖 shorthand 的颜色,open 态写入的 borderColor 被移除后,CSSOM 中 border-color
471
+ // 声明随之删除 → 回退 UA 初始值 currentColor(文字色,近黑)→ 收起后边框变黑(真机 bug)。
472
+ borderColor: "var(--dsw-alias-border-l4, #e5e7eb)",
473
+ borderRadius: "16px",
430
474
  marginBottom: "12px",
431
- background: "var(--dsw-alias-bg-layer-2, #ffffff)"
475
+ background: "var(--dsw-alias-bg-layer-3, #fafafa)",
476
+ overflow: "hidden"
432
477
  };
433
- const groupTitleStyle = {
434
- margin: "0 0 4px",
435
- fontSize: "13px",
436
- fontWeight: "500",
478
+ const cardOpenStyle = {
479
+ ...cardStyle,
480
+ background: "var(--dsw-alias-bg-layer-2, #ffffff)",
481
+ borderColor: "var(--dsw-alias-label-dimmed, #c9ced6)"
482
+ };
483
+ const cardHeaderStyle = {
484
+ display: "flex",
485
+ alignItems: "center",
486
+ gap: "12px",
487
+ width: "100%",
488
+ padding: "14px 16px",
489
+ appearance: "none",
490
+ WebkitAppearance: "none",
491
+ border: "0",
492
+ background: "none",
493
+ font: "inherit",
494
+ textAlign: "left",
495
+ cursor: "pointer"
496
+ };
497
+ const cardHeadTextStyle = { flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: "4px" };
498
+ const cardNameStyle = {
499
+ fontSize: "15px",
500
+ fontWeight: "600",
501
+ lineHeight: "1.4",
437
502
  color: "var(--dsw-alias-label-primary, #1f2329)"
438
503
  };
504
+ const cardDescStyle = {
505
+ fontSize: "13px",
506
+ lineHeight: "1.5",
507
+ color: "var(--dsw-alias-label-tertiary, #8a919f)"
508
+ };
509
+ const cardBodyStyle = {
510
+ borderTop: "0.5px solid var(--dsw-alias-border-l2, #e5e7eb)",
511
+ margin: "0 16px",
512
+ paddingBottom: "8px"
513
+ };
514
+ const chevronStyle = {
515
+ flexShrink: 0,
516
+ width: "14px",
517
+ height: "14px",
518
+ backgroundImage:
519
+ "url(data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 14 14' fill='none'%3E%3Cpath d='M3.5 5.25L7 8.75L10.5 5.25' stroke='%2381858C' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E)",
520
+ backgroundRepeat: "no-repeat",
521
+ backgroundPosition: "center",
522
+ backgroundSize: "14px 14px",
523
+ transition: "transform .16s"
524
+ };
439
525
  const sectionStyle = {
440
526
  maxWidth: "760px",
441
527
  color: "var(--dsw-alias-label-primary, #1f2329)",
@@ -503,18 +589,45 @@ window.__ModuleLoader__.load({
503
589
  const hintStyle = { color: "var(--dsw-alias-label-tertiary, #8a919f)", margin: 0, fontSize: "12px", lineHeight: "1.5" };
504
590
  const errStyle = { color: "var(--dsw-alias-label-error, #d54941)", margin: 0, fontSize: "12px", lineHeight: "1.5" };
505
591
 
592
+ const toggleCard = (key) => setOpenCards((o) => ({ ...o, [key]: !o[key] }));
593
+ // 折叠卡片:header 自身是 button(整行可点 + aria-expanded + aria-label),body 仅在展开时渲染。
594
+ const card = (key, title, desc, children) =>
595
+ h("div", { style: openCards[key] ? cardOpenStyle : cardStyle }, [
596
+ h("button", {
597
+ type: "button",
598
+ className: "mp-card-header",
599
+ "aria-expanded": openCards[key] ? "true" : "false",
600
+ "aria-label": `${t(openCards[key] ? "collapse" : "expand")}: ${title}`,
601
+ style: cardHeaderStyle,
602
+ onClick: () => toggleCard(key)
603
+ }, [
604
+ h("span", { style: cardHeadTextStyle }, [
605
+ h("span", { style: cardNameStyle }, title),
606
+ h("span", { style: cardDescStyle }, desc)
607
+ ]),
608
+ h("span", { style: openCards[key] ? { ...chevronStyle, transform: "rotate(180deg)" } : chevronStyle })
609
+ ]),
610
+ openCards[key] ? h("div", { className: "mp-card-body", style: cardBodyStyle }, children) : null
611
+ ]);
612
+
506
613
  const num = (field) => ({
507
614
  type: "text",
508
615
  inputMode: "numeric",
509
616
  value: draft[field],
510
617
  disabled,
511
- style: { ...inputStyle, borderColor: validation === field ? "var(--dsw-alias-label-error, #d54941)" : undefined },
618
+ style: { ...inputStyle, borderColor: validation === field ? "var(--dsw-alias-label-error, #d54941)" : "var(--dsw-alias-border-l2, #e5e7eb)" },
512
619
  onChange: (e) => edit(field, e.target.value)
513
620
  });
514
621
 
515
622
  return h("div", { className: "memory-palace-settings", style: sectionStyle }, [
516
623
  // 强制覆盖宿主 Webview 全局样式对原生 checkbox 尺寸的覆盖(内联 style 可能不敌全局 CSS)。
517
- h("style", null, ".memory-palace-settings input[type=checkbox]{width:18px!important;height:18px!important;margin:0;flex-shrink:0!important;cursor:pointer;}"),
624
+ h("style", null,
625
+ ".memory-palace-settings input[type=checkbox]{width:18px!important;height:18px!important;margin:0;flex-shrink:0!important;cursor:pointer;}" +
626
+ // v1.7.1(特性2):展开区首条元素自带 borderTop(row/toggle 共用该样式),会与
627
+ // .mp-card-body 的 border-top 叠成双线 → 去掉首条的边框与上内边距。
628
+ ".memory-palace-settings .mp-card-body > *:first-child{border-top:0!important;padding-top:0!important;}" +
629
+ ".memory-palace-settings .mp-card-header:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4b5bff);outline-offset:-2px;border-radius:16px;}"
630
+ ),
518
631
  h("div", { style: { display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: "12px" } }, [
519
632
  h("div", null, [
520
633
  h("h3", { style: headingStyle }, t("title")),
@@ -526,8 +639,7 @@ window.__ModuleLoader__.load({
526
639
  ])
527
640
  ]),
528
641
  failed ? h("p", { style: errStyle }, t("saveFailed")) : null,
529
- h("div", { style: cardStyle }, [
530
- h("p", { style: groupTitleStyle }, t("core")),
642
+ card("core", t("core"), t("coreDesc"), [
531
643
  h("div", { style: toggleStyle }, [
532
644
  h("div", { style: { flexShrink: 1, minWidth: 0 } }, [
533
645
  h("p", { style: { ...labelStyle, margin: 0 } }, t("bridgeLabel")),
@@ -546,10 +658,40 @@ window.__ModuleLoader__.load({
546
658
  ...num("buddyWorkspaceMemoryDirs"),
547
659
  type: "text",
548
660
  placeholder: ".workbuddy/memory, .codebuddy/memory"
549
- }), "buddyWorkspaceMemoryDirs")
661
+ }), "buddyWorkspaceMemoryDirs"),
662
+ // v1.7.2:静默预设(极简模式等)。命中后本插件在该会话整体隐身(提示词/投影/工具/写入/子代理)。
663
+ // 用普通文本输入(非 num —— 这里填的是预设 id 列表,不是数字)。
664
+ row(t("silentPresetsLabel"), t("silentPresetsHint"),
665
+ h("input", {
666
+ type: "text",
667
+ value: draft.silentPresets,
668
+ disabled,
669
+ style: { ...inputStyle, borderColor: "var(--dsw-alias-border-l2, #e5e7eb)" },
670
+ placeholder: "minimal",
671
+ onChange: (e) => edit("silentPresets", e.target.value)
672
+ }), "silentPresets")
673
+ ]),
674
+ // v1.7.1(特性3):自定义指令。非空时经 system prompt 追加到「记忆分工说明」之后;
675
+ // 它是恒定内容(用户配置一次不变),故放 section 而非 E 投影 —— 零缓存成本。
676
+ card("custom", t("custom"), t("customDesc"), [
677
+ row(t("customLabel"), t("customHint"),
678
+ h("textarea", {
679
+ value: draft.customInstructions,
680
+ disabled,
681
+ rows: 6,
682
+ placeholder: t("customPlaceholder"),
683
+ style: {
684
+ ...inputStyle,
685
+ height: "auto",
686
+ minHeight: "120px",
687
+ padding: "10px 12px",
688
+ lineHeight: "1.6",
689
+ resize: "vertical"
690
+ },
691
+ onChange: (e) => edit("customInstructions", e.target.value)
692
+ }), "customInstructions")
550
693
  ]),
551
- h("div", { style: cardStyle }, [
552
- h("p", { style: groupTitleStyle }, t("smartSummary")),
694
+ card("smartSummary", t("smartSummary"), t("smartSummaryDesc"), [
553
695
  // 轮次结束自动记录(summarize):三种记忆模式的共用总闸门,始终显示,置于记忆模式之上、不随模式切换隐藏。
554
696
  toggle(t("summarizeLabel"), t("summarizeHint"), "summarize"),
555
697
  row(t("memoryModeLabel"),
@@ -599,16 +741,14 @@ window.__ModuleLoader__.load({
599
741
  row(t("projectMaxTokensLabel"), t("projectMaxTokensHint"), h("input", num("projectMaxTokens")), "projectMaxTokens")
600
742
  ])
601
743
  ]),
602
- h("div", { style: cardStyle }, [
603
- h("p", { style: groupTitleStyle }, t("storage")),
744
+ card("storage", t("storage"), t("storageDesc"), [
604
745
  row(t("userPathLabel"), t("userPathHint"), h("input", { ...num("userMemoryPath"), type: "text" }), "userMemoryPath"),
605
746
  row(t("wsDirLabel"), t("wsDirHint"), h("input", { ...num("workspaceMemoryDir"), type: "text" }), "workspaceMemoryDir"),
606
747
  row(t("retentionLabel"), draft.memoryMode === "hybrid" ? t("retentionHintHybrid") : t("retentionHint"), h("input", num("dailyLogRetentionDays")), "dailyLogRetentionDays"),
607
748
  row(t("userBudgetLabel"), t("userBudgetHint"), h("input", num("userBudgetChars")), "userBudgetChars"),
608
749
  row(t("wsBudgetLabel"), t("wsBudgetHint"), h("input", num("workspaceBudgetChars")), "workspaceBudgetChars")
609
750
  ]),
610
- h("div", { style: cardStyle }, [
611
- h("p", { style: groupTitleStyle }, t("dev")),
751
+ card("dev", t("dev"), t("devDesc"), [
612
752
  row(t("distillTimeoutLabel"), t("distillTimeoutHint"), h("input", num("summaryTimeoutMs")), "summaryTimeoutMs"),
613
753
  toggle(t("distillDebugLogLabel"), t("distillDebugLogHint"), "distillDebugLog")
614
754
  ])
@@ -3,7 +3,7 @@
3
3
  import { mkdir, readdir, unlink, readFile, writeFile } from "node:fs/promises";
4
4
  import { readFileSync } from "node:fs";
5
5
  import { join, dirname } from "node:path";
6
- import { todayISO, expandHome, readMdSync, toHomeShort, normLine, isStructural, stripSmartTag } from "./text.mjs";
6
+ import { todayISO, expandHome, normLine, isStructural, stripSmartTag } from "./text.mjs";
7
7
 
8
8
  // 追加一行记忆,若目标文件已包含相同内容则跳过(去重),返回是否实际写入。
9
9
  export async function appendLineDedup(file, line) {
@@ -237,30 +237,6 @@ export function createRecords({ getConfig, paths }) {
237
237
  }
238
238
  }
239
239
 
240
- // 读取目录里最近的(非今日)每日日志,拼成一段供 memory_read 展示(最多 3 份)。
241
- async function recentLogs(dir) {
242
- let files = [];
243
- try {
244
- files = await readdir(dir);
245
- } catch {
246
- return "";
247
- }
248
- const today = todayISO();
249
- const dated = files
250
- .map((f) => /^(\d{4}-\d{2}-\d{2})\.md$/.exec(f))
251
- .filter((m) => m && m[1] < today)
252
- .map((m) => m[1])
253
- .sort()
254
- .reverse()
255
- .slice(0, 3);
256
- const parts = [];
257
- for (const date of dated) {
258
- const text = readMdSync(join(dir, `${date}.md`));
259
- if (text) parts.push(`# 日志 ${date} @ ${toHomeShort(dir)}\n${text.slice(0, cfg().workspaceBudgetChars)}`);
260
- }
261
- return parts.join("\n\n");
262
- }
263
-
264
240
  // 轻量结构化条目(无 LLM):截断原始文本,错误带 [ERROR] 前缀。
265
241
  async function writeLightEntry(dirs, turn, isError) {
266
242
  const userText = turn.find((b) => b.role === "user")?.text ?? "";
@@ -289,5 +265,7 @@ export function createRecords({ getConfig, paths }) {
289
265
  }
290
266
  }
291
267
 
292
- return { appendDaily, prune, recentLogs, writeLightEntry, captureError };
268
+ // v1.7.1:recentLogs 已删除 —— memory_read 的 scope='daily' 改为按日期(isoDaysAgo)直读,
269
+ // 不再需要"最近 N 份文件"语义(跨日跳空会取偏)。
270
+ return { appendDaily, prune, writeLightEntry, captureError };
293
271
  }
@@ -14,6 +14,16 @@ export const todayISO = () => {
14
14
  return `${d.getFullYear()}-${m}-${day}`;
15
15
  };
16
16
 
17
+ // 本地日期偏移(0=今天,1=昨天,2=前天…),供 memory_read 按**日期**取日志
18
+ // (而不是"最近 N 份文件"——跨日跳空时会取偏)。同 todayISO 的教训:必须本地时间。
19
+ export const isoDaysAgo = (n = 0) => {
20
+ const d = new Date();
21
+ d.setDate(d.getDate() - n);
22
+ const m = String(d.getMonth() + 1).padStart(2, "0");
23
+ const day = String(d.getDate()).padStart(2, "0");
24
+ return `${d.getFullYear()}-${m}-${day}`;
25
+ };
26
+
17
27
  // 本地时间戳(YYYY-MM-DDTHH-mm-ss,`:` 换 `-` 兼容 Windows 文件名)。
18
28
  // 同 todayISO 的教训:必须用本地时间,不能用 toISOString()(UTC 会差 8 小时)。
19
29
  // 供项目记忆蒸馏备份文件名(MEMORY.md.{时间戳})使用。
@@ -232,7 +232,7 @@ export function registerHybridTools({ ctx, getConfig, paths, records, state }) {
232
232
  "(workspaceBudgetChars); (2) at least reorgCooldownDays (default 7) since the last reorganize. " +
233
233
  "If either gate fails the call is REJECTED — use memory_update_section instead. " +
234
234
  "Requirements for newContent: keep the full `## 章节` + `- 条目` format; NEVER lose still-valid key " +
235
- "information — read the daily logs (memory_read) and current MEMORY.md for cross-checking first; " +
235
+ "information — read the daily logs and current MEMORY.md for cross-checking first (memory_read with scope 'all'); " +
236
236
  "merge duplicates, drop only strikethrough/obsolete content; keep user-level MEMORY.md untouched " +
237
237
  "(user-level reorganization is FORBIDDEN). A last-reorg timestamp comment is appended automatically. " +
238
238
  "A user confirmation dialog is shown before execution.",
package/lib/index.js CHANGED
@@ -22,11 +22,10 @@
22
22
  // - src/index.mjs:最薄入口——apply() 装配 + 闭包运行时(session/event 跟踪、settle 时序、section 注入)
23
23
  // - src/client/(00-head…90-tail):浏览器 bundle 源码(build 时零依赖拼接为 lib/client.js 单文件,
24
24
  // 硬约束——dsh 客户端模块系统不支持插件相对 require)
25
- import { join } from "node:path";
26
25
  import Schema from "@deepseek-ai/schemastery";
27
26
  // v1.6.0-rc1:适配 DSH 0.1.2-alpha.2——dsh-settings 不再导出自由函数 installSettingsSection /
28
27
  // settingsNamespace,设置节注册改用 SettingsProvider 实例方法 installSection(经 ctx.inject(["settings"]))。
29
- import { todayISO, toHomeShort, readMdSync, budgetClip, stripSmartTag, stripDeletedLines, extractText, extractToolErrorText } from "./common/text.mjs";
28
+ import { extractText, extractToolErrorText } from "./common/text.mjs";
30
29
  import { SCENE_KEYWORDS } from "./common/prompts.mjs";
31
30
  import { createPaths } from "./common/paths.mjs";
32
31
  import { createRecords } from "./common/records.mjs";
@@ -43,6 +42,11 @@ const MEMORY_PALACE_SETTINGS_NAMESPACE = "memory-palace";
43
42
 
44
43
  export const Config = Schema.object({
45
44
  enabled: Schema.boolean().default(true).description("启用 memory-palace 记忆注入与每日日志写入。"),
45
+ // ---- v1.7.2:预设级静默(官方 minimal「裸测环境」口径)----
46
+ // 宿主把「模式」实现为 agent 平面的 preset:minimal 预设用 persona complete:true 独占 system prompt。
47
+ // 但本插件注册在 host 平面(profile bundle 的 insert),各通道对**每个 agent** 都生效,preset 并不会
48
+ // 把它摘掉——故须自行按会话判据静默,否则记忆正文仍会经 E 投影进历史(实测症状)。
49
+ silentPresets: Schema.array(Schema.string()).default(["minimal"]).description("在这些 agent 预设下本插件整体静默(等价 enabled=false):不注入系统提示词与投影、记忆工具对模型隐身、不写日志、不跑记忆子代理。默认 [\"minimal\"](官方极简模式);置空数组 = 关闭该机制。判据取会话创建头 agentPreset 与 agent-preset/selected 事件(宿主公开事实)。"),
46
50
  userMemoryPath: Schema.string().default("~/.deepseek-harness/MEMORY.md").description("用户级记忆文件路径(支持 ~ 展开)。"),
47
51
  workspaceMemoryDir: Schema.string().default(".deepseek-harness/memory").description("无 buddy 目录时使用的项目级每日日志目录;项目级 MEMORY.md 位于其同级(.deepseek-harness/MEMORY.md)。"),
48
52
  dailyLogRetentionDays: Schema.number().default(30).description("每日日志保留天数,过期日志会被蒸馏进 MEMORY.md。"),
@@ -61,7 +65,7 @@ export const Config = Schema.object({
61
65
  summaryTimeoutMs: Schema.number().default(60000).description("蒸馏 LLM 调用的超时(毫秒),超时视为失败并降级;覆盖智能模式摘要与手动蒸馏两条链路;默认 60000(60s)。"),
62
66
  distillDebugLog: Schema.boolean().default(false).description("调试开关:向 dsh 服务端 stderr 输出蒸馏 LLM 调用诊断。distillLogLevel=info 时仅输出元数据(模型解析/请求参数/流进度/错误详情,不含文本);distillLogLevel=debug 会额外打印 LLM 原始响应文本(分隔符包裹),仅限受信本地排障开启。"),
63
67
  // ---- v1.4.1:蒸馏 stderr 日志级别(平铺键,不进 UI;默认 info;distillDebugLog=true 时生效) ----
64
- distillLogLevel: Schema.string().default("info").description("蒸馏 stderr 日志级别:info=仅元数据诊断(默认,不打印 LLM 原始响应);debug=额外打印 LLM 原始响应文本(分隔符包裹),仅限受信本地排障开启。无需 UI 配置,经 profile/settings.yaml 设置 distillLogLevel 键。"),
68
+ distillLogLevel: Schema.string().default("info").description("蒸馏 stderr 日志级别:info=仅元数据诊断(默认,不打印 LLM 原始响应);debug=额外打印 LLM 原始响应文本(分隔符包裹),仅限受信本地排障开启。无需 UI 配置,经 DSH home($DSH_HOME)根目录的 settings.yaml 设置 distillLogLevel 键。"),
65
69
  // ---- v1.4.0:智能模式最终输出软预算(v1.4.1 起语义变更:prompt 软约束,思考不受限;实际硬上限由模型自身 maxTokens 决定) ----
66
70
  summaryMaxTokens: Schema.number().default(2000).description("会话摘要 LLM 的最终输出软预算(prompt 约束,思考不受限;实际硬上限由模型自身 maxTokens 决定)。默认 2000;可调大以容纳更多 durable 事实。"),
67
71
  projectMaxTokens: Schema.number().default(8000).description("手动「蒸馏项目记忆」LLM 的最终输出软预算(prompt 约束,思考不受限;实际硬上限由模型自身 maxTokens 决定)。默认 8000。"),
@@ -70,6 +74,9 @@ export const Config = Schema.object({
70
74
  // ---- v1.6.0:hybrid 模式配置(仅 memoryMode=hybrid 时生效) ----
71
75
  reorgCooldownDays: Schema.number().default(7).description("hybrid 模式:项目级 MEMORY.md 全量重整的冷却天数(距上次重整)。与「超出注入预算」双条件同时满足才允许 memory_reorganize;时间戳以 HTML 注释落在 MEMORY.md 文件尾。"),
72
76
  subagentLogBudget: Schema.number().default(20000).description("hybrid 模式:记忆子代理回喂今日工作日志的字符上限。超出时仅回喂章节目录,子代理用 log_read_section 按需读取章节。"),
77
+ // ---- v1.7.1(特性3):自定义指令(用户自写,经 system prompt 注入到「记忆分工 prompt」之后) ----
78
+ // 放 system 而非 E 投影:用户配置一次即恒定 → 零缓存成本(见下方 section 的分流原则)。
79
+ customInstructions: Schema.string().default("").description("自定义指令:非空时追加到系统提示词「记忆分工说明」之后,用于承载不适合写进用户记忆的特殊指令。对全部会话与三种记忆模式生效;留空则不注入。"),
73
80
  });
74
81
 
75
82
  export const inject = ["systemPrompt", "tools", "llm", "webServer", "webRuntime"];
@@ -126,6 +133,9 @@ export function apply(ctx, config) {
126
133
  lastSummarizedSeq: -1, // 智能模式增量摘要断点(session 事件 seq)
127
134
  summarySessionId: null,
128
135
  planModeActive: false, // 计划模式:禁写记忆(硬编码默认,无开关;仅经 session/event 的 plan/mode 翻转;未装 dsh-plan-mode 永不触发=不拦截)
136
+ // v1.7.2:会话 → agent 预设 id(仅"切换预设"事件写入;创建头另在 presetOfSession 里兜底读)。
137
+ // 只增不减:会话结束后残留几条字符串,代价可忽略;切回同一 session 断言预设不变(宿主侧保证)。
138
+ presetBySession: new Map(),
129
139
  // v1.7.0:injectedSessionIds 已删除——记忆正文改经 E 投影(src/projection.mjs)注入为
130
140
  // 常驻消息,compaction 后由投影自动重注,不再需要"仅首次注入"的会话级标记。
131
141
  };
@@ -135,11 +145,50 @@ export function apply(ctx, config) {
135
145
  const TURN_BUFFER_CHAR_CAP = 30000;
136
146
  const SETTLE_DELAY = 1500;
137
147
 
148
+ // ---------- v1.7.2:预设级静默判据(官方 minimal = 宿主给模型的"裸测环境") ----------
149
+ // 背景:宿主的「模式」= agent 平面的 preset(`packages/preset/agent-presets/presets/*/agent.cordis.yml`),
150
+ // minimal 预设以 persona `complete: true` 独占 system prompt 并关掉 runtime context——那是官方跑分口径
151
+ // 的刻意设计。而本插件是 host 平面插件(profile bundle insert),其 systemPrompt.section / agent/pre-step
152
+ // 投影 / 工具注册对**每个 agent** 都生效,preset 不会把它摘掉;`complete` 又只吞 sections、不裁 tools。
153
+ // 结果就是"指令没了、记忆正文照进、工具 schema 照发"的半残状态(实测:极简模式下投影仍在注入)。
154
+ // 因此必须自行判定会话预设并整体静默。
155
+ //
156
+ // 判据取宿主公开事实,不引入额外服务依赖:
157
+ // ① session.header.agentPreset —— 创建头,由 session-controller 的 composeAgent 写入**解析后**的
158
+ // 预设 id(未显式指定时即部署默认),故默认预设会话同样能识别;
159
+ // ② `agent-preset/selected` 事件 —— 仅"尚未产生任何消息"的空会话可切预设,切换时追加,
160
+ // 由下方 session/event 监听捕获。
161
+ // 二者合起来等价于宿主的 `agentPreset` 会话投影(init=header,apply=该事件),无需注入 sessionProjections。
162
+ // fail-open:判据缺失(老宿主 / 非 preset 部署)一律视为"不静默",绝不因判据缺失而丢掉记忆能力。
163
+ function presetOfSession(session) {
164
+ if (!session) return undefined;
165
+ const switched = state.presetBySession.get(session.id);
166
+ if (typeof switched === "string" && switched) return switched;
167
+ const header = session.header?.agentPreset;
168
+ return typeof header === "string" && header ? header : undefined;
169
+ }
170
+
171
+ /**
172
+ * 该会话是否应整体静默:`enabled=false`(全局停用)或命中「静默预设」名单。
173
+ * 命中后 section / E 投影 / turn-end 写入 / 记忆工具 / hybrid 子代理一并关闭——
174
+ * 语义等价于该会话里没装本插件。
175
+ * @param {object|undefined} session
176
+ * @returns {boolean}
177
+ */
178
+ function isSessionSilent(session) {
179
+ const cfg = source();
180
+ if (!cfg.enabled) return true;
181
+ const list = Array.isArray(cfg.silentPresets) ? cfg.silentPresets.filter((x) => typeof x === "string" && x) : [];
182
+ if (!list.length) return false; // 名单空 = 关闭该机制(只受 enabled 管)
183
+ const preset = presetOfSession(session);
184
+ return preset !== undefined && list.includes(preset);
185
+ }
186
+
138
187
  // ---- 装配:路径解析 / 记录读写 / 蒸馏 / 工具 / route ----
139
188
  const paths = createPaths(() => source(), () => state.activeCwd);
140
189
  const records = createRecords({ getConfig: () => source(), paths });
141
190
  const distill = createDistill({ ctx, getConfig: () => source(), paths, records, state });
142
- registerTools({ ctx, getConfig: () => source(), paths, records, state });
191
+ registerTools({ ctx, getConfig: () => source(), paths, state });
143
192
  registerApi({ ctx, paths, distill, state, getSettingsFace });
144
193
  // v1.6.0:hybrid 模式独立模块。必须【无条件注册】——apply() 同步段执行时 settings 服务
145
194
  // 尚未挂载(v1.6.0-rc1 起设置节经 SettingsProvider.installSection 在 ctx.inject(["settings"])
@@ -150,8 +199,75 @@ export function apply(ctx, config) {
150
199
  // 的 prompt 不引导使用,guards 白名单只拦 hybrid 工具)。
151
200
  const hybrid = registerHybrid({ ctx, getConfig: () => source(), paths, records, state });
152
201
  // v1.7.0 特性1:E 投影通道(记忆正文常驻注入)。与 hybrid 同理,无条件注册——
153
- // 其内部读热配置,无副作用(enabled=false 时 buildProjections 返回空)。
154
- registerProjection({ ctx, getConfig: () => source(), paths });
202
+ // 其内部读热配置,无副作用(enabled=false 或命中静默预设时 buildProjections 返回空)。
203
+ // v1.7.2:把 isSessionSilent 透传下去——投影按**会话**判定,故必须知道 agent 所属会话的预设。
204
+ registerProjection({ ctx, getConfig: () => source(), paths, isSilent: isSessionSilent });
205
+
206
+ // ---------- v1.7.2:静默会话(enabled=false 或命中静默预设)的工具 schema 隐身 ----------
207
+ // 背景:`complete: true` 只收缩 sections、**不裁剪 tools**——记忆工具的 schema 仍会经 toolProvider
208
+ // 进 assemble,在"裸测环境"里白吃 token 且可能被模型幻觉调用。故静默会话需显式隐身工具。
209
+ // 机制约束:① enabled / silentPresets 都是热配置,apply() 同步段读不到 → 不能条件注册(否则切回后
210
+ // 工具从未注册,同 v1.6.0 hybrid 踩坑);② tools.restrict() 要求 agent 作用域 ctx、静态名单、
211
+ // dispose 才解除;③ 宿主无"当前是哪个 preset"的装配期 API,但 agent/created 时 session 创建头已带
212
+ // agentPreset(composeAgent 写入解析后的 id),故此处判定可靠。
213
+ // 落法:挂 agent/created 建立掩码,并在**空会话切换预设**时同步(宿主允许"尚未产生任何消息"的会话
214
+ // 改预设;此时模型还没看过任何东西,掩码必须跟着变,否则切到极简后工具仍暴露)。
215
+ // 语义与 model selection 一致(能力集在 agent 装配前冻结):运行中热切 enabled / silentPresets
216
+ // 仅影响后续新建 agent,当前 agent 不变——可接受(execute 内已有 enabled 兜底,即便残留 schema 被调
217
+ // 也返回 disabled)。
218
+ // deny 名单含 4 基础工具 + 3 hybrid 工具;log_read_section / log_write_ops 是子 agent 内部工具
219
+ // (经 ctx.llm.stream 的 tools 参数、不入全局层),列进 deny 会触发 unknown-tool 抛错,故不含。
220
+ const MEMORY_TOOL_NAMES = [
221
+ "memory_note",
222
+ "memory_note_user",
223
+ "memory_read",
224
+ "memory_delete",
225
+ "memory_write",
226
+ "memory_update_section",
227
+ "memory_reorganize",
228
+ ];
229
+ // sessionId → agent(仅用于切换预设时重新同步掩码;agent/disposed 时清理,避免长跑进程里越积越多)
230
+ const agentBySession = new Map();
231
+ // sessionId → restrict() 的解除函数(掩码是否已戴,靠它判断 + 反向解除)
232
+ const toolMaskBySession = new Map();
233
+
234
+ /** 按会话当前预设同步工具掩码:静默→戴上(deny 全部记忆工具),非静默→摘下。幂等。 */
235
+ function syncToolMask(agent) {
236
+ const sessionId = agent?.session?.id;
237
+ if (!sessionId) return;
238
+ const masked = toolMaskBySession.has(sessionId);
239
+ const silent = isSessionSilent(agent?.session);
240
+ if (silent === masked) return;
241
+ try {
242
+ if (silent) {
243
+ const release = agent?.ctx?.tools?.restrict({ deny: MEMORY_TOOL_NAMES });
244
+ if (typeof release === "function") toolMaskBySession.set(sessionId, release);
245
+ } else {
246
+ toolMaskBySession.get(sessionId)?.();
247
+ toolMaskBySession.delete(sessionId);
248
+ }
249
+ } catch (error) {
250
+ // 绝不冒泡:restrict 抛错(如某工具因异常未注册命中 unknown-tool)时降级为"不隐身",
251
+ // 由 execute 的 enabled 兜底保证功能仍停用,只是没省掉 schema token。
252
+ console.error(`[memory-palace] tool-hide skipped: ${error?.message || String(error)}`);
253
+ }
254
+ }
255
+
256
+ ctx.on("agent/created", ({ agent }) => {
257
+ if (agent?.session?.id) agentBySession.set(agent.session.id, agent);
258
+ syncToolMask(agent);
259
+ });
260
+ ctx.on("agent/disposed", ({ agent }) => {
261
+ const sessionId = agent?.session?.id;
262
+ if (!sessionId) return;
263
+ try {
264
+ toolMaskBySession.get(sessionId)?.();
265
+ } catch {
266
+ /* scope 已在卸载,忽略 */
267
+ }
268
+ toolMaskBySession.delete(sessionId);
269
+ agentBySession.delete(sessionId);
270
+ });
155
271
 
156
272
  // ---- session/event 跟踪:更新 activeCwd/activeSession/增量断点 + 累积 turnBuffer ----
157
273
  // 关键:一次用户请求在 dsh agent 循环里会被拆成多个 turn(每个工具调用一轮),
@@ -167,6 +283,16 @@ export function apply(ctx, config) {
167
283
  state.lastSummarizedSeq = session.firstLiveSeq;
168
284
  }
169
285
  const type = event?.type;
286
+ // v1.7.2:预设切换(仅空会话可切;宿主在切换提交后追加该事件)。记进 Map 供 isSessionSilent 读取。
287
+ if (type === "agent-preset/selected") {
288
+ const id = event?.data?.agentPreset;
289
+ if (session?.id && typeof id === "string" && id) state.presetBySession.set(session.id, id);
290
+ // 掩码跟随:会话切进/切出静默预设时立即戴上或摘下(此时模型尚未看过任何内容,
291
+ // 不做这一步会出现"切到极简、工具 schema 仍暴露"的漏网)。
292
+ const owner = session?.id ? agentBySession.get(session.id) : undefined;
293
+ if (owner) syncToolMask(owner);
294
+ return;
295
+ }
170
296
  // 计划模式:禁写记忆(硬编码默认行为,无开关;不依赖 dsh-plan-mode 服务,未装则永不触发=安全降级=不拦截)
171
297
  if (type === "plan/mode") {
172
298
  state.planModeActive = !!(event?.data?.active);
@@ -212,24 +338,24 @@ export function apply(ctx, config) {
212
338
  });
213
339
 
214
340
  // ---------- 读取:同步 section text(systemPrompt 要求同步) ----------
215
- // v1.7.0:section 只保留「常量指令(intro)+ 今日工作日志」。
216
- // 用户级 / 项目级 MEMORY.md 已移出 section,改由 E 投影(src/projection.mjs)承载为
217
- // 常驻消息(每个 step 可见)。分流依据是「变化频率」:MEMORY.md 低频 durable → 投影;
218
- // 今日日志高频易变 → 留 section 每步注入(不进历史以免膨胀)。
341
+ // v1.7.1:section **只保留恒定内容**(intro 指令 + 记忆分工说明 + planNote),
342
+ // 今日工作日志已迁入 E 投影(src/projection.mjs)。
343
+ // 分流依据是「内容是否恒定」:恒定 → 留 section(system prompt 在序列最前,内容恒定则
344
+ // 前缀缓存永久有效);易变 → 走 E 投影追加到历史尾部,且按文件身份只注一次。
345
+ // ⚠️ 切勿把任何「每步可能变化」的内容放回本 section —— 变一次就会让其后整段前缀作废。
346
+ // 实测代价:9 次全量重算、命中率从 99.26% 掉到 94.53%(见 testdata/session.v3.jsonl)。
219
347
  ctx.systemPrompt.section({
220
348
  name: "memory-palace",
221
349
  order: 50,
222
- text: () => {
350
+ // v1.7.2:text 接收宿主 AssembleContext(`{ agent, scope, signal }`,见 agent 包 assembleContextFor),
351
+ // 故可按**会话**判定预设静默 —— 与投影/工具/写入同一判据,避免"half-injected"状态。
352
+ text: (context) => {
223
353
  const cfg = source();
224
354
  if (!cfg.enabled) return "";
225
- const blocks = [];
226
- // 今日工作日志:每 step 注入,预算 workspaceBudgetChars(与项目 MEMORY.md 同字段,
227
- // 但各自独立 budgetClip 截断,互不挤占)。v1.4.1 的 budgetClip 已是"结构行 + 尾部最新"。
228
- for (const dir of paths.readDirs()) {
229
- const dirShort = toHomeShort(dir);
230
- const t = readMdSync(join(dir, `${todayISO()}.md`));
231
- if (t) blocks.push(`# 今日工作日志 (${todayISO()} @ ${dirShort})\n${stripSmartTag(stripDeletedLines(budgetClip(t, cfg.workspaceBudgetChars)))}`);
232
- }
355
+ // v1.7.2:极简(裸测)预设整体静默。注:minimal 预设的 complete:true 本来也会吞掉本节,
356
+ // 这里显式返回空串是为了① 覆盖"自定义静默预设未用 complete"的情形;② 让本节的去留与其余
357
+ // 通道严格一致,便于排障(不会出现"投影关了、section 还在"的错觉)。
358
+ if (isSessionSilent(context?.agent?.session)) return "";
233
359
  // v1.7.0:alreadyInjected / injectedSessionIds 已整体删除(记忆正文改走 E 投影)。
234
360
  // intro(含记忆公民指令)仍【始终】注入——若因记忆为空而整体返回空串,agent 将不知道
235
361
  // 记忆系统存在、不会主动记,形成「无记忆 → 无指令 → 永不记」死循环。
@@ -241,7 +367,7 @@ export function apply(ctx, config) {
241
367
  // v1.6.0:hybrid=记忆子代理自动维护日志 + agent 主动维护 MEMORY.md(见 HYBRID_PROACTIVE)。
242
368
  const proactive =
243
369
  source().memoryMode === "smart"
244
- ? "\n\n[记忆说明] 你的跨 session 记忆由 LLM 智能摘要自动维护(每轮结束自动提炼摘要并沉淀 durable 事实到 MEMORY.md),无需主动调用 memory_note / memory_note_user;读取全部记忆用 memory_read 工具(不要手动 glob/read 记忆文件)。"
370
+ ? "\n\n[记忆说明] 你的跨 session 记忆由 LLM 智能摘要自动维护(每轮结束自动提炼摘要并沉淀 durable 事实到 MEMORY.md),无需主动调用 memory_note / memory_note_user;读取记忆用 memory_read 工具,scope 默认 'memory',需要日志时显式传 scope(不要手动 glob/read 记忆文件)。"
245
371
  : source().memoryMode === "hybrid"
246
372
  ? HYBRID_PROACTIVE
247
373
  : "\n\n[记忆公民指令] 你拥有跨 session 的 Markdown 记忆。以下场景【必须】主动调用 memory_note(项目级约定)或 memory_note_user(跨项目个人偏好)落档,不要依赖轮次结束的自动兜底——它只做原始文本截断,无法代替你的高质量总结:\n" +
@@ -253,19 +379,25 @@ export function apply(ctx, config) {
253
379
  "判定标准:这条信息「下个 session 的我」还需要吗?不需要(闲聊、一次性操作、显而易见)就不记。格式:一句话结论开头 + 关键细节(命令/路径/数字),不写流水账。";
254
380
  const intro = bridged
255
381
  ? "你拥有持久化、人类可直接编辑的 Markdown 记忆文件。当前项目已存在 WorkBuddy/CodeBuddy 项目记忆目录,本插件直接读写这些目录(不再单独创建 .deepseek-harness/memory/)。" +
256
- "写入记忆:项目级约定用 memory_note 工具,跨项目个人偏好用 memory_note_user 工具;读取全部记忆用 memory_read 工具(不要手动 glob/read 记忆文件)。用它保持跨 session 一致性;看不到的内容不要编造。" +
382
+ "写入记忆:项目级约定用 memory_note 工具,跨项目个人偏好用 memory_note_user 工具;读取记忆用 memory_read 工具,scope 默认 'memory'(用户级 + 项目级 MEMORY.md),需要今日/历史日志时显式传 scope:'daily' 或 'all'(不要手动 glob/read 记忆文件)。用它保持跨 session 一致性;看不到的内容不要编造。" +
383
+ "注意:上下文中的记忆是**会话起始快照**,不随记忆文件之后的更新自动刷新;需要以当前状态为依据时(改记忆前、或据记忆作答前)用 memory_read 重读。" +
257
384
  antiMangle + proactive
258
385
  : "你拥有持久化、人类可直接编辑的 Markdown 记忆文件(位于 ~/.deepseek-harness/MEMORY.md,以及各项目的 .deepseek-harness/MEMORY.md(长期记忆)与 .deepseek-harness/memory/(每日日志))。" +
259
- "写入记忆:项目级约定用 memory_note 工具,跨项目个人偏好用 memory_note_user 工具;读取全部记忆用 memory_read 工具(不要手动 glob/read 记忆文件)。用它保持跨 session 一致性;看不到的内容不要编造。" +
386
+ "写入记忆:项目级约定用 memory_note 工具,跨项目个人偏好用 memory_note_user 工具;读取记忆用 memory_read 工具,scope 默认 'memory'(用户级 + 项目级 MEMORY.md),需要今日/历史日志时显式传 scope:'daily' 或 'all'(不要手动 glob/read 记忆文件)。用它保持跨 session 一致性;看不到的内容不要编造。" +
387
+ "注意:上下文中的记忆是**会话起始快照**,不随记忆文件之后的更新自动刷新;需要以当前状态为依据时(改记忆前、或据记忆作答前)用 memory_read 重读。" +
260
388
  antiMangle + proactive;
261
389
  // 计划模式禁写提示(硬编码默认行为,无开关):无论记忆模式都追加,让 agent 自觉不写(网关物理兜底仍生效)
262
390
  const planNote = state.planModeActive
263
391
  ? "\n\n[plan 模式] 当前处于 plan 模式,不要调用 memory_note / memory_note_user 写入记忆,也不要请求删除记忆(读取记忆用 memory_read,仍可用)。"
264
392
  : "";
265
393
  const introFull = intro + planNote;
266
- // v1.7.0:blocks 仅含今日日志(用户级/项目级 MEMORY.md 已移出,改由 E 投影注入)。
267
- // 返回值永非空串(只含 intro 时亦然),避免 harness 对空 section 的处理歧义。
268
- return blocks.length ? [introFull, ...blocks].join("\n\n") : introFull;
394
+ // v1.7.1(特性3):自定义指令追加在「记忆插件 prompt + 记忆分工 prompt」之后 ——
395
+ // 拼接顺序即 system prompt 里的实际排布(同一 section 内完成,order 不变)。
396
+ // 它由用户在设置页配置,内容恒定 → 放 system 零缓存成本,不违反本节的分流原则。
397
+ const custom = typeof cfg.customInstructions === "string" ? cfg.customInstructions.trim() : "";
398
+ // v1.7.1:本 section 已无任何动态块(日志迁出 E 投影),直接返回常量指令。
399
+ // 返回值仍非空串(即便自定义指令为空也含 intro),避免 harness 对空 section 的处理歧义。
400
+ return custom ? `${introFull}\n\n[用户自定义指令] ${custom}` : introFull;
269
401
  },
270
402
  });
271
403
 
@@ -276,6 +408,9 @@ export function apply(ctx, config) {
276
408
  if (state.planModeActive) return;
277
409
  const cfg = source();
278
410
  if (!cfg.enabled) return;
411
+ // v1.7.2:静默会话(极简等预设)不写任何记忆——错误捕获 / 轻量兜底 / smart 摘要 / hybrid 子代理
412
+ // 全部在此一处提前返回(hybrid 分支在其下方,天然被拦)。
413
+ if (isSessionSilent(state.activeSession)) return;
279
414
  const dirs = paths.writeDirs();
280
415
  if (!dirs.length) return;
281
416
 
@@ -1,28 +1,38 @@
1
- // memory-palace v1.7.0 特性1:E 投影 —— 记忆正文的独立注入通道。
1
+ // memory-palace E 投影 —— 记忆正文与今日日志的独立注入通道。
2
2
  //
3
3
  // 背景(v1.6.3 及以前):用户级 + 项目级 MEMORY.md 走 systemPrompt.section,受
4
4
  // 「仅首次注入」限制(`alreadyInjected` 打了标记就不撕,只有 compaction 清),
5
5
  // 导致记忆正文在 turn 1 的 step 2 之后就消失、全程不再进场。
6
6
  //
7
- // 现在:两份 MEMORY.md 改经 `agent/pre-step` 投影为**独立 user 消息**,常驻对话历史:
7
+ // 现在:记忆正文改经 `agent/pre-step` 投影为**独立 user 消息**,常驻对话历史:
8
8
  // - 每个 step 都可见(消息在历史里,不依赖注入时机);
9
- // - 内容未变只写一次(进历史后后续 step 的 decision.messages 已含它 → 去重命中);
10
- // - compaction 把消息移出 surface 后,后续 step 找不到 → 自动重注(白送)。
9
+ // - v1.7.1 起去重判据由「全文深比较」改为「**文件身份**」(首行 heading,含路径 + 日期):
10
+ // 同一文件只注一次,内容再变也不重注 —— 记忆正文由 agent 自己写入,其内容本就在
11
+ // 上下文(tool/call 参数)里,重注纯属冗余;换文件(跨日期日志)才视为新身份注入;
12
+ // - v1.7.1 起**今日工作日志由 systemPrompt.section 迁入本通道**。日志是 agent 唯一
13
+ // 「不知道自己缺」的内容(hybrid 子代理以独立 LLM stream 写入、不回注主对话),
14
+ // 必须注入;迁出后 section 只剩恒定指令 → system prompt 恒定 → 前缀缓存永久有效
15
+ // (此前日志在 section 里每步求值,一变就让序列最前的整段前缀作废)。
16
+ // - compaction 把消息移出 surface 后,身份判据即判为缺失 → 自动重注**磁盘最新版**,
17
+ // 顺带完成一次「刷新到最新」。
18
+ // - v1.7.2 起**静默会话整体不投影**(isSilent(session)):宿主「模式」是 agent 平面预设,
19
+ // 本插件却在 host 平面,投影对每个 agent 都生效——官方 minimal 预设(persona complete:true
20
+ // 独占 system prompt 的"裸测环境")下必须自行按会话静默,否则记忆正文仍会常驻历史吃 token。
11
21
  //
12
22
  // 实现照抄宿主 `packages/context/agent-instructions/src/index.ts` 三件套(API 全公开、无第一方特权):
13
23
  // 1. `inject: ['sessionProjections']`(服务随 dsh-base 默认装载)
14
24
  // 2. `ctx.on('agent/pre-step', async ({agent, messages, step, signal}, next) => {...})`
15
25
  // 3. `createUserMessage()`(来自 @deepseek-ai/dsh-llm)
16
- // 投递方式:同步版——折叠进 `decision.messages`(`toSpliced(lastClaimedIndex + 1, 0, desired)`),
26
+ // 投递方式:同步版——折叠进 `decision.messages`(`toSpliced(lastClaimedIndex + 1, 0, ...pending)`),
17
27
  // 不做异步 inbox 刷新(agent-instructions 注释明写异步投影有两个 commit 边界的时序约束,
18
28
  // 本版刻意回避;记忆更新后下一步自然带上新内容)。
19
29
  //
20
30
  // 🔴 契约风险:pre-step 监听器抛错会让**整个 turn 失败**(宿主测试
21
31
  // packages/acp/acp/tests/turns.spec.ts:150-156 锚定),故钩子内整体 try-catch,
22
32
  // 任何异常降级为「本步不投影」并留一行 stderr 线索,绝不冒泡。详见 DEVELOPMENT.md §7.4。
23
- import { isDeepStrictEqual } from "node:util";
33
+ import { join } from "node:path";
24
34
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
25
- import { expandHome, toHomeShort, readMdSync, budgetClip, stripSmartTag, stripDeletedLines } from "./common/text.mjs";
35
+ import { expandHome, toHomeShort, todayISO, readMdSync, budgetClip, stripSmartTag, stripDeletedLines } from "./common/text.mjs";
26
36
 
27
37
  // 投影消息的 source 标注。
28
38
  // - kind: 'plugin' → 明确标注"插件注入",供下游按 source 过滤(子 agent 去噪 / turnBuffer 采集)。
@@ -34,20 +44,35 @@ const PROJECTION_SOURCE = Object.freeze({
34
44
  form: "instructions",
35
45
  });
36
46
 
37
- // 同一份内容是否已在这批消息里(逐字段深比较,照抄 agent-instructions 的 sameContextPayload)。
38
- function sameContextPayload(left, right) {
39
- return isDeepStrictEqual(left.content, right.content)
40
- && isDeepStrictEqual(left.source, right.source);
47
+ // v1.7.1 判据:投影身份 = 消息首行 heading(已编码目标文件路径 + 日期)。
48
+ // 只比身份、不比正文 —— 同一文件投影过一次后,内容再变也不重注。
49
+ function projectionIdentity(msg) {
50
+ const text = msg?.content?.[0]?.text ?? "";
51
+ const i = text.indexOf("\n");
52
+ return i === -1 ? text : text.slice(0, i);
41
53
  }
42
54
 
43
- // 扫描当前 surface,判断该 payload 是否已经作为本插件消息存在于会话历史中。
44
- // 存在 → 不重复注入("内容不变只写一次"靠它实现)。
55
+ // 只在双方都是本插件投影时才比身份 —— 规避真实用户消息与宿主注入消息
56
+ // (runtime context / skill 目录等)因首行文本巧合而误撞。
57
+ function isOwnProjection(msg) {
58
+ return msg?.source?.kind === "plugin" && msg?.source?.plugin === "dsh-memory-palace";
59
+ }
60
+
61
+ function sameProjectionIdentity(left, right) {
62
+ return isOwnProjection(left) && isOwnProjection(right)
63
+ && projectionIdentity(left) === projectionIdentity(right);
64
+ }
65
+
66
+ // 扫描当前 surface,判断该身份是否已经作为本插件消息存在于会话历史中。
67
+ // 存在 → 不重复注入("同一文件只注一次"靠它实现)。
68
+ // compaction 把消息移出 surface 后即判为缺失 → 自动重注磁盘最新版
69
+ // (身份不变、正文刷新,故无需 injectedSessionIds 之类的标记机制)。
45
70
  function alreadyOnSurface(session, desired) {
46
71
  const nodes = session?.surface?.nodes;
47
72
  if (!Array.isArray(nodes)) return false;
48
73
  for (const seq of nodes) {
49
74
  const event = typeof session.eventAt === "function" ? session.eventAt(seq) : undefined;
50
- if (event?.type === "user/message" && sameContextPayload(event.data, desired)) return true;
75
+ if (event?.type === "user/message" && sameProjectionIdentity(event.data, desired)) return true;
51
76
  }
52
77
  return false;
53
78
  }
@@ -62,14 +87,18 @@ function buildProjection(text, heading) {
62
87
  }
63
88
 
64
89
  /**
65
- * 收集本步要投影的记忆消息(用户级 + 项目级,各自独立一条)。
66
- * 两者拆成两条独立消息(v1.7.0 定案):否则"项目记忆一改,用户记忆连带重发"。
67
- * @param {{ getConfig: () => object, paths: object }} deps
68
- * @returns {object[]} 按 [用户级, 项目级…] 顺序的消息数组(可能为空)
90
+ * 收集本步要投影的消息(用户级 / 项目级 MEMORY.md / 今日工作日志,各自独立一条)。
91
+ * 拆成多条独立消息(v1.7.0 定案,v1.7.1 扩展):否则"某一条内容一改,其余连带重发"。
92
+ * v1.7.2:新增 `session` + `isSilent` —— 静默会话(官方 minimal 等预设)整体不投影。
93
+ * @param {{ getConfig: () => object, paths: object, session?: object, isSilent?: (session?: object) => boolean }} deps
94
+ * @returns {object[]} 按 [用户级, 项目级…, 今日日志…] 顺序的消息数组(可能为空)
69
95
  */
70
- export function buildProjections({ getConfig, paths }) {
96
+ export function buildProjections({ getConfig, paths, session, isSilent }) {
71
97
  const cfg = getConfig();
72
98
  if (!cfg.enabled) return [];
99
+ // v1.7.2:静默会话(极简模式等)不投影——投影消息是**常驻历史**,比 section 更"重":
100
+ // 它要一路吃 token 直到 compaction,正是"裸测环境"最不该有的东西。
101
+ if (isSilent?.(session)) return [];
73
102
  const out = [];
74
103
  // 用户级 MEMORY.md
75
104
  const userFile = expandHome(cfg.userMemoryPath);
@@ -92,14 +121,24 @@ export function buildProjections({ getConfig, paths }) {
92
121
  if (msg) out.push(msg);
93
122
  }
94
123
  }
124
+ // 今日工作日志(v1.7.1 由 systemPrompt.section 迁入)。heading 沿用原 section 格式,
125
+ // 天然含日期与目录 → 跨天 / 换目录自动成为新身份。预算沿用 workspaceBudgetChars,
126
+ // 与项目级 MEMORY.md 各自独立 budgetClip,互不挤占。
127
+ for (const dir of paths.readDirs()) {
128
+ const text = readMdSync(join(dir, `${todayISO()}.md`));
129
+ if (!text) continue;
130
+ const clipped = stripSmartTag(stripDeletedLines(budgetClip(text, cfg.workspaceBudgetChars)));
131
+ const msg = buildProjection(clipped, `# 今日工作日志 (${todayISO()} @ ${toHomeShort(dir)})`);
132
+ if (msg) out.push(msg);
133
+ }
95
134
  return out;
96
135
  }
97
136
 
98
137
  /**
99
138
  * 注册 E 投影钩子。
100
- * @param {{ ctx: object, getConfig: () => object, paths: object }} deps
139
+ * @param {{ ctx: object, getConfig: () => object, paths: object, isSilent?: (session?: object) => boolean }} deps
101
140
  */
102
- export function registerProjection({ ctx, getConfig, paths }) {
141
+ export function registerProjection({ ctx, getConfig, paths, isSilent }) {
103
142
  ctx.on("agent/pre-step", async ({ agent, messages, step, signal }, next) => {
104
143
  // 先让瀑布流继续,拿到宿主与其他插件合成后的决策——投影要折叠进它的 messages。
105
144
  const decision = await next();
@@ -107,12 +146,14 @@ export function registerProjection({ ctx, getConfig, paths }) {
107
146
  signal?.throwIfAborted?.();
108
147
  if (decision.kind !== "enter") return decision;
109
148
  const session = agent?.session;
110
- const desired = buildProjections({ getConfig, paths });
149
+ // v1.7.2:静默会话(极简模式等)不投影。放在 next() 之后、构造之前,成本最低。
150
+ if (isSilent?.(session)) return decision;
151
+ const desired = buildProjections({ getConfig, paths, session, isSilent });
111
152
  if (!desired.length) return decision;
112
- // 逐条去重:已被本步的 messages 覆盖、或已在 surface 上的,跳过。
153
+ // 逐条去重(按**文件身份**、非内容):已被本步 messages 覆盖、或已在 surface 上的,跳过。
113
154
  const pending = desired.filter((msg) =>
114
- !messages.some((m) => sameContextPayload(m, msg))
115
- && !decision.messages.some((m) => sameContextPayload(m, msg))
155
+ !messages.some((m) => sameProjectionIdentity(m, msg))
156
+ && !decision.messages.some((m) => sameProjectionIdentity(m, msg))
116
157
  && !alreadyOnSurface(session, msg));
117
158
  if (!pending.length) return decision;
118
159
  // 折叠位置:紧跟在"本步被认领的消息"之后,使直接提示在前、驱动追加的 runtime context 在后。
package/lib/tools.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  // memory-palace 记忆工具:memory_note / memory_note_user / memory_read / memory_delete
2
2
  // + 删除硬确认闸门(tools/pre-execute → harness 原生确认弹窗)。
3
- // 经 registerTools 注入 ctx/config/paths/records/运行时状态;在 index.mjs 装配时调用一次。
3
+ // 经 registerTools 注入 ctx/config/paths/运行时状态;在 index.mjs 装配时调用一次。
4
4
  import { defineTool } from "@deepseek-ai/dsh-tools";
5
5
  import { join } from "node:path";
6
- import { todayISO, expandHome, toHomeShort, readMdSync } from "./common/text.mjs";
6
+ import { todayISO, isoDaysAgo, expandHome, toHomeShort, readMdSync, budgetClip } from "./common/text.mjs";
7
7
  import { appendLineDedup, findMatches, removeLineByMatch, recentLogDates } from "./common/records.mjs";
8
8
 
9
9
  /**
10
- * @param {{ ctx: object, getConfig: () => object, paths: object, records: object, state: object }} deps
10
+ * @param {{ ctx: object, getConfig: () => object, paths: object, state: object }} deps
11
11
  */
12
- export function registerTools({ ctx, getConfig, paths, records, state }) {
12
+ export function registerTools({ ctx, getConfig, paths, state }) {
13
13
  const cfg = () => getConfig();
14
14
 
15
15
  // 删除作用域的中文标签。
@@ -162,18 +162,34 @@ export function registerTools({ ctx, getConfig, paths, records, state }) {
162
162
  }),
163
163
  );
164
164
 
165
- // ---------- 可选工具:读取全部记忆(用户级 + 项目级 MEMORY.md 与每日日志) ----------
166
- // AI 说"读取项目记忆/看看记忆"时直接调用,返回聚合内容,避免 AI 自己翻文件、只找 MEMORY.md 而漏掉每日日志。
165
+ // ---------- 可选工具:读取记忆(scope 控制范围,默认只读 durable 长期记忆) ----------
166
+ // AI 说"读取项目记忆/看看记忆"时直接调用,返回聚合内容,避免 AI 自己翻文件、只找 MEMORY.md 而漏掉项目级记忆。
167
+ // v1.7.1:加 scope(memory 默认 / project / today / yesterday / daily / all)—— 当日日志实测
168
+ // 可达 1.7 万字符,默认值刻意不含它;确实需要日志时必须显式传 scope。
169
+ // project 原名 node —— 为与 memory_write / memory_update_section 的 scope='project' 统一而更名,消除读写两侧命名歧义。
167
170
  ctx.tools.register(
168
171
  defineTool({
169
172
  name: "memory_read",
170
173
  description:
171
- "Read all persistent memory: user-level MEMORY.md (cross-project preferences), " +
172
- "and for the current project the workspace MEMORY.md plus recent daily logs " +
173
- "(YYYY-MM-DD.md) from .workbuddy/memory, .codebuddy/memory, or .deepseek-harness/memory. " +
174
- "Use this instead of manually globbing/reading memory files — it aggregates everything. " +
175
- "This tool takes no parameters; call it with an empty object, e.g. tools.memory_read({}) — the runtime rejects undefined arguments.",
176
- parameters: {},
174
+ "Read persistent memory. scope defaults to 'memory' and decides what comes back: " +
175
+ "'memory' (default) = user-level MEMORY.md (cross-project preferences) + this project's workspace MEMORY.md; " +
176
+ "'project' = this project's workspace MEMORY.md only (same naming as the write-side scope of memory_write / memory_update_section); " +
177
+ "'today' / 'yesterday' = that single day's daily log; " +
178
+ "'daily' = the last three days of logs (today + yesterday + the day before); " +
179
+ "'all' = memory + daily (large — only when the logs are genuinely needed). " +
180
+ "Start from the default scope and widen it only when the question is really about logs. " +
181
+ "Use this instead of manually globbing/reading memory files. " +
182
+ "Call it as tools.memory_read({}) or tools.memory_read({ scope: 'daily' }) — the runtime rejects undefined arguments.",
183
+ parameters: {
184
+ scope: {
185
+ type: "string",
186
+ enum: ["memory", "project", "today", "yesterday", "daily", "all"],
187
+ description:
188
+ "What to read. 'memory' (default) = user-level + workspace MEMORY.md (durable long-term memory; usually all you need). " +
189
+ "'project' = workspace MEMORY.md only (same value as the write-side scope of memory_write). 'today' / 'yesterday' = that single day's log. " +
190
+ "'daily' = last three days of logs. 'all' = memory + daily.",
191
+ },
192
+ },
177
193
  output: {
178
194
  schema: {
179
195
  type: "object",
@@ -186,28 +202,50 @@ export function registerTools({ ctx, getConfig, paths, records, state }) {
186
202
  },
187
203
  render: (_args, value) => [{ type: "text", text: value?.memory ?? value?.message ?? "No memory." }],
188
204
  },
189
- async execute() {
205
+ async execute(args = {}) {
190
206
  const c = cfg();
191
207
  if (!c.enabled) return { ok: false, message: "memory-palace is currently disabled in settings.", memory: "" };
208
+ // v1.7.1:默认 scope='memory'(长期记忆)。刻意不设 'all' —— 默认全量会让 agent
209
+ // 不加思考地把日志(实测单日可达 1.7 万字符)一起吞下,白白吃掉上下文。
210
+ const scope = args?.scope ?? "memory";
211
+ const wantUser = scope === "memory" || scope === "all";
212
+ const wantProject = scope === "memory" || scope === "project" || scope === "all";
213
+ // 日志按**日期**取(而非"最近 N 份文件"——跨日跳空会取偏):today / yesterday / daily(近三天) / all
214
+ const logDays =
215
+ scope === "today" ? [0]
216
+ : scope === "yesterday" ? [1]
217
+ : scope === "daily" || scope === "all" ? [0, 1, 2]
218
+ : [];
192
219
  try {
193
220
  const blocks = [];
194
- const userFile = expandHome(c.userMemoryPath);
195
- const userFileShort = toHomeShort(userFile);
196
- const u = readMdSync(userFile);
197
- if (u) blocks.push(`# 用户级记忆 (${userFileShort})\n${u}`);
221
+ if (wantUser) {
222
+ const userFile = expandHome(c.userMemoryPath);
223
+ const u = readMdSync(userFile);
224
+ if (u) blocks.push(`# 用户级记忆 (${toHomeShort(userFile)})\n${u}`);
225
+ }
198
226
  for (const dir of paths.readDirs()) {
199
227
  const dirShort = toHomeShort(dir);
200
- const w = paths.memoryReadCandidates(dir).map(readMdSync).filter(Boolean).join("\n\n");
201
- if (w) blocks.push(`# 工作区记忆 (${dirShort})\n${w}`);
202
- const t = readMdSync(join(dir, `${todayISO()}.md`));
203
- if (t) blocks.push(`# 今日工作日志 (${todayISO()} @ ${dirShort})\n${t}`);
204
- const recent = await records.recentLogs(dir);
205
- if (recent) blocks.push(recent);
228
+ if (wantProject) {
229
+ // 标题必须用实际读到的 MEMORY.md 路径,而非日志目录 —— dsh 布局下 MEMORY.md 位于
230
+ // 日志目录的上一级,旧实现拿 dir(.../memory)当标题会误导真实路径(buddy 布局
231
+ // MEMORY.md 恰在 memory/ 内所以未暴露)。与 E 投影的 per-file 粒度对齐。
232
+ for (const f of paths.memoryReadCandidates(dir)) {
233
+ const t = readMdSync(f);
234
+ if (t) blocks.push(`# 工作区记忆 (${toHomeShort(f)})\n${t}`);
235
+ }
236
+ }
237
+ for (const n of logDays) {
238
+ const day = isoDaysAgo(n);
239
+ const t = readMdSync(join(dir, `${day}.md`));
240
+ if (!t) continue;
241
+ const label = n === 0 ? "今日" : n === 1 ? "昨日" : "前日";
242
+ blocks.push(`# ${label}工作日志 (${day} @ ${dirShort})\n${budgetClip(t, c.workspaceBudgetChars)}`);
243
+ }
206
244
  }
207
245
  if (!blocks.length) {
208
- return { ok: true, message: "No memory files found yet.", memory: "" };
246
+ return { ok: true, message: `No memory files found (scope=${scope}).`, memory: "" };
209
247
  }
210
- return { ok: true, message: "Memory loaded.", memory: blocks.join("\n\n") };
248
+ return { ok: true, message: `Memory loaded (scope=${scope}).`, memory: blocks.join("\n\n") };
211
249
  } catch (e) {
212
250
  return { ok: false, message: `Failed: ${e}`, memory: "" };
213
251
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-memory-palace",
3
- "version": "1.7.0",
3
+ "version": "1.7.2-alpha.1",
4
4
  "description": "把 WorkBuddy 的文件式记忆系统移植进 DeepSeek Harness:用户级 + 工作区的人类可读 Markdown 记忆(~/.deepseek-harness/MEMORY.md 与 <cwd>/.deepseek-harness/memory/)。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -41,13 +41,13 @@
41
41
  },
42
42
  "peerDependencies": {
43
43
  "@deepseek-ai/cordis": "*",
44
- "@deepseek-ai/dsh-llm": "*",
45
- "@deepseek-ai/dsh-settings": "^0.1.2-alpha.2",
46
- "@deepseek-ai/dsh-tools": "^0.1.2-alpha.2",
44
+ "@deepseek-ai/dsh-llm": "^0.1.5-rc.1",
45
+ "@deepseek-ai/dsh-settings": "^0.1.5-rc.1",
46
+ "@deepseek-ai/dsh-tools": "^0.1.5-rc.1",
47
47
  "@deepseek-ai/schemastery": "^3.18.2"
48
48
  },
49
49
  "devDependencies": {
50
- "@deepseek-ai/dsh-settings": "^0.1.2-alpha.2"
50
+ "@deepseek-ai/dsh-settings": "^0.1.5-rc.1"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "node scripts/build.mjs",