icex-dsh-memory 0.0.0-stage → 0.2.0

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
@@ -1,3 +1,12 @@
1
- # Temporary Holding Version
1
+ # icex-dsh-memory
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cross-session memory for DeepSeek Harness, in one host plugin.
4
+
5
+ - **Injected once per session** — a budgeted digest of durable facts enters the context as an inbox message (`agent.inject`), so the system-prompt prefix stays stable and the model can see exactly which memories it received in the session log.
6
+ - **One tool, five actions** — `memory` with `add`, `replace`, `forget`, `search`, `list`.
7
+ - **Plain Markdown store** you can read, edit and version: `~/.dsh/memory/MEMORY.md` (global) and `<cwd>/.dsh/memory/MEMORY.md` (per working directory).
8
+ - **Provenance** — every entry carries `src=<session>@<seq>` and a date; memory is an index into the session log, never a replacement for it.
9
+ - **Self-maintaining** — on the first session after a week, the plugin merges near-duplicates and archives entries beyond the cap; nothing is deleted, and `memory consolidate` runs it on demand.
10
+ - **No dependencies** — the tool API is loaded from the running app; when it cannot be found the plugin still injects memory and the policy falls back to editing the file with the built-in filesystem tools.
11
+
12
+ See [docs/DETAIL.md](docs/DETAIL.md) for the store format, budgets, and known limits.
@@ -0,0 +1,4 @@
1
+ # One host row: prompt policy, the per-session digest injection, and the memory tool.
2
+ - insert:
3
+ - id: icex-dsh-memory
4
+ name: icex-dsh-memory
package/docs/DETAIL.md ADDED
@@ -0,0 +1,95 @@
1
+ # Icex DSH Memory
2
+
3
+ 给 DeepSeek Harness 加一层跨会话记忆。只做三件事:把事实存成可读的文件、在会话开始时注入一段有预算的摘要、给模型一个写入口。
4
+
5
+ ## 存储
6
+
7
+ 两个作用域,都是纯 Markdown,可以手改、可以进 git:
8
+
9
+ | 作用域 | 路径 | 用途 |
10
+ | --- | --- | --- |
11
+ | global | `~/.dsh/memory/MEMORY.md`(`$DSH_HOME` 优先) | 用户偏好、跨项目约定 |
12
+ | project | `<cwd>/.dsh/memory/MEMORY.md` | 只在这个工作目录生效的项目事实 |
13
+
14
+ 一行一条:
15
+
16
+ ```
17
+ - [pref] 回答要结论先行,不要铺垫 <!-- id=4c1a2b src=session-5f0adb65@42 at=2026-11-20 -->
18
+ ```
19
+
20
+ - `kind`:`pref` / `project` / `pitfall` / `decision` / `tool`
21
+ - `id`:由内容与日期派生的 6 位短 id,`replace` / `forget` 用它定位
22
+ - `src`:产生这条事实的会话与事件序号;记忆指回原始日志,冲突时以日志为准
23
+ - `at`:写入日期
24
+
25
+ `add` 会做一次近似查重(同作用域、词集 Jaccard ≥ 0.85),命中时返回已有条目而不是新增;`replace` / `forget` 按行原地修改,文件里其他手写内容保持不动。
26
+
27
+ ## 注入
28
+
29
+ 每次 agent 创建时(`agent/created`)读取两个作用域,拼成一条 `<memory-context>` 消息,通过 `agent.inject` 放进收件箱:
30
+
31
+ - 只注入一次,不随每步变化;不动系统提示前缀,避免打掉 provider 的 KV cache
32
+ - 作为 `agent/inbox/spliced` 事件进日志,可在会话里回看"这次到底给了模型哪些记忆"
33
+ - 预算:全局 620 字符 / 项目 1000 字符,各取最近 8 / 12 条;装不下的条目收起并显式写"…N more",不静默截断
34
+ - 内容为空的会话不注入
35
+
36
+ ## 工具
37
+
38
+ `memory`,一个工具五个 action:
39
+
40
+ | action | 参数 | 行为 |
41
+ | --- | --- | --- |
42
+ | `add` | `text`, `kind`, `scope` | 查重后追加一行,带 `src` 与日期 |
43
+ | `replace` | `id`, `text`, `kind` | 原地替换该条 |
44
+ | `forget` | `id` | 删除该条 |
45
+ | `search` | `query`, `scope` | 本地词集打分,返回最多 10 条 |
46
+ | `list` | `scope` | 最近 20 条 |
47
+
48
+ 写入约束:单条 ≤200 字符、拒绝疑似密钥(`sk-…`、`token=`、私钥等)、`add` 自动查重。文件写入走"临时文件 + rename",避免并发写坏。
49
+
50
+ ## 整理(自动 + 手动)
51
+
52
+ 插件自己完成,不依赖任何定时器或后台进程:**每次会话开始检查一次**,距上次整理超过 `consolidateIntervalDays`(默认 7 天)就顺手跑一遍。
53
+
54
+ 整理只做两件确定性的事,不调用模型、不删除内容:
55
+
56
+ 1. **合并近似重复**:同一作用域内相似度 ≥ `dedupeSimilarity`(默认 0.85)的条目只留一条,被合并的进归档。
57
+ 2. **控制条数**:单作用域超过 `maxEntries`(默认 60)时,最旧的条目移进 `MEMORY.archive.md`,不是删掉。
58
+
59
+ 被移走的条目全部写在同目录的 `MEMORY.archive.md` 里,随时可以捞回来。运行结果记录在 `~/.dsh/memory/.state.json`(上次时间 + 本次报告),并用 `.consolidate.lock` 防止两个会话同时整理。
60
+
61
+ 想立刻整理就调工具:`memory` + `action: consolidate`,返回合并和被归档的条数。
62
+
63
+ 可调参数(写在 bundle 的 config 里,全部可选):
64
+
65
+ | 字段 | 默认 | 含义 |
66
+ | --- | --- | --- |
67
+ | `consolidateIntervalDays` | `7` | 两次自动整理的最小间隔天数 |
68
+ | `maxEntries` | `60` | 每个作用域保留的最大条数,超出部分归档 |
69
+ | `dedupeSimilarity` | `0.85` | 判定重复的相似度阈值(0.5–0.99) |
70
+
71
+
72
+ ## 安装
73
+
74
+ ```sh
75
+ cd ~/codes/icex-dsh-memory
76
+ # 在 Plugins 里用本地目录安装,或把该目录作为一个 bundle 加进 profile 的 dsh.profile.bundles
77
+ ```
78
+
79
+ 插件自行从运行中的 app 里加载 `@deepseek-ai/dsh-tools`;通过 `link:` 安装也不需要在本仓库跑 `pnpm install`。找不到时降级为"只注入 + 用文件工具编辑",不会报错中断会话。
80
+
81
+ ## 验证
82
+
83
+ 1. 新开一个会话,问"你的记忆里有我吗"——应能看到注入的摘要(也可在会话日志里找 `agent/inbox/spliced`)。
84
+ 2. 说一条长期偏好,确认模型调用 `memory add`;检查 `~/.dsh/memory/MEMORY.md` 多了一行带 `src` 的条目。
85
+ 3. 再开一个新会话,确认该条目出现在开场摘要里。
86
+ 4. 说"这条不用了",确认走 `forget` 或 `replace`,文件里对应行消失或更新。
87
+ 5. 用 context 面板对比:注入 token 应 ≤ 1.5k;同一会话多轮之间 `cacheRead` 不应因记忆抖动。
88
+
89
+ ## 已知边界
90
+
91
+ - **只注入一次**:同一会话内新增的记忆不会中途重新注入,下个会话才生效(这是为了缓存稳定)。
92
+ - **不做 LLM 蒸馏**:什么时候写由模型判断,整理只做确定性的去重与归档,不改写措辞、不调用模型;检索也是词集打分,没有 embedding。
93
+ - **不做向量召回**:需要原始对话细节时,用官方 opt-in 的 `dsh-tool-session-query`(`session_search`,作用域为 cwd 完全相同)。
94
+ - **project 作用域按工作目录精确匹配**:在子目录开新会话不会继承父目录的项目记忆。
95
+ - 超过预算的旧条目不会自动淘汰,只是不进入摘要;需要长期维护时手动 `list` + `forget`。
package/icon.svg ADDED
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
2
+ <rect x="6" y="10" width="52" height="44" rx="8" fill="none" stroke="#4B5563" stroke-width="3"/>
3
+ <path d="M16 24h32M16 34h24M16 44h28" stroke="#4B5563" stroke-width="3" stroke-linecap="round"/>
4
+ <circle cx="50" cy="44" r="7" fill="#4B5563"/>
5
+ </svg>
package/index.js ADDED
@@ -0,0 +1,590 @@
1
+ /**
2
+ * icex-dsh-memory — cross-session memory for DeepSeek Harness.
3
+ *
4
+ * Two halves, both host-side:
5
+ * 1. A budgeted digest of durable facts is injected once per agent as an inbox
6
+ * message (`agent.inject`), so it never disturbs the system-prompt prefix and
7
+ * stays visible in the session log.
8
+ * 2. A `memory` tool reads and writes those facts, one line per fact, with a
9
+ * provenance pointer back to the session that produced it.
10
+ *
11
+ * The store is plain Markdown the user can edit by hand:
12
+ * ~/.dsh/memory/MEMORY.md global facts
13
+ * <cwd>/.dsh/memory/MEMORY.md project facts (same working directory)
14
+ *
15
+ * Format, one entry per line:
16
+ * - [pref] Answer conclusions first. <!-- id=m7k2 src=session-abc@42 at=2026-11-20 -->
17
+ *
18
+ * `@deepseek-ai/dsh-tools` is optional: when it resolves, the model gets the
19
+ * `memory` tool; when it does not, the policy falls back to editing the file
20
+ * with the built-in filesystem tools.
21
+ */
22
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, statSync } from 'node:fs'
23
+ import { createHash } from 'node:crypto'
24
+ import { homedir } from 'node:os'
25
+ import { dirname, join } from 'node:path'
26
+ import { pathToFileURL } from 'node:url'
27
+
28
+ export const name = 'icex-dsh-memory'
29
+ export const inject = ['systemPrompt', 'tools']
30
+
31
+ /** Absolute directory of the global memory store. */
32
+ export const HOME = process.env.DSH_HOME && process.env.DSH_HOME !== ''
33
+ ? join(process.env.DSH_HOME, 'memory')
34
+ : join(homedir(), '.dsh', 'memory')
35
+
36
+ const KINDS = ['pref', 'project', 'pitfall', 'decision', 'tool']
37
+ const GLOBAL_FILE = join(HOME, 'MEMORY.md')
38
+ const STATE_FILE = join(HOME, '.state.json')
39
+ const LOCK_FILE = join(HOME, '.consolidate.lock')
40
+ const CONSOLIDATE = { intervalDays: 7, maxEntries: 60, dedupe: 0.85 }
41
+ const ENTRY_RE = /^- \[([a-z]+)\] (.+?)(?: <!-- id=([0-9a-z]+) src=(\S+) at=([0-9-]+) -->)?$/u
42
+ const MAX_TEXT = 200
43
+ const BUDGET = { global: 1000, project: 1200 }
44
+ const TAKE = { global: 12, project: 12 }
45
+
46
+ /** A single durable fact. */
47
+ export function makeEntry(text, kind, src) {
48
+ const trimmed = String(text).trim().replace(/\s+/g, ' ')
49
+ if (trimmed === '') throw new Error('memory text is empty')
50
+ if (trimmed.length > MAX_TEXT) throw new Error('memory text exceeds ' + MAX_TEXT + ' characters')
51
+ if (!KINDS.includes(kind)) throw new Error('unknown memory kind: ' + kind)
52
+ if (looksSecret(trimmed)) throw new Error('refusing to store something that looks like a secret')
53
+ const at = new Date().toISOString().slice(0, 10)
54
+ const id = createHash('sha256').update(trimmed + '\u0000' + at).digest('hex').slice(0, 6)
55
+ return { id, kind, text: trimmed, src: src === '' ? 'manual' : src, at }
56
+ }
57
+
58
+ /** Cheap secret screen: never persist credentials. */
59
+ export function looksSecret(text) {
60
+ return /(sk-[A-Za-z0-9]{8,}|ghp_[A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|-----BEGIN [A-Z ]*PRIVATE KEY|(?:password|passwd|api[_-]?key|token|secret)\s*[:=]\s*\S{4,})/i.test(text)
61
+ }
62
+
63
+ /** Render one entry as a store line. */
64
+ export function formatEntry(entry) {
65
+ return '- [' + entry.kind + '] ' + entry.text + ' <!-- id=' + entry.id + ' src=' + entry.src + ' at=' + entry.at + ' -->'
66
+ }
67
+
68
+ /** Parse store text into entries, keeping unrelated user prose out of the way. */
69
+ export function parseEntries(text) {
70
+ const entries = []
71
+ for (const line of String(text).split('\n')) {
72
+ const match = ENTRY_RE.exec(line.trim())
73
+ if (match === null) continue
74
+ entries.push({
75
+ id: match[3] === undefined ? '' : match[3],
76
+ kind: match[1],
77
+ text: match[2].trim(),
78
+ src: match[4] === undefined ? '' : match[4],
79
+ at: match[5] === undefined ? '' : match[5],
80
+ })
81
+ }
82
+ return entries
83
+ }
84
+
85
+ /** Read a store file, returning entries and the raw line array. */
86
+ export function readStore(file) {
87
+ if (!existsSync(file)) return { entries: [], lines: [] }
88
+ const text = readFileSync(file, 'utf8')
89
+ return { entries: parseEntries(text), lines: text.split('\n') }
90
+ }
91
+
92
+ /** Write a file atomically (tmp beside the target, then rename). */
93
+ function writeAtomic(file, text) {
94
+ mkdirSync(dirname(file), { recursive: true })
95
+ const tmp = file + '.tmp-' + process.pid + '-' + Date.now()
96
+ writeFileSync(tmp, text, 'utf8')
97
+ renameSync(tmp, file)
98
+ }
99
+
100
+ /** Append one entry, preserving any prose the user keeps in the file. */
101
+ export function appendEntry(file, entry) {
102
+ const { lines } = readStore(file)
103
+ const body = lines.length === 0 ? [] : lines.slice()
104
+ while (body.length > 0 && body[body.length - 1].trim() === '') body.pop()
105
+ body.push(formatEntry(entry), '')
106
+ writeAtomic(file, body.join('\n'))
107
+ }
108
+
109
+ /** Replace the entry with this id, in place. */
110
+ export function replaceEntry(file, id, entry) {
111
+ const { lines } = readStore(file)
112
+ const index = lines.findIndex((line) => {
113
+ const match = ENTRY_RE.exec(line.trim())
114
+ return match !== null && match[3] === id
115
+ })
116
+ if (index < 0) return false
117
+ lines[index] = formatEntry({ ...entry, id })
118
+ writeAtomic(file, lines.join('\n'))
119
+ return true
120
+ }
121
+
122
+ /** Remove the entry with this id. */
123
+ export function forgetEntry(file, id) {
124
+ const { lines } = readStore(file)
125
+ const index = lines.findIndex((line) => {
126
+ const match = ENTRY_RE.exec(line.trim())
127
+ return match !== null && match[3] === id
128
+ })
129
+ if (index < 0) return false
130
+ lines.splice(index, 1)
131
+ writeAtomic(file, lines.join('\n'))
132
+ return true
133
+ }
134
+
135
+ /** Sidecar state: when consolidation last ran and what it did. */
136
+ export function readState() {
137
+ try {
138
+ const raw = readFileSync(STATE_FILE, 'utf8')
139
+ const parsed = JSON.parse(raw)
140
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
141
+ } catch (error) {
142
+ return {}
143
+ }
144
+ }
145
+
146
+ /** Persist sidecar state atomically; a failure here must not break a session. */
147
+ function writeState(state) {
148
+ try {
149
+ writeAtomic(STATE_FILE, JSON.stringify(state, null, 2) + '\n')
150
+ } catch (error) {
151
+ // State is a cache of the last run, not a source of truth.
152
+ }
153
+ }
154
+
155
+ /** Archive path paired with a store file: MEMORY.md -> MEMORY.archive.md. */
156
+ export function archivePath(file) {
157
+ return file.replace(/\.md$/u, '.archive.md')
158
+ }
159
+
160
+ /** Append removed entries to the archive instead of deleting them. */
161
+ function appendArchive(file, entries) {
162
+ if (entries.length === 0) return
163
+ const target = archivePath(file)
164
+ mkdirSync(dirname(target), { recursive: true })
165
+ const existing = existsSync(target) ? readFileSync(target, 'utf8') : '# Archived memory: merged duplicates and entries beyond the cap\n'
166
+ writeAtomic(target, existing.replace(/\n*$/u, '\n') + entries.map(formatEntry).join('\n') + '\n')
167
+ }
168
+
169
+ /** Keep only the given entry ids; user prose and unknown lines survive. */
170
+ export function rewriteEntries(file, keepIds) {
171
+ const { lines } = readStore(file)
172
+ const kept = lines.filter((line) => {
173
+ const match = ENTRY_RE.exec(line.trim())
174
+ if (match === null) return true
175
+ if (match[3] === undefined) return true
176
+ return keepIds.has(match[3])
177
+ })
178
+ writeAtomic(file, kept.join('\n'))
179
+ }
180
+
181
+ /**
182
+ * Deterministic consolidation: merge near-duplicates (keeping the newer entry)
183
+ * and move entries beyond the cap to the archive. No model call, nothing deleted.
184
+ */
185
+ export function consolidateFile(file, options) {
186
+ const opts = { ...CONSOLIDATE, ...options }
187
+ const { entries } = readStore(file)
188
+ if (entries.length === 0) return { file, before: 0, kept: 0, merged: 0, archived: 0 }
189
+ const kept = []
190
+ const removed = []
191
+ for (const entry of entries) {
192
+ const index = kept.findIndex((candidate) => similarity(candidate.text, entry.text) >= opts.dedupe)
193
+ if (index < 0) {
194
+ kept.push(entry)
195
+ continue
196
+ }
197
+ const twin = kept[index]
198
+ if ((entry.at || '') > (twin.at || '')) {
199
+ removed.push(twin)
200
+ kept[index] = entry
201
+ } else {
202
+ removed.push(entry)
203
+ }
204
+ }
205
+ const overflow = kept.length > opts.maxEntries ? kept.slice(0, kept.length - opts.maxEntries) : []
206
+ const final = kept.slice(overflow.length)
207
+ if (removed.length > 0 || overflow.length > 0) {
208
+ rewriteEntries(file, new Set(final.map((entry) => entry.id)))
209
+ appendArchive(file, removed.concat(overflow))
210
+ }
211
+ return { file, before: entries.length, kept: final.length, merged: removed.length, archived: overflow.length }
212
+ }
213
+
214
+ /** Skip if another session is consolidating right now. */
215
+ function acquireLock() {
216
+ try {
217
+ const info = existsSync(LOCK_FILE) ? statSync(LOCK_FILE) : null
218
+ if (info !== null && Date.now() - info.mtimeMs < 10 * 60 * 1000) return false
219
+ if (info !== null) rmSync(LOCK_FILE, { force: true })
220
+ writeFileSync(LOCK_FILE, String(process.pid), { flag: 'wx' })
221
+ return true
222
+ } catch (error) {
223
+ return false
224
+ }
225
+ }
226
+
227
+ function releaseLock() {
228
+ try {
229
+ rmSync(LOCK_FILE, { force: true })
230
+ } catch (error) {
231
+ // A stale lock expires on its own.
232
+ }
233
+ }
234
+
235
+ /** Run consolidation when the interval elapsed; returns the report or null. */
236
+ export function maybeConsolidate(cwd, options) {
237
+ const opts = { ...CONSOLIDATE, ...options }
238
+ const state = readState()
239
+ const last = Date.parse(typeof state.lastConsolidatedAt === 'string' ? state.lastConsolidatedAt : '')
240
+ if (Number.isFinite(last) && Date.now() - last < opts.intervalDays * 24 * 60 * 60 * 1000) return null
241
+ if (!acquireLock()) return null
242
+ try {
243
+ const files = [GLOBAL_FILE]
244
+ const project = projectFile(cwd)
245
+ if (project !== null) files.push(project)
246
+ const report = files.filter((file) => existsSync(file)).map((file) => consolidateFile(file, opts))
247
+ if (report.length === 0) return null
248
+ writeState({
249
+ ...state,
250
+ lastConsolidatedAt: new Date().toISOString(),
251
+ lastReport: report,
252
+ })
253
+ return report
254
+ } finally {
255
+ releaseLock()
256
+ }
257
+ }
258
+
259
+ /** Token set used by the duplicate screen and the local search ranking. */
260
+ function tokens(text) {
261
+ return new Set(String(text).toLowerCase().split(/[^a-z0-9\u4e00-\u9fff]+/u).filter((part) => part.length > 0))
262
+ }
263
+
264
+ /** Jaccard similarity of two facts, used to refuse near-duplicates. */
265
+ export function similarity(left, right) {
266
+ const a = tokens(left)
267
+ const b = tokens(right)
268
+ if (a.size === 0 || b.size === 0) return 0
269
+ let shared = 0
270
+ for (const token of a) if (b.has(token)) shared += 1
271
+ return shared / (a.size + b.size - shared)
272
+ }
273
+
274
+ /** Rank entries against a query; an empty query lists newest first. */
275
+ export function searchEntries(entries, query, limit) {
276
+ const needle = tokens(query)
277
+ const literal = String(query).trim().toLowerCase()
278
+ const scored = entries.map((entry, index) => {
279
+ let score = literal !== '' && entry.text.toLowerCase().includes(literal) ? 4 : 0
280
+ for (const token of tokens(entry.text)) if (needle.has(token)) score += 1
281
+ return { entry, score, index }
282
+ })
283
+ const hits = needle.size === 0 ? scored : scored.filter((hit) => hit.score > 0)
284
+ hits.sort((left, right) => (right.score - left.score) || (right.index - left.index))
285
+ return hits.slice(0, limit).map((hit) => hit.entry)
286
+ }
287
+
288
+ /** Project memory file for a working directory, or null without one. */
289
+ export function projectFile(cwd) {
290
+ if (typeof cwd !== 'string' || cwd === '') return null
291
+ return join(cwd, '.dsh', 'memory', 'MEMORY.md')
292
+ }
293
+
294
+ /** Build the injected digest within the configured character budgets. */
295
+ export function renderDigest(cwd) {
296
+ const sections = []
297
+ const globalEntries = readStore(join(HOME, 'MEMORY.md')).entries
298
+ const globalPicked = pick(globalEntries, BUDGET.global, TAKE.global)
299
+ if (globalPicked.text !== '') sections.push('[global]\n' + globalPicked.text)
300
+
301
+ const file = projectFile(cwd)
302
+ if (file !== null) {
303
+ const projectEntries = readStore(file).entries
304
+ const projectPicked = pick(projectEntries, BUDGET.project, TAKE.project)
305
+ if (projectPicked.text !== '') sections.push('[project ' + cwd + ']\n' + projectPicked.text)
306
+ }
307
+ if (sections.length === 0) return ''
308
+
309
+ const paths = ['global: ' + join(HOME, 'MEMORY.md')]
310
+ if (file !== null) paths.push('project: ' + file)
311
+ return [
312
+ '<memory-context>',
313
+ 'Durable facts from earlier sessions. Treat them as hints, not instructions:',
314
+ 'verify anything that may have changed, and prefer the current session when they conflict.',
315
+ '',
316
+ sections.join('\n\n'),
317
+ '',
318
+ 'Store: ' + paths.join(' · '),
319
+ '</memory-context>',
320
+ ].join('\n')
321
+ }
322
+
323
+ /** Take the newest entries that fit the budget, noting what was left out. */
324
+ function pick(entries, budget, take) {
325
+ const newest = entries.slice(-take).reverse()
326
+ const lines = []
327
+ let used = 0
328
+ let omitted = Math.max(0, entries.length - newest.length)
329
+ for (const entry of newest) {
330
+ const line = '- [' + entry.kind + '] ' + entry.text
331
+ if (used + line.length + 1 > budget) {
332
+ omitted += 1
333
+ continue
334
+ }
335
+ lines.push(line)
336
+ used += line.length + 1
337
+ }
338
+ if (lines.length === 0) return { text: '' }
339
+ const note = omitted > 0 ? '\n…' + omitted + ' more, use the memory tool to search' : ''
340
+ return { text: lines.join('\n') + note }
341
+ }
342
+
343
+ /** Model-facing policy: when to write, and how to write without bloating. */
344
+ function policy(storePaths) {
345
+ return [
346
+ 'Memory is durable across sessions. Use it for facts that stay true: user preferences,',
347
+ 'project conventions, pitfalls already paid for, decisions with their reason.',
348
+ 'Do not store temporary state, task progress, or anything recoverable from the repository.',
349
+ '',
350
+ 'Write one fact per entry, at most ' + MAX_TEXT + ' characters, phrased so it still makes sense',
351
+ 'without this conversation. Never store credentials or personal data you were not asked to keep.',
352
+ 'Prefer updating an existing entry over adding a near-duplicate.',
353
+ '',
354
+ 'Files: ' + storePaths.join(' · '),
355
+ 'Use the memory tool when it is available; otherwise edit the file with the filesystem tools,',
356
+ 'one "- [kind] fact <!-- id=… src=… at=… -->" line per entry.',
357
+ ].join('\n')
358
+ }
359
+
360
+ /** Resolve the session working directory, falling back to the process cwd. */
361
+ async function workingDirectory(ctx, agent, signal) {
362
+ try {
363
+ if (agent !== undefined && ctx.workingDirectory !== undefined) {
364
+ const dir = await ctx.workingDirectory.ensure(agent, signal)
365
+ if (typeof dir === 'string' && dir !== '') return dir
366
+ }
367
+ } catch (error) {
368
+ // A session without a working directory still gets global memory.
369
+ }
370
+ return process.cwd()
371
+ }
372
+
373
+ /** Session-scoped provenance pointer for a fact. */
374
+ function provenance(exec) {
375
+ const session = exec?.agent?.session
376
+ const id = session?.header?.id ?? session?.id
377
+ const seq = session?.events?.at?.(-1)?.seq
378
+ return (typeof id === 'string' && id !== '' ? id : 'unknown') + (typeof seq === 'number' ? '@' + seq : '')
379
+ }
380
+
381
+ /** Load the harness tool API, from the profile or from the running app bundle. */
382
+ async function loadTools() {
383
+ try {
384
+ return await import('@deepseek-ai/dsh-tools')
385
+ } catch (error) {
386
+ // A link: installed plugin has no node_modules of its own; use the app copy.
387
+ }
388
+ const resources = process.resourcesPath
389
+ if (typeof resources === 'string' && resources !== '') {
390
+ const candidate = join(resources, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-tools', 'lib', 'index.js')
391
+ if (existsSync(candidate)) {
392
+ try {
393
+ return await import(pathToFileURL(candidate).href)
394
+ } catch (error) {
395
+ return null
396
+ }
397
+ }
398
+ }
399
+ return null
400
+ }
401
+
402
+ /** Harness tool API resolved once at load: the app copy when the plugin has none. */
403
+ const TOOLS = await loadTools()
404
+
405
+ /** Merge row config over the built-in consolidation defaults. */
406
+ function tuningOf(config) {
407
+ const source = config !== null && typeof config === 'object' ? config : {}
408
+ const pick = (value, fallback, min, max) => {
409
+ const number = typeof value === 'number' ? value : Number(value)
410
+ if (!Number.isFinite(number)) return fallback
411
+ return Math.min(max, Math.max(min, number))
412
+ }
413
+ return {
414
+ intervalDays: pick(source.consolidateIntervalDays, CONSOLIDATE.intervalDays, 1, 365),
415
+ maxEntries: pick(source.maxEntries, CONSOLIDATE.maxEntries, 5, 1000),
416
+ dedupe: pick(source.dedupeSimilarity, CONSOLIDATE.dedupe, 0.5, 0.99),
417
+ }
418
+ }
419
+
420
+ /** Apply the plugin: one prompt section, one injection, optionally one tool. */
421
+ export function apply(ctx, config) {
422
+ const tuning = tuningOf(config)
423
+ const globalFile = GLOBAL_FILE
424
+
425
+ ctx.systemPrompt.section({
426
+ name: 'tool:memory',
427
+ order: 900,
428
+ text: policy([globalFile, '<cwd>/.dsh/memory/MEMORY.md']),
429
+ })
430
+
431
+ ctx.on('agent/created', (payload) => {
432
+ const agent = payload?.agent ?? payload
433
+ if (agent === undefined || typeof agent.inject !== 'function') return
434
+ void (async () => {
435
+ try {
436
+ const cwd = await workingDirectory(ctx, agent)
437
+ try {
438
+ const report = maybeConsolidate(cwd, tuning)
439
+ if (report !== null) {
440
+ const merged = report.reduce((total, item) => total + item.merged, 0)
441
+ const archived = report.reduce((total, item) => total + item.archived, 0)
442
+ ctx.logger?.info?.('icex-dsh-memory: consolidated, merged ' + merged + ', archived ' + archived)
443
+ }
444
+ } catch (error) {
445
+ ctx.logger?.warn?.('icex-dsh-memory: consolidation failed: ' + String(error))
446
+ }
447
+ const text = renderDigest(cwd)
448
+ if (text === '') return
449
+ agent.inject({ content: [{ type: 'text', text }], source: { kind: 'icex-memory' } })
450
+ } catch (error) {
451
+ ctx.logger?.warn?.('icex-dsh-memory: digest injection failed: ' + String(error))
452
+ }
453
+ })()
454
+ })
455
+
456
+ if (TOOLS === null || typeof TOOLS.defineTool !== 'function') {
457
+ ctx.logger?.info?.('icex-dsh-memory: dsh-tools unavailable; file-edit memory policy only')
458
+ return
459
+ }
460
+ if (ctx.tools === undefined) return
461
+ registerTool(ctx, TOOLS.defineTool, tuning)
462
+ }
463
+
464
+ /** Register the single `memory` tool backed by the Markdown stores. */
465
+ function registerTool(ctx, defineTool, tuning) {
466
+ const output = {
467
+ schema: {
468
+ type: 'object',
469
+ additionalProperties: false,
470
+ properties: {
471
+ ok: { type: 'boolean' },
472
+ action: { type: 'string' },
473
+ duplicateOf: { type: 'string' },
474
+ reason: { type: 'string' },
475
+ entries: {
476
+ type: 'array',
477
+ items: {
478
+ type: 'object',
479
+ additionalProperties: false,
480
+ properties: {
481
+ id: { type: 'string' },
482
+ kind: { type: 'string' },
483
+ text: { type: 'string' },
484
+ src: { type: 'string' },
485
+ scope: { type: 'string' },
486
+ },
487
+ },
488
+ },
489
+ },
490
+ },
491
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
492
+ }
493
+
494
+ ctx.tools.register(defineTool({
495
+ name: 'memory',
496
+ description:
497
+ 'Read and write durable cross-session facts: user preferences, project conventions, pitfalls, '
498
+ + 'and decisions. Entries live in a Markdown store (global and per-working-directory) and are '
499
+ + 'injected automatically at the start of later sessions. Use search before adding, so facts '
500
+ + 'are updated rather than duplicated.',
501
+ parameters: {
502
+ action: {
503
+ type: 'string',
504
+ required: true,
505
+ enum: ['add', 'replace', 'forget', 'search', 'list', 'consolidate'],
506
+ description: 'add, replace, forget, search, list, or consolidate (merge duplicates and archive overflow).',
507
+ },
508
+ scope: {
509
+ type: 'string',
510
+ enum: ['global', 'project'],
511
+ description: 'global facts apply everywhere; project facts apply to this working directory only. Default global.',
512
+ },
513
+ kind: {
514
+ type: 'string',
515
+ enum: KINDS,
516
+ description: 'Fact category: pref, project, pitfall, decision, or tool.',
517
+ },
518
+ text: {
519
+ type: 'string',
520
+ description: 'The fact, at most ' + MAX_TEXT + ' characters, understandable without this conversation.',
521
+ },
522
+ id: {
523
+ type: 'string',
524
+ description: 'Entry id, required for replace and forget.',
525
+ },
526
+ query: {
527
+ type: 'string',
528
+ description: 'Search words; omit to list the newest entries.',
529
+ },
530
+ },
531
+ output,
532
+ async execute(args, exec) {
533
+ const cwd = await workingDirectory(ctx, exec?.agent, exec?.signal)
534
+ const scope = args.scope === 'project' ? 'project' : 'global'
535
+ const file = scope === 'project' ? projectFile(cwd) : GLOBAL_FILE
536
+ if (file === null) return { ok: false, action: args.action, entries: [] }
537
+ const { entries } = readStore(file)
538
+
539
+ if (args.action === 'consolidate') {
540
+ const files = [GLOBAL_FILE]
541
+ const project = projectFile(cwd)
542
+ if (project !== null) files.push(project)
543
+ const report = files.filter((item) => existsSync(item)).map((item) => consolidateFile(item, tuning))
544
+ writeState({ ...readState(), lastConsolidatedAt: new Date().toISOString(), lastReport: report, manual: true })
545
+ const merged = report.reduce((total, item) => total + item.merged, 0)
546
+ const archived = report.reduce((total, item) => total + item.archived, 0)
547
+ return { ok: true, action: 'consolidate', reason: 'merged ' + merged + ', archived ' + archived, entries: [] }
548
+ }
549
+ if (args.action === 'list') {
550
+ return { ok: true, action: 'list', entries: searchEntries(entries, '', 20).map((entry) => view(entry, scope)) }
551
+ }
552
+ if (args.action === 'search') {
553
+ return { ok: true, action: 'search', entries: searchEntries(entries, args.query ?? '', 10).map((entry) => view(entry, scope)) }
554
+ }
555
+ if (args.action === 'forget') {
556
+ if (typeof args.id !== 'string' || args.id === '') return { ok: false, action: 'forget', entries: [] }
557
+ return { ok: forgetEntry(file, args.id), action: 'forget', entries: [] }
558
+ }
559
+ if (args.action === 'replace') {
560
+ if (typeof args.id !== 'string' || args.id === '') return { ok: false, action: 'replace', reason: 'id is required', entries: [] }
561
+ let replacement
562
+ try {
563
+ replacement = makeEntry(args.text, args.kind ?? 'pref', provenance(exec))
564
+ } catch (error) {
565
+ return { ok: false, action: 'replace', reason: String(error.message ?? error), entries: [] }
566
+ }
567
+ return { ok: replaceEntry(file, args.id, replacement), action: 'replace', entries: [view(replacement, scope)] }
568
+ }
569
+
570
+ let entry
571
+ try {
572
+ entry = makeEntry(args.text, args.kind ?? 'pref', provenance(exec))
573
+ } catch (error) {
574
+ return { ok: false, action: 'add', reason: String(error.message ?? error), entries: [] }
575
+ }
576
+ const twin = entries.find((existing) => similarity(existing.text, entry.text) >= 0.85)
577
+ if (twin !== undefined) {
578
+ return { ok: false, action: 'add', duplicateOf: twin.id, entries: [view(twin, scope)] }
579
+ }
580
+ appendEntry(file, entry)
581
+ return { ok: true, action: 'add', entries: [view(entry, scope)] }
582
+ },
583
+ presentCall: (args) => ({ card: 'generic', title: 'Memory: ' + args.action, kind: 'other' }),
584
+ }))
585
+ }
586
+
587
+ /** Compact tool-facing projection of an entry. */
588
+ function view(entry, scope) {
589
+ return { id: entry.id, kind: entry.kind, text: entry.text, src: entry.src, scope }
590
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Icex DSH Memory",
4
+ "description": "Cross-session memory: a budgeted digest injected at session start, plus a memory tool that keeps facts in a Markdown store with provenance.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Icex DSH Memory",
4
+ "description": "跨会话记忆:会话开始注入一段有预算的摘要,并用一个 memory 工具把事实写进带来源的 Markdown 存储。",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "icex-dsh-memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "description": "Cross-session memory for DeepSeek Harness: a budgeted MEMORY.md digest injected once per session, plus one memory tool with provenance back to the producing session.",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./locale/*.json": "./locale/*.json",
9
+ "./icon": "./icon.svg"
10
+ },
11
+ "files": [
12
+ "index.js",
13
+ "cordis.patch.yml",
14
+ "locale/*.json",
15
+ "docs",
16
+ "icon.svg",
17
+ "README.md"
18
+ ],
19
+ "dsh": {
20
+ "bundle": {
21
+ "patch": "./cordis.patch.yml"
22
+ }
23
+ },
24
+ "license": "MIT",
25
+ "publishConfig": {
26
+ "access": "public",
27
+ "registry": "https://registry.npmjs.org/"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/icexxxxxx/dsh-plugins.git",
32
+ "directory": "packages/memory"
33
+ },
34
+ "keywords": [
35
+ "deepseek-harness",
36
+ "dsh-plugin",
37
+ "dsh"
38
+ ]
39
+ }