@alanzhao/dsh-memory-lite 0.2.4 → 0.2.6

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 ADDED
@@ -0,0 +1,155 @@
1
+ # dsh-memory-lite
2
+
3
+ English | [简体中文](README.md)
4
+
5
+ **Cross-session long-term memory for your dsh agent.** Plain Markdown files, zero dependencies: preferences, decisions and constraints from a session survive restarts, upgrades and profile switches.
6
+
7
+ > Every dsh session starts from a blank page — transcripts are persisted for audit, but the model never sees them again. This plugin adds that layer back: one resident memory catalog + 5 memory tools + background extraction.
8
+
9
+ <p align="center">
10
+ <img src="docs/preview/header-indicator.png" alt="The memory-lite indicator in the session header" height="44">
11
+ </p>
12
+
13
+ ## Quick start (3 steps)
14
+
15
+ ```sh
16
+ # 1. Install (= pnpm add inside the profile; the package is added to
17
+ # dsh.profile.bundles automatically)
18
+ dsh plugin --profile web add @alanzhao/dsh-memory-lite
19
+
20
+ # 2. Restart dsh (the host half and the browser half load at boot)
21
+
22
+ # 3. Verify — the three checks below
23
+ ```
24
+
25
+ After installing you should see:
26
+
27
+ - a `memory-lite` capsule in the session header: **green** = last extraction ok, gray = extraction off, red = last extraction failed
28
+ - a full settings page under **Settings → memory-lite** (screenshot below)
29
+ - ask the model to remember something ("remember that I use pnpm") — it calls `remember` and a file lands under `~/.agent-memory/peers/<peer>/memories/preferences/` (directories are created on first use)
30
+
31
+ Requirements: **dsh ≥ 0.1.5** (since 0.2.0 the plugin RPC uses the `/api` shared Fetch-route registry; `connection.rpc.handle` is unusable for third-party plugins after 0.1.3-alpha.2), Node ≥ 22.
32
+
33
+ <p align="center">
34
+ <img src="docs/preview/settings-extraction.png" alt="Settings → memory-lite: extraction mode and triggers" width="560">
35
+ </p>
36
+
37
+ ## Features
38
+
39
+ | What | Notes |
40
+ |---|---|
41
+ | Explicit memory (5 tools) | `read_memory` / `search_memory` / `remember` / `update_memory` / `forget_memory`; `update` archives the previous content into `## History`, `forget` is a soft delete into `.trash/` |
42
+ | L0 catalog injection | one resident catalog message per session (rendered from `_index.md`); re-published when the index changes or compaction moves it off the visible surface |
43
+ | Implicit extraction | a background run feeds the new conversation window to the model and applies a create / merge / update / skip decision, with dedup search and parse-failure repair |
44
+ | Cross-peer sharing | mount another peer's memories read-only under `shared/<name>/` |
45
+ | Header indicator | capsule + three-state dot in the session header, polling the run status every 10 s |
46
+ | Peer isolation | the peer name derives from the session cwd (basename + short hash); cwd-less sessions fall back to `defaultPeer` |
47
+
48
+ <p align="center">
49
+ <img src="docs/preview/settings-model.png" alt="Settings → memory-lite: message scope, extraction model, reasoning effort" width="560">
50
+ </p>
51
+
52
+ ## What it costs
53
+
54
+ | When | Cost |
55
+ |---|---|
56
+ | Every step | the 5 tool schemas are injected (~300–800 tokens) |
57
+ | Every session | one resident catalog message, capped at 1200 tokens by default; near-zero incremental cost once the KV cache hits |
58
+ | Every explicit remember | one tool call; the index rebuild costs no LLM |
59
+ | Every implicit extraction | **one LLM call** (two when the answer needs a repair), using your default model or a pinned one |
60
+
61
+ Default triggers: 50 new conversation messages (`windowTurns`) or 30 minutes idle (`idleTimeoutMin`); turn-boundary and flush triggers are off by default.
62
+
63
+ > **Tip**: extraction is a structured JSON task and needs no reasoning. Set **reasoning effort = off** — otherwise the model can spend the whole output budget thinking (two calls and 20–80 s per run).
64
+
65
+ ## Configuration
66
+
67
+ Everything is edited in **Settings → memory-lite** and stored under the `dsh-memory-lite:` section of `~/.dsh/settings.yaml`. Most fields apply on save; `root` and `sharing.*` need a restart.
68
+
69
+ | Group | Field | Notes |
70
+ |---|---|---|
71
+ | Extraction | Mode | `incremental` (default, implicit extraction on) / `explicit_only` / `off` |
72
+ | Triggers | Window turns | one run once this many new messages accumulate; default 50; 0 = trigger on every message (not a disable) |
73
+ | | Idle timeout (min) | extract the remaining window after N idle minutes; default 30 |
74
+ | | Turn-boundary / flush triggers | off by default (more expensive) |
75
+ | | Min messages / debounce | thresholds for the two triggers above |
76
+ | Content | Max messages | most messages fed to the model per run; default 20 |
77
+ | | Message scope | default user + assistant; raw tool results excluded (cost and noise only); all three unchecked = the default |
78
+ | | Tool-result truncation (bytes) | only used when "tool results" is checked |
79
+ | | Include digest / dedup search | both on by default |
80
+ | Model | Extraction model | follows the live global default model unless pinned to a provider/model |
81
+ | | Reasoning effort | read from the selected model's declaration; **off is recommended** |
82
+ | Reliability | Parse retry | one cheap repair call when the answer is not valid JSON (on by default) |
83
+ | | Audit log | writes `peers/{peer}/sessions/{session-id}.json` and `extraction.log` |
84
+ | Catalog | Token cap | truncation cap for the L0 catalog, default 1200 |
85
+ | UI | Indicator order | header utilities slot order; refresh the page after saving |
86
+ | Storage | Memory root | `~/.agent-memory` by default, **restart to apply** |
87
+ | | Default peer | owner of cwd-less sessions |
88
+ | | Cross-peer sharing | master switch, **restart to apply**; individual mounts are picked below |
89
+
90
+ Full schema and defaults: [`src/config.ts`](https://github.com/alanzhao0128/dsh-memory-lite/blob/main/src/config.ts).
91
+
92
+ ## What the memory looks like
93
+
94
+ ```
95
+ ~/.agent-memory/
96
+ ├── peers/{peer}/
97
+ │ ├── memories/
98
+ │ │ ├── _index.md # L0 catalog (generated; hand-editable)
99
+ │ │ ├── preferences/ entities/ events/ experiences/
100
+ │ │ │ └── {slug}.md # L1 full text
101
+ │ └── sessions/ # extraction bookmark + audit + extraction.log
102
+ └── .trash/ # soft-deleted memories (dated folders)
103
+ ```
104
+
105
+ Each memory file uses `## Current` / `## History` / `## Related`; updates archive instead of overwriting. The four categories are retrieval paths for the model: preferences (always relevant), entities (mentioned knowledge), events (time-related), experiences (task lessons).
106
+
107
+ ## How it works (short version)
108
+
109
+ - **Catalog injection**: in the `agent/pre-step` waterfall the peer's `_index.md` is rendered into one `user/message` carrying the official `plugin` source kind with the `catalog` form; subagent sessions get none.
110
+ - **Extraction**: triggered by `windowTurns` or idle → select the window → grep existing memories for dedup → one LLM decision → write files → advance the per-session bookmark. **A failed run keeps the bookmark**, so the same window is retried on the next trigger.
111
+ - **Safety**: every file access goes through a containment boundary (relative paths only; `..`, absolute paths and symlink escapes are rejected at the executor).
112
+ - **Concurrency**: all writes go through a serial queue with atomic tmp+rename replacement.
113
+
114
+ Details (design tradeoffs, incident notes, known deviations) live in [`IMPLEMENTATION.md`](https://github.com/alanzhao0128/dsh-memory-lite/blob/main/IMPLEMENTATION.md).
115
+
116
+ ## Troubleshooting
117
+
118
+ | Symptom | What to do |
119
+ |---|---|
120
+ | Nothing happens after installing; the model has no memory tools | **Restart dsh**; check that `dsh plugin --profile web ls` lists the package and that it is in `dsh.profile.bundles` |
121
+ | No memory-lite capsule in the header | Refresh the page; the slot lives in the header utilities row (order is configurable) |
122
+ | The capsule is red | The last extraction failed: read the `note` of the last line in `~/.agent-memory/peers/<peer>/sessions/extraction.log` |
123
+ | Extraction never fires | Check, in order: extraction mode, window turns, message scope, max messages (0 = nothing is extracted) |
124
+ | The log says `no configured model`, or the panel shows 已失效 (stale) | The extraction model was renamed or removed — pick another one |
125
+ | Extraction is slow / always `parse-error-recovered` | Reasoning effort is eating the output budget: set it to off |
126
+ | Memories land under the wrong peer | The peer derives from the session cwd; cwd-less sessions use `defaultPeer` (configurable) |
127
+
128
+ ## Uninstall
129
+
130
+ ```sh
131
+ dsh plugin --profile web remove @alanzhao/dsh-memory-lite
132
+ # restart dsh
133
+ ```
134
+
135
+ Your memories are not deleted: `~/.agent-memory` is left for you to keep or remove.
136
+
137
+ ## Known limits
138
+
139
+ - `forget_memory` has no approval gate (the model can soft-delete directly).
140
+ - `## Related` auto-maintenance is not implemented.
141
+ - No CLI / MCP entry point.
142
+ - The browser half (indicator + settings page) is verified on the dsh web profile only.
143
+ - Extraction quality depends on the model you pick; small models produce JSON that needs repair more often.
144
+
145
+ ## Development
146
+
147
+ ```sh
148
+ npm install
149
+ npm run build # tsc -> lib/
150
+ npm test # node:test + tsx, including a real Loader boot smoke test
151
+ ```
152
+
153
+ ## License
154
+
155
+ MIT
package/README.md CHANGED
@@ -1,117 +1,153 @@
1
1
  # dsh-memory-lite
2
2
 
3
- Lightweight, zero-dependency long-term memory for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness). Memories are plain Markdown files under a configurable root; the plugin injects an L0 memory catalog into each session and exposes five model-facing tools.
3
+ [English](README.en.md) | 简体中文
4
4
 
5
- Design: [《Light Memory for DSH 设计方案》](https://github.com/deepseek-ai/deepseek-harness) v7 (2026-08-25). Implementation spec: [IMPLEMENTATION.md](IMPLEMENTATION.md).
5
+ **给你的 dsh agent 一份跨会话的长期记忆。** 纯 Markdown 文件、零依赖:会话里的偏好、决策、约束会被记下来,重启、升级、换 profile 之后依然在。
6
6
 
7
- > **Status: Phase 1-3 implemented.** Explicit capture (remember / update / forget), L0 catalog injection, search and read (Phase 1); implicit background extraction (Phase 2, window + idle triggers active, turn/flush triggers shipped but off by config); and read-only cross-peer sharing (Phase 3) are built and live-tested. Not yet built: `forget_memory` approval, `## Related` auto-maintenance, CLI/MCP (Phase 4).
7
+ > dsh 的每个会话都是白纸开局 —— 转录落盘是为了审计,模型再也看不到它。这个插件补上那一层:一条常驻的记忆目录 + 5 个记忆工具 + 后台自动提取。
8
8
 
9
- ## Install
9
+ <p align="center">
10
+ <img src="docs/preview/header-indicator.png" alt="会话标题栏里的 memory-lite 指示器" height="44">
11
+ </p>
10
12
 
11
- > **Requires dsh ≥ 0.1.5.** v0.2.0 migrated the plugin RPC channels to the `/api` shared Fetch-route registry (`connection.fetch.register`); `connection.rpc.handle` is unusable for third-party plugins since 0.1.3-alpha.2 (official issue #5926, unfixed on master).
12
-
13
- Install into a profile and add it to that profile's bundle list:
13
+ ## 快速开始(3 步)
14
14
 
15
15
  ```sh
16
+ # 1. 安装(= 在 profile 里 pnpm add,并自动把包加进 dsh.profile.bundles)
16
17
  dsh plugin --profile web add @alanzhao/dsh-memory-lite
17
- ```
18
18
 
19
- or, for a local checkout, add a linked dependency and bundle:
19
+ # 2. 重启 dsh(宿主插件与浏览器半边都在启动时加载)
20
20
 
21
- ```jsonc
22
- // $DSH_HOME/profiles/web/package.json
23
- {
24
- "dependencies": { "@alanzhao/dsh-memory-lite": "^0.2.0" },
25
- "dsh": { "profile": { "bundles": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app", "@alanzhao/dsh-memory-lite"] } }
26
- }
21
+ # 3. 验证:见下面三条
27
22
  ```
28
23
 
29
- The bundle inserts the plugin row without configuration; defaults apply immediately.
30
-
31
- ## Configuration
32
-
33
- All settings are edited in the **settings panel** (Settings → memory-lite). They persist to the harness settings document (`~/.dsh/settings.yaml`, section `dsh-memory-lite:`) and most take effect **immediately** — no restart, no YAML editing. The header indicator and extraction behavior react live.
34
-
35
- The plugin row in `cordis.patch.yml` carries **no configuration** (mount only); a row config, if present, acts as the deployment base layer under the settings document (settings values win). The full schema, with defaults, lives in [src/config.ts](src/config.ts):
36
-
37
- ```yaml
38
- - id: memory-lite
39
- name: "@alanzhao/dsh-memory-lite"
40
- # config: # optional deployment defaults; settings override
41
- # root: '~/.agent-memory'
42
- # defaultPeer: dsh-web
43
- # extraction:
44
- # mode: incremental
45
- # windowTurns: 50
46
- # messageScope: [user, assistant] # count/feed only conversation turns
47
- # turnStoppingTrigger: false
48
- # flushTrigger: false
49
- # sharing:
50
- # enabled: true
51
- # mounts:
52
- # - name: dsh-test
53
- # peer: dsh-test-72572e8b
54
- # subpath: ''
55
- # readonly: true
56
- ```
24
+ 装好后你应该看到:
25
+
26
+ - 会话标题栏出现 `memory-lite` 胶囊:**绿点** = 最近一次提取正常,灰 = 提取关闭,红 = 最近一次提取失败
27
+ - **设置 → memory-lite** 出现完整配置页(下图)
28
+ - 对模型说「记住:我用 pnpm 作为包管理器」,它会调用 `remember`,文件落到 `~/.agent-memory/peers/<peer>/memories/preferences/`(首次使用会自动建目录)
57
29
 
58
- Effect timing:
30
+ 要求:**dsh ≥ 0.1.5**(0.2.0 起插件的 RPC 走 `/api` 共享 Fetch 路由;`connection.rpc.handle` 对第三方插件在 0.1.3-alpha.2 之后不可用),Node ≥ 22。
59
31
 
60
- - **Live** (apply on save): `extraction.*`, `index.maxTokens`, `defaultPeer`, `workspacePeers.*`, `ui.headerOrder` (after a refresh for the slot order).
61
- - **Stale model values**: if `extraction.llm.route` (or `reasoningEffort`) points at a model the provider has renamed or removed, the panel shows it as a flagged *已失效* option with a warning instead of silently displaying *跟随全局默认*. The plugin never rewrites it for you — extraction keeps failing until you pick a new value.
62
- - **Restart** (persisted, apply on next boot): `root`, `sharing.*` — `MemoryStore` pins them at construction; the panel labels them accordingly.
32
+ <p align="center">
33
+ <img src="docs/preview/settings-extraction.png" alt="设置 → memory-lite:提取模式与触发方式" width="560">
34
+ </p>
63
35
 
64
- ## Tools
36
+ ## 功能
65
37
 
66
- | Tool | Purpose |
38
+ | 能力 | 说明 |
67
39
  |---|---|
68
- | `read_memory` | Read the full text of one memory file (exact path from the catalog). |
69
- | `search_memory` | Line search across the session peer's memory files. |
70
- | `remember` | Create or append a memory — call ONLY when the user explicitly asks to remember. |
71
- | `update_memory` | Replace a memory's current content; the previous content moves to `## History` (ADD-only). |
72
- | `forget_memory` | Soft-delete a memory into `<root>/.trash/`. |
40
+ | 显式记忆(5 个工具) | `read_memory` / `search_memory` / `remember` / `update_memory` / `forget_memory`;`update` 把旧内容归档进 `## History`,`forget` 是软删除(进 `.trash/`) |
41
+ | L0 目录注入 | 每个会话注入一条常驻的记忆目录消息(`_index.md` 渲染);目录变化、或压缩把它挤出可见面时自动重发 |
42
+ | 隐式提取 | 后台把新增对话窗口喂给模型,产出 create / merge / update / skip 决策,带去重检索与解析失败重试 |
43
+ | 跨 peer 共享 | 把别的 peer 的记忆以只读方式挂到 `shared/<name>/` 下 |
44
+ | 头部指示器 | 标题栏胶囊 + 三色点,每 10 秒轮询一次运行状态 |
45
+ | peer 隔离 | peer 名由会话 cwd 推导(目录名 + 短哈希),无 cwd 的会话落到 `defaultPeer` |
73
46
 
74
- ### Memory file layout
47
+ <p align="center">
48
+ <img src="docs/preview/settings-model.png" alt="设置 → memory-lite:计入窗口的消息类型、提取模型、推理强度" width="560">
49
+ </p>
50
+
51
+ ## 它会花多少钱
52
+
53
+ | 时机 | 成本 |
54
+ |---|---|
55
+ | 每一步 | 5 个工具 schema 注入(约 300–800 tokens) |
56
+ | 每个会话 | L0 目录一条常驻消息,默认上限 1200 tokens;命中 KV cache 后增量接近 0 |
57
+ | 每次显式 remember | 一次工具调用;索引重建不花 LLM |
58
+ | 每次隐式提取 | **1 次 LLM 调用**(解析失败重试时 2 次),用你的默认模型或指定模型 |
59
+
60
+ 默认触发条件:新增 50 条会话消息(`windowTurns`)或空闲 30 分钟(`idleTimeoutMin`);回合边界与落盘触发默认关闭。
61
+
62
+ > **建议**:提取是结构化 JSON 任务,不需要推理。把「推理强度」设为 **off** —— 否则模型可能把输出预算全花在思考上(表现为每次跑两次、耗时 20–80 秒)。
63
+
64
+ ## 配置
65
+
66
+ 全部在 **设置 → memory-lite** 里改,存到 `~/.dsh/settings.yaml` 的 `dsh-memory-lite:` 段。多数字段**保存即生效**;`root` 与 `sharing.*` 需要重启。
67
+
68
+ | 分组 | 字段 | 说明 |
69
+ |---|---|---|
70
+ | 提取 | 提取模式 | `incremental`(默认,隐式提取开)/ `explicit_only` / `off` |
71
+ | 触发方式 | 窗口触发(消息数) | 新增消息数 ≥ 此值触发一次;默认 50;0 = 每条消息触发(不是禁用) |
72
+ | | 空闲兜底(分钟) | 空闲 N 分钟后提取剩余窗口;默认 30 |
73
+ | | 回合边界触发 / 会话落盘触发 | 默认关闭(成本更高) |
74
+ | | 回合边界最小消息数 / 回合防抖(毫秒) | 上面两个触发器的门槛 |
75
+ | 提取内容 | 单次消息上限 | 一次喂给模型的最大消息数;默认 20 |
76
+ | | 计入窗口的消息类型 | 默认 用户 + 助手;工具结果原文默认排除(只增成本与噪声);三项全不勾 = 用默认 |
77
+ | | 工具结果截断(字节) | 仅勾选「工具结果原文」时生效 |
78
+ | | 携带会话摘要 / 去重检索 | 默认都开 |
79
+ | 提取模型 | 提取模型 | 默认跟随全局默认模型(活值);也可固定到某个 provider/model |
80
+ | | 推理强度 | 按所选模型声明的强度读取;**建议 off** |
81
+ | 可靠性 | 解析失败重试 | JSON 解析失败时一次廉价 repair 调用(默认开) |
82
+ | | 审计日志 | 写 `peers/{peer}/sessions/{session-id}.json` 与 `extraction.log` |
83
+ | 目录注入 | 目录 token 上限 | L0 目录截断上限,默认 1200 |
84
+ | 界面 | 指示器位置 | 标题栏 utilities 槽顺序;保存后刷新页面生效 |
85
+ | 存储与共享 | 记忆根目录 | 默认 `~/.agent-memory`,**重启生效** |
86
+ | | 默认 peer | 无 cwd 会话的归属 |
87
+ | | 跨 peer 共享 | 总开关,**重启生效**;具体挂载在下方勾选 |
88
+
89
+ 完整 schema 与默认值见 [`src/config.ts`](https://github.com/alanzhao0128/dsh-memory-lite/blob/main/src/config.ts)。
90
+
91
+ ## 记忆长什么样
75
92
 
76
93
  ```
77
94
  ~/.agent-memory/
78
95
  ├── peers/{peer}/
79
96
  │ ├── memories/
80
- │ │ ├── _index.md # L0 index (generated; human-editable)
97
+ │ │ ├── _index.md # L0 目录(生成;可人工编辑)
81
98
  │ │ ├── preferences/ entities/ events/ experiences/
82
- │ │ │ └── {slug}.md # L1 full text
83
- │ └── sessions/ # extraction checkpoint + audit ({session-id}.json) and extraction.log
84
- └── .trash/ # soft-deleted memories (root/.trash/<date>/)
99
+ │ │ │ └── {slug}.md # L1 全文
100
+ │ └── sessions/ # 提取书签 + 审计 + extraction.log
101
+ └── .trash/ # forget 的软删除(按日期分目录)
85
102
  ```
86
103
 
87
- Each memory file uses `## Current` / `## History` / `## Related` sections; updates archive, never destroy. The four categories are retrieval paths for the model: preferences (always relevant), entities (mentioned knowledge), events (time-related), experiences (task lessons).
104
+ 每个记忆文件用 `## Current` / `## History` / `## Related` 三段;更新是归档而不是覆盖。四个分类是给模型的检索路径:preferences(总是相关)、entities(被提到的事实)、events(时间相关)、experiences(任务经验)。
88
105
 
89
- ## How it works
106
+ ## 工作原理(简版)
90
107
 
91
- - **L0 catalog injection** (`agent/pre-step` waterfall, copied from `@deepseek-ai/dsh-tool-skill`): the peer's `_index.md` is rendered into one durable `user/message` carrying the **official** `plugin` source kind with the `catalog` form (`{kind:'plugin', plugin:'dsh-memory-lite', form:'catalog'}`) — the private `memory-catalog` kind used before 0.2.3 is still read back so old sessions never publish a duplicate. Re-published when the index changes or compaction moves it off the visible surface. A fresh empty index publishes nothing (unless sharing mounts are enabled — then only the `## shared` hint is published). Subagent sessions get no catalog.
92
- - **Peer isolation**: each session's cwd derives its peer name (sanitized basename + short hash); cwd-less sessions fall back to `defaultPeer`.
93
- - **Peer display names**: Chinese and other non-ASCII workspace directories collapse to hash-suffixed ASCII names (e.g. `workspace-aad65ea5`). The plugin records a human-readable `.peer-meta.json` (`displayName`, e.g. 健康分析) per peer the first time a session with that cwd is seen; the sharing settings list shows `健康分析 (workspace-aad65ea5)`.
94
- - **Path safety**: every file access goes through a containment boundary — relative paths only, `..` / absolute / symlink escapes rejected at the executor.
95
- - **Implicit extraction** (Phase 2): once `windowTurns` (default 50) new in-scope conversation messages accumulate — or after `idleTimeoutMin` (default 30 min) of idle — a background run feeds the new window to the LLM and applies a create/merge/update/skip decision (dedup against existing memories), then advances a per-session checkpoint and rolling digest. Turn-boundary and flush triggers are shipped but disabled by config (cost); subagent sessions are never extracted. Only `messageScope` event kinds count toward the trigger and enter the window (default `['user','assistant']`; raw tool results excluded — their output adds token cost and noise while the assistant message already carries the interpretation). Audit trails live in `peers/{peer}/sessions/`.
96
- - **Cross-peer sharing** (Phase 3): `sharing.mounts` expose another peer's memories read-only at `shared/<name>/...`; `search_memory` covers shared mounts and results keep the `shared/<name>` prefix. Shared entries stay out of the local catalog.
97
- - **Concurrent writes**: all mutations run through a serial queue with atomic tmp+rename replacement.
98
- - **Header status indicator** (browser half, `lib/client.js`): a compact "memory-lite" capsule in the session-header utilities row, left of the built-in "open workspace" split button (order -20 vs the button's -10). The dot polls the `/api/memory-status/snapshot` RPC channel every 10s — green (last extraction run ok), red (last run failed or the plugin is unreachable), gray (extraction mode off / explicit_only). No data yet is green.
108
+ - **目录注入**:在 `agent/pre-step` 瀑布里把 `_index.md` 渲染成一条带官方 `plugin` + `catalog` 形式的 `user/message`;子代理会话不注入。
109
+ - **提取**:按 `windowTurns` 或空闲触发 → 取窗口内消息 → grep 已有记忆去重 → 一次 LLM 决策 → 写文件 → 推进每会话书签。**失败不推进书签**,下次触发重试。
110
+ - **安全**:所有文件访问过包含边界(只允许相对路径;`..`、绝对路径、symlink 逃逸在执行层拒绝)。
111
+ - **并发**:所有写入走串行队列 + 原子替换(tmp + rename)。
99
112
 
100
- ## Model Experience
113
+ 细节(设计取舍、事故记录、实现偏差)在 [`IMPLEMENTATION.md`](https://github.com/alanzhao0128/dsh-memory-lite/blob/main/IMPLEMENTATION.md)。
101
114
 
102
- - **Per step**: the 5 tool schemas are injected into every model request (~300–800 tokens).
103
- - **Per session**: the L0 catalog is one durable surface message (resident; re-sent only after compaction or an index change, capped at `index.maxTokens`, default 1200 — ~1000 tokens with the current memory count, near-zero incremental cost with KV cache).
104
- - **Per explicit remember**: one tool call; the index rebuild is free (no LLM).
115
+ ## 故障排查
105
116
 
106
- ## Development
117
+ | 现象 | 处理 |
118
+ |---|---|
119
+ | 装完没反应、模型看不到记忆工具 | 必须**重启 dsh**;确认 `dsh plugin --profile web ls` 里有这个包,且 `dsh.profile.bundles` 里也有它 |
120
+ | 标题栏没有 memory-lite 胶囊 | 刷新页面;槽位在标题栏 utilities 区(位置可在设置里调) |
121
+ | 胶囊红点 | 最近一次提取失败:看 `~/.agent-memory/peers/<peer>/sessions/extraction.log` 最后一行的 `note` |
122
+ | 提取从不触发 | 依次检查:提取模式、窗口触发消息数、计入窗口的消息类型、单次消息上限(0 = 不提取) |
123
+ | 日志出现 `no configured model`,或设置页显示「已失效」 | 提取模型指向了已改名/删除的模型,重新选一个 |
124
+ | 提取很慢 / 总是 `parse-error-recovered` | 推理强度太高吃光输出预算:把「推理强度」设为 off |
125
+ | 记忆写到了别的 peer | peer 由会话 cwd 推导;无 cwd 的会话用 `defaultPeer`(设置里可改) |
126
+
127
+ ## 卸载
107
128
 
108
129
  ```sh
109
- npm install # project-local .npm-cache avoids a root-owned npm cache
110
- npm run build # tsc -> lib/
111
- npm test # node:test + tsx; includes a real Loader boot smoke
130
+ dsh plugin --profile web remove @alanzhao/dsh-memory-lite
131
+ # 重启 dsh
112
132
  ```
113
133
 
114
- The Loader boot test (`tests/boot.test.ts`) boots a real `cordis.yml` through the Cordis Loader with the services the plugin needs and asserts all five tools register; it requires `npm run build` first (it loads the built `lib/`).
134
+ 记忆文件不会被删:`~/.agent-memory` 留着自己处理(想清空直接删目录)。
135
+
136
+ ## 已知限制
137
+
138
+ - `forget_memory` 没有审批门控(模型可以直接软删除)。
139
+ - `## Related` 的自动维护还没做。
140
+ - 没有 CLI / MCP 入口。
141
+ - 浏览器半边(指示器 + 设置页)只在 dsh web profile 上验证过。
142
+ - 隐式提取的质量取决于你选的模型;小模型更容易产出需要 repair 的 JSON。
143
+
144
+ ## 开发
145
+
146
+ ```sh
147
+ npm install
148
+ npm run build # tsc -> lib/
149
+ npm test # node:test + tsx(含真实 Loader 启动冒烟)
150
+ ```
115
151
 
116
152
  ## License
117
153
 
Binary file
package/lib/client.js CHANGED
@@ -136,7 +136,7 @@ window.__ModuleLoader__.load({
136
136
  { path: ['extraction', 'turnDebounceMs'], type: 'number', group: 'extraction', sub: '触发方式', label: '回合防抖(毫秒)', hint: '回合边界提取的防抖窗口;0 = 无防抖,每次都触发' },
137
137
  // ---- 提取内容 ----
138
138
  { path: ['extraction', 'maxMessages'], type: 'number', group: 'extraction', sub: '提取内容', label: '单次消息上限', hint: '单次提取喂给 LLM 的最大消息数;0 = 窗口为空,不提取(等效禁用)' },
139
- { path: ['extraction', 'messageScope'], type: 'multicheck', group: 'extraction', sub: '提取内容', label: '计入窗口的消息类型', options: [['user', '用户消息'], ['assistant', '助手消息'], ['tool_result', '工具结果原文']], hint: '勾选的类型计入触发计数并进入提取窗口;工具结果默认排除(助手消息已含解读,原文只增成本与噪声)。保存即时生效。' },
139
+ { path: ['extraction', 'messageScope'], type: 'multicheck', group: 'extraction', sub: '提取内容', label: '计入窗口的消息类型', options: [['user', '用户消息'], ['assistant', '助手消息'], ['tool_result', '工具结果原文']], hint: '勾选的类型计入触发计数并进入提取窗口;工具结果默认排除(助手消息已含解读,原文只增成本与噪声)。三项全不勾 = 用默认(用户 + 助手)。保存即时生效。' },
140
140
  { path: ['extraction', 'toolResultMaxBytes'], type: 'number', group: 'extraction', sub: '提取内容', label: '工具结果截断(字节)', hint: '仅当上方勾选“工具结果原文”时生效:每条 tool_result 喂给 LLM 前的截断字节;0 = 工具内容全部丢弃' },
141
141
  { path: ['extraction', 'includeDigest'], type: 'toggle', group: 'extraction', sub: '提取内容', label: '携带会话摘要', hint: '提取时携带滚动会话 digest' },
142
142
  { path: ['extraction', 'dedup'], type: 'toggle', group: 'extraction', sub: '提取内容', label: '去重检索', hint: '提取前 grep 已有记忆做去重/矛盾判断' },
@@ -237,7 +237,7 @@ window.__ModuleLoader__.load({
237
237
  // - routeOptions: [['', '跟随全局默认(当前:<provider> / <model>)'], ...all '<provider> / <model>']
238
238
  // - effortOptionsFor(route): efforts of the selected model, prefixed with the
239
239
  // '跟随全局默认' empty option (the model's defaultEffort when absent).
240
- function useModelOptions(connection, agentDefaultScope) {
240
+ function useModelOptions(connection, agentDefaultScope, selectedRoute) {
241
241
  const [catalog, setCatalog] = useState(null); // { groups: [{id,name,models:[{id,name}]}] }
242
242
  const [efforts, setEfforts] = useState(null); // { efforts: [], defaultEffort } for the selected route
243
243
  const [effortRoute, setEffortRoute] = useState('');
@@ -274,32 +274,6 @@ window.__ModuleLoader__.load({
274
274
  return () => { alive = false; };
275
275
  }, [connection]);
276
276
 
277
- // Reasoning efforts are resolved lazily per selected route through
278
- // /memory-model-efforts (host resolveModelInfo), not embedded in the
279
- // catalog (that would be N host calls per mount).
280
- useEffect(() => {
281
- if (!connection || effortRoute === '') { setEfforts(null); return; }
282
- let alive = true;
283
- const load = async () => {
284
- try {
285
- const res = await connection.rpc.call('/api', 'memory-model-efforts/snapshot', { route: effortRoute });
286
- if (!alive) return;
287
- if (res && res.ok && res.value) {
288
- setEfforts(res.value);
289
- } else {
290
- setEfforts({ efforts: [], defaultEffort: undefined });
291
- }
292
- } catch (err) {
293
- if (alive) {
294
- console.error('[memory-lite] /memory-model-efforts failed:', err);
295
- setEfforts({ efforts: [], defaultEffort: undefined });
296
- }
297
- }
298
- };
299
- void load();
300
- return () => { alive = false; };
301
- }, [connection, effortRoute]);
302
-
303
277
  useEffect(() => {
304
278
  if (!agentDefaultScope) return undefined;
305
279
  return agentDefaultScope.subscribe(() => { force((n) => n + 1); });
@@ -311,6 +285,36 @@ window.__ModuleLoader__.load({
311
285
  const defModel = defValue ? defValue.model : undefined;
312
286
  const defRoute = (defProvider && defModel) ? defProvider + '/' + defModel : '';
313
287
 
288
+ // Reasoning efforts belong to one concrete model route. An empty
289
+ // selection means 跟随全局默认: that route IS the live global default
290
+ // model, so the dropdown must offer its efforts, not just the empty
291
+ // option (which is what the field hint already promises).
292
+ const selectedKey = typeof selectedRoute === 'string' ? selectedRoute : '';
293
+ const effortRouteTarget = selectedKey === '' ? defRoute : selectedKey;
294
+
295
+ // Resolved lazily per target route through /memory-model-efforts (host
296
+ // resolveModelInfo), not embedded in the catalog (N host calls/mount).
297
+ // effortRoute remembers which route the fetched `efforts` describe.
298
+ useEffect(() => {
299
+ if (!connection || effortRouteTarget === '') { setEfforts(null); setEffortRoute(''); return; }
300
+ let alive = true;
301
+ const load = async () => {
302
+ try {
303
+ const res = await connection.rpc.call('/api', 'memory-model-efforts/snapshot', { route: effortRouteTarget });
304
+ if (!alive) return;
305
+ setEffortRoute(effortRouteTarget);
306
+ setEfforts(res && res.ok && res.value ? res.value : { efforts: [], defaultEffort: undefined });
307
+ } catch (err) {
308
+ if (!alive) return;
309
+ console.error('[memory-lite] /memory-model-efforts failed:', err);
310
+ setEffortRoute(effortRouteTarget);
311
+ setEfforts({ efforts: [], defaultEffort: undefined });
312
+ }
313
+ };
314
+ void load();
315
+ return () => { alive = false; };
316
+ }, [connection, effortRouteTarget]);
317
+
314
318
  const routeOptions = [];
315
319
  if (defRoute !== '') {
316
320
  routeOptions.push(['', '跟随全局默认(当前:' + defRoute + ')']);
@@ -325,16 +329,13 @@ window.__ModuleLoader__.load({
325
329
  }
326
330
  }
327
331
 
328
- // For one selected route, expose its reasoning efforts. The efforts
329
- // were fetched lazily (see the effortRoute effect above) the last time
330
- // the route changed; selecting a route re-triggers that fetch.
331
- // Selected route drives the lazy efforts fetch (see the effortRoute
332
- // effect above). effortOptionsFor renders from the fetched efforts;
333
- // while the fetch is in flight only the default option shows.
334
- const selectRoute = (route) => { setEffortRoute(route || ''); };
332
+ // Options for the effort dropdown: the efforts of the route the value
333
+ // belongs to, where '' means the live global default model (resolved
334
+ // above). While that route's fetch is in flight only the default shows.
335
335
  const effortOptionsFor = (route) => {
336
336
  const opts = [['', '跟随全局默认']];
337
- if (!route || route === '' || route !== effortRoute) return opts;
337
+ const target = route === undefined || route === null || route === '' ? defRoute : String(route);
338
+ if (target === '' || target !== effortRoute) return opts;
338
339
  const list = (efforts && efforts.efforts) || [];
339
340
  for (const eff of list) {
340
341
  opts.push([eff.id, eff.name + (eff.description ? '(' + eff.description + ')' : '')]);
@@ -345,8 +346,11 @@ window.__ModuleLoader__.load({
345
346
  // A list is authoritative only once its fetch answered; until then a
346
347
  // stored value missing from the options is not yet known to be stale.
347
348
  const catalogReady = catalog !== null && !failed;
348
- const effortsReadyFor = (route) => route !== '' && route === effortRoute && efforts !== null;
349
- return { routeOptions, effortOptionsFor, selectRoute, failed, catalogReady, effortsReadyFor };
349
+ const effortsReadyFor = (route) => {
350
+ const target = route === undefined || route === null || route === '' ? defRoute : String(route);
351
+ return target !== '' && target === effortRoute && efforts !== null;
352
+ };
353
+ return { routeOptions, effortOptionsFor, failed, catalogReady, effortsReadyFor };
350
354
  }
351
355
 
352
356
  /* ---- 共享挂载 peer 列表 (16.9 补: 勾选式编辑) ---- */
@@ -444,12 +448,9 @@ window.__ModuleLoader__.load({
444
448
  : null;
445
449
  control = jsx('select', {
446
450
  value: String(shown ?? ''),
447
- onChange: (e) => {
448
- const next = e.target.value;
449
- // Selecting a model route re-targets the lazy efforts fetch.
450
- if (isRoute && modelOptions && modelOptions.selectRoute) modelOptions.selectRoute(next);
451
- onChange(key, next);
452
- },
451
+ // The lazy efforts fetch follows the selected route on its own
452
+ // (useModelOptions takes it as an argument), so nothing to re-target.
453
+ onChange: (e) => { onChange(key, e.target.value); },
453
454
  style: inputStyle,
454
455
  children: (resolved.options || []).map(([optValue, optLabel]) =>
455
456
  jsx('option', { value: optValue, children: optLabel, key: optValue })),
@@ -504,27 +505,26 @@ window.__ModuleLoader__.load({
504
505
  // Sharing-mount checkbox state: a Set of peer names checked for sharing.
505
506
  const [mountDraft, setMountDraft] = useState(null); // null = untouched
506
507
 
507
- const modelOptions = useModelOptions(connection, agentDefaultScope);
508
- const peerList = usePeerList(connection);
509
-
510
- useEffect(() => {
511
- if (!scope) return undefined;
512
- return scope.subscribe(() => { force((n) => n + 1); });
513
- }, [scope]);
514
-
515
508
  const snapshot = scope ? scope.getSnapshot() : null;
516
509
  const value = snapshot && snapshot.status === 'ready' ? snapshot.value : undefined;
517
510
  const writable = snapshot ? snapshot.writable : false;
518
511
 
519
- // Fetch the stored route's reasoning efforts on mount. Without this the
520
- // effort dropdown only offers 跟随全局默认 until the user re-picks the
521
- // route, which hides both the model's real efforts and a stale one.
512
+ // The route the effort dropdown belongs to: the staged edit wins, then
513
+ // the stored value. '' = 跟随全局默认, which useModelOptions resolves to
514
+ // the live default model for the efforts fetch.
515
+ const draftRoute = draft['extraction.llm.route'];
522
516
  const storedRoute = readPath(value, ['extraction', 'llm', 'route']);
523
- const storedRouteKey = typeof storedRoute === 'string' ? storedRoute : '';
517
+ const selectedRoute = draftRoute !== undefined
518
+ ? (typeof draftRoute === 'string' ? draftRoute : '')
519
+ : (typeof storedRoute === 'string' ? storedRoute : '');
520
+
521
+ const modelOptions = useModelOptions(connection, agentDefaultScope, selectedRoute);
522
+ const peerList = usePeerList(connection);
523
+
524
524
  useEffect(() => {
525
- if (storedRouteKey === '' || !modelOptions || !modelOptions.selectRoute) return;
526
- modelOptions.selectRoute(storedRouteKey);
527
- }, [storedRouteKey]);
525
+ if (!scope) return undefined;
526
+ return scope.subscribe(() => { force((n) => n + 1); });
527
+ }, [scope]);
528
528
 
529
529
  const setField = (key, val) => {
530
530
  setDraft((d) => ({ ...d, [key]: val }));
@@ -534,9 +534,15 @@ window.__ModuleLoader__.load({
534
534
 
535
535
  const fieldValue = (spec) => {
536
536
  const key = pathKey(spec.path);
537
- if (draft[key] !== undefined) return draft[key];
538
- const stored = readPath(value, spec.path);
539
- return stored !== undefined ? stored : DEFAULTS[key];
537
+ const fallback = DEFAULTS[key];
538
+ const chosen = draft[key] !== undefined ? draft[key] : readPath(value, spec.path);
539
+ if (chosen === undefined) return fallback;
540
+ // The host resolves an empty multicheck to its default
541
+ // (normalizeMessageScope: [] -> user+assistant), so the panel has to
542
+ // show that same selection — otherwise it renders "nothing checked"
543
+ // while the runtime keeps counting those kinds.
544
+ if (Array.isArray(chosen) && chosen.length === 0 && Array.isArray(fallback)) return fallback;
545
+ return chosen;
540
546
  };
541
547
 
542
548
  const save = async () => {
@@ -560,6 +566,11 @@ window.__ModuleLoader__.load({
560
566
  if (spec && (spec.type === 'text' || spec.type === 'dynamic-select') && (val === '' || val === null || val === undefined)) {
561
567
  return { op: 'unset', path };
562
568
  }
569
+ // An all-unchecked multicheck means "use the default" on the host,
570
+ // so persist an unset rather than an empty array in the document.
571
+ if (spec && spec.type === 'multicheck' && Array.isArray(val) && val.length === 0) {
572
+ return { op: 'unset', path };
573
+ }
563
574
  return { op: 'set', path, value: val };
564
575
  }).filter(Boolean);
565
576
  // Sharing mounts: write the whole array when the checkbox set changed.
package/package.json CHANGED
@@ -1,20 +1,32 @@
1
1
  {
2
2
  "name": "@alanzhao/dsh-memory-lite",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Lightweight zero-dependency memory plugin for DeepSeek Harness: Markdown-file memory store, L0 catalog injection, and 5 model-facing tools.",
5
5
  "keywords": [
6
6
  "dsh",
7
7
  "dsh-plugin",
8
8
  "memory",
9
+ "agent-memory",
10
+ "long-term-memory",
9
11
  "deepseek-harness"
10
12
  ],
11
13
  "type": "module",
12
14
  "main": "lib/index.js",
13
15
  "types": "lib/index.d.ts",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/alanzhao0128/dsh-memory-lite.git"
19
+ },
20
+ "homepage": "https://github.com/alanzhao0128/dsh-memory-lite#readme",
21
+ "bugs": {
22
+ "url": "https://github.com/alanzhao0128/dsh-memory-lite/issues"
23
+ },
14
24
  "files": [
15
25
  "lib",
16
26
  "cordis.patch.yml",
17
27
  "README.md",
28
+ "README.en.md",
29
+ "docs",
18
30
  "LICENSE"
19
31
  ],
20
32
  "license": "MIT",