dsh-memory-garden 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 泡泡
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # dsh-memory-garden · 记忆花园
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
+ 给 DeepSeek Harness 用的**自生长记忆**插件。
4
+
5
+ 骨架默认是空的,靠聊天慢慢长出三块档案——**关于你 / 关于我 / 我们之间**。所有数据都是工作区里的 md / json:能读、能手改、能拷走,换机器也不丢。
6
+
7
+ ## 它做什么
8
+
9
+ 1. **铺骨架**:`memory_init` 或 `/memory init`,建好
10
+ ```
11
+ 记忆花园/
12
+ 人设.md 手写:名字、自称、语气
13
+ 档案.json 自生长:关于你 / 关于我 / 我们之间
14
+ 存档.md 世界观:稳定 / 在变
15
+ 交接.md 换会话时写「手上在做什么」;压缩前插件会追一条机械快照
16
+ 日记/ 一天一篇
17
+ 原文/ 会话原文(可选,自己往里放)
18
+ 索引.json 日记标签
19
+ 纠错.md 用户纠正过你的原话
20
+ 状态.json 积压计数(自动维护)
21
+ ```
22
+ 2. **开局索引**:每轮注入一小块状态——档案几条、日记几篇、积压多少、今天写没写。不塞全文。
23
+ 3. **自生长**:积压到阈值(默认 20 条)时,索引里会提示「攒够了」,模型用 `memory_grow` 把新认识写进档案;写完积压自动清零。
24
+ 4. **压缩前落款**:会话压缩时往 `交接.md` 追加一条机械快照,**不覆盖**人写的那份。
25
+
26
+ ## 它不做什么
27
+
28
+ - 不替用户调模型:提炼由当前模型自己做,插件只负责「存」和「提醒该长了」。
29
+ - 不做备份、不加密、不建库。
30
+
31
+ ## 四个工具
32
+
33
+ | 工具 | 干什么 |
34
+ | --- | --- |
35
+ | `memory_init` | 铺骨架(已有文件不覆盖,`force: true` 才覆盖) |
36
+ | `memory_status` | 看状态:档案几条、日记几篇、积压多少 |
37
+ | `memory_search` | 按关键词或日期(`11月19`)翻旧日记和纠错 |
38
+ | `memory_grow` | 往「关于你/关于我/我们之间」写条目,自动去重、封顶、清零 |
39
+
40
+ 命令:`/memory init`、`/memory search 关键词`、`/memory`(看状态)。
41
+
42
+ ## 装
43
+
44
+ ```bash
45
+ dsh plugin --profile <你的profile> add /home/wjb/Projects/dsh-memory-garden
46
+ ```
47
+
48
+ 或者在 profile 的 `cordis.patch.yml` 里加这个 bundle。
49
+
50
+ ## 配置
51
+
52
+ 在 profile 里给插件传配置,例如:
53
+
54
+ ```yaml
55
+ memory-garden:
56
+ dir: 记忆花园
57
+ grow:
58
+ threshold: 20 # 攒多少条提示一次
59
+ maxPerBlock: 14 # 每块最多几条,超了挤掉最老的
60
+ maxCharsPerItem: 120
61
+ index:
62
+ maxChars: 1400
63
+ snapshot:
64
+ enabled: true
65
+ ```
66
+
67
+ ## 边界
68
+
69
+ - 默认**不预置任何人的记忆**,第一版打开就是空骨架——别人用不会看到我的。
70
+ - 日记和原文都是普通文件,想备份自己拷。
@@ -0,0 +1,4 @@
1
+ # dsh-memory-garden bundle:把记忆花园挂进 DSH
2
+ - insert:
3
+ - id: memory-garden
4
+ name: dsh-memory-garden
package/index.mjs ADDED
@@ -0,0 +1,474 @@
1
+ // dsh-memory-garden · 记忆花园
2
+ //
3
+ // 给 DSH 用的「自生长」记忆:骨架默认是空的,靠聊天慢慢长出三块档案
4
+ // (关于你 / 关于我 / 我们之间)。所有数据都是工作区里的 md / json,
5
+ // 能读、能手改、能拷走。
6
+ //
7
+ // 它做四件事:
8
+ // 1. 铺骨架:/memory init 建好 人设 / 档案 / 存档 / 交接 / 日记 / 原文 / 索引 / 纠错
9
+ // 2. 开局索引:每轮注入一小块状态(积压多少条、今天日记写没写、上次提炼几天前)
10
+ // 3. 压缩前落款:会话压缩时往 交接.md 追一条机械快照,不覆盖人写的
11
+ // 4. 自生长:模型看到「积压够了」就自己总结,调 memory_grow 写进三块档案
12
+ //
13
+ // 它不做的:不替用户调模型(提炼由当前模型自己做,插件只负责存和提示)、
14
+ // 不做备份、不加密。
15
+
16
+ import {
17
+ existsSync, readFileSync, writeFileSync, readdirSync, statSync,
18
+ mkdirSync, renameSync,
19
+ } from 'node:fs'
20
+ import { join, resolve } from 'node:path'
21
+
22
+ export const name = 'memory-garden'
23
+ export const inject = ['systemPrompt']
24
+
25
+ const DEFAULTS = {
26
+ dir: '记忆花园',
27
+ index: { enabled: true, order: 240, maxChars: 1400 },
28
+ snapshot: { enabled: true, scanHours: 6 },
29
+ grow: { threshold: 20, maxPerBlock: 14, maxCharsPerItem: 120 },
30
+ cwd: '',
31
+ debug: false,
32
+ }
33
+
34
+ const 人设模板 = `# 人设(骨架)
35
+
36
+ > 只写「她本来是谁」:名字、自称、语气、底线。这里是手写的,不会自动长。
37
+ > 留空也行,用默认值。
38
+
39
+ - 名字:
40
+ - 自称:我
41
+ - 语气:温柔
42
+
43
+ ## 用户改的
44
+
45
+ (还没改过)
46
+ `
47
+
48
+ const 存档模板 = `# 记忆存档(世界观)
49
+
50
+ > 从日记里沉淀出来的结论,分两段。可以手改,也可以让模型重写。
51
+
52
+ ## 【稳定的】他是什么样的人、我们约定过什么
53
+
54
+ (还空着)
55
+
56
+ ## 【在变的】最近的状态、新的经历
57
+
58
+ (还空着)
59
+ `
60
+
61
+ const 交接模板 = `# 交接
62
+
63
+ > 换会话、压缩前,把「手上在做什么」写在这儿。插件也会往里落机械快照。
64
+
65
+ (还空着)
66
+ `
67
+
68
+ const 纠错模板 = `# 纠错
69
+
70
+ > 用户纠正过你的原话。存原文,不改写;「当时」是当时的理解。
71
+
72
+ (还空着)
73
+ `
74
+
75
+ function merge(base, patch) {
76
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return base
77
+ const out = { ...base }
78
+ for (const [k, v] of Object.entries(patch)) {
79
+ const cur = base ? base[k] : undefined
80
+ out[k] = v && typeof v === 'object' && !Array.isArray(v)
81
+ ? merge(cur && typeof cur === 'object' ? cur : {}, v)
82
+ : v
83
+ }
84
+ return out
85
+ }
86
+ const pad = n => String(n).padStart(2, '0')
87
+ const ymd = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
88
+ const hm = d => `${pad(d.getHours())}:${pad(d.getMinutes())}`
89
+
90
+ function readIf(path) { try { return existsSync(path) && statSync(path).isFile() ? readFileSync(path, 'utf8') : null } catch { return null } }
91
+ function writeAtomic(path, text) {
92
+ const tmp = path + '.tmp-' + process.pid
93
+ writeFileSync(tmp, text, 'utf8')
94
+ renameSync(tmp, path)
95
+ }
96
+ function readJson(path, fallback) {
97
+ try { const t = readIf(path); if (!t) return fallback; return JSON.parse(t) } catch { return fallback }
98
+ }
99
+ function writeJson(path, obj) { writeAtomic(path, JSON.stringify(obj, null, 1)) }
100
+
101
+ export function paths(cwd, cfg) {
102
+ const root = join(resolve(cwd), cfg.dir)
103
+ return {
104
+ root,
105
+ persona: join(root, '人设.md'),
106
+ files: join(root, '档案.json'),
107
+ canon: join(root, '存档.md'),
108
+ handoff: join(root, '交接.md'),
109
+ diary: join(root, '日记'),
110
+ raw: join(root, '原文'),
111
+ index: join(root, '索引.json'),
112
+ fix: join(root, '纠错.md'),
113
+ state: join(root, '状态.json'),
114
+ }
115
+ }
116
+
117
+ export function initSkeleton(cwd, cfg, force = false) {
118
+ const p = paths(cwd, cfg)
119
+ const created = [], skipped = []
120
+ mkdirSync(p.diary, { recursive: true })
121
+ mkdirSync(p.raw, { recursive: true })
122
+ const put = (path, rel, text) => {
123
+ if (existsSync(path) && !force) { skipped.push(rel); return }
124
+ writeAtomic(path, text); created.push(rel)
125
+ }
126
+ put(p.persona, '人设.md', 人设模板)
127
+ put(p.canon, '存档.md', 存档模板)
128
+ put(p.handoff, '交接.md', 交接模板)
129
+ put(p.fix, '纠错.md', 纠错模板)
130
+ if (!existsSync(p.files)) { writeJson(p.files, { 关于你: [], 关于我: [], 我们之间: [] }); created.push('档案.json') }
131
+ else skipped.push('档案.json')
132
+ if (!existsSync(p.index)) { writeJson(p.index, {}); created.push('索引.json') } else skipped.push('索引.json')
133
+ if (!existsSync(p.state)) { writeJson(p.state, { pending: 0, lastGrow: '', turns: 0 }); created.push('状态.json') } else skipped.push('状态.json')
134
+ return { created, skipped }
135
+ }
136
+
137
+ function diaryDays(p) {
138
+ try { return readdirSync(p.diary).filter(f => /^\d{4}-\d{2}-\d{2}\.md$/.test(f)).sort() } catch { return [] }
139
+ }
140
+
141
+ export function buildIndex(cwd, cfg) {
142
+ const p = paths(cwd, cfg)
143
+ const canon = readIf(p.canon) || ''
144
+ const handoff = readIf(p.handoff) || ''
145
+ const 档案 = readJson(p.files, null)
146
+ const st = readJson(p.state, { pending: 0, lastGrow: '', turns: 0 })
147
+ const days = diaryDays(p)
148
+ const today = ymd(new Date()) + '.md'
149
+ const 块 = 档案 ? Object.keys(档案) : []
150
+ const 条数 = 档案 ? 块.reduce((a, k) => a + (档案[k] || []).length, 0) : 0
151
+ const 天前 = st.lastGrow ? Math.floor((Date.now() - Date.parse(st.lastGrow + 'T00:00:00')) / 86400000) : null
152
+ const lines = [
153
+ '[记忆花园]',
154
+ `档案:${条数} 条(${块.map(k => `${k}${(档案[k] || []).length}`).join(' / ') || '空'})`,
155
+ `存档:${canon ? canon.length + ' 字' : '没有'}|交接:${handoff ? handoff.length + ' 字' : '没有'}`,
156
+ `日记:${days.length} 篇,今天${days.includes(today) ? '已写' : '还没写'}`,
157
+ `积压:${st.pending || 0} 条${天前 == null ? '' : `|上次长档案:${天前} 天前`}`,
158
+ ]
159
+ const 人设 = readIf(p.persona)
160
+ const 用户段 = 人设 && 人设.includes('## 用户改的') ? 人设.split('## 用户改的')[1].trim() : ''
161
+ const 改条数 = (用户段.match(/^- \[/gm) || []).length
162
+ if (改条数) lines.push(`人设:用户改过 ${改条数} 条${st.lastPersona ? `(最近 ${st.lastPersona})` : ''}`)
163
+ if ((st.pending || 0) >= (cfg.grow.threshold || 20)) {
164
+ lines.push('→ 攒够了:用 memory_grow 把新认识的写进三块档案(关于你/关于我/我们之间),写完插件会把积压清零。')
165
+ }
166
+ if (days.length && !days.includes(today)) lines.push('→ 今天的日记还没写,收工时记得补。')
167
+ let text = lines.join('\n')
168
+ if (text.length > (cfg.index.maxChars || 1400)) text = text.slice(0, cfg.index.maxChars) + '…'
169
+ return text
170
+ }
171
+
172
+ export function searchGarden(cwd, cfg, q, limit = 4) {
173
+ const p = paths(cwd, cfg)
174
+ const query = String(q || '').trim()
175
+ if (!query) return { hits: [], text: '给个词' }
176
+ const 词 = query.split(/[\s,。、?!,?!]+/).filter(w => w.length >= 2)
177
+ const 命中 = []
178
+ // 日期说法
179
+ const m = query.match(/(\d{1,2})\s*[月\-/]\s*(\d{1,2})/)
180
+ for (const f of diaryDays(p)) {
181
+ if (m && +f.slice(5, 7) === +m[1] && +f.slice(8, 10) === +m[2]) 命中.push({ kind: '日记', day: f, text: readIf(join(p.diary, f)) || '' })
182
+ }
183
+ const 索引 = readJson(p.index, {})
184
+ for (const f of diaryDays(p)) {
185
+ if (命中.some(h => h.day === f)) continue
186
+ const it = 索引[f.replace(/\.md$/, '')] || {}
187
+ const tags = (it.tags || []).join(' ')
188
+ const body = readIf(join(p.diary, f)) || ''
189
+ const score = 词.reduce((a, w) => a + (tags.includes(w) ? 2 : 0) + (body.includes(w) ? 1 : 0), 0)
190
+ if (score) 命中.push({ kind: '日记', day: f, text: body, score })
191
+ }
192
+ 命中.sort((a, b) => (b.score || 0) - (a.score || 0))
193
+ const 纠 = readIf(p.fix) || ''
194
+ const 纠行 = 纠.split('\n').filter(ln => ln.trim() && !ln.trim().startsWith('>') && 词.some(w => ln.includes(w))).slice(0, 5)
195
+ const out = 命中.slice(0, limit).map(h => `${h.day}:${h.text.replace(/\n+/g, ' ').slice(0, 300)}`)
196
+ const text = [
197
+ out.length ? out.join('\n') : '日记里没翻到。',
198
+ 纠行.length ? '纠错记录:\n' + 纠行.map(x => '· ' + x.trim().slice(0, 120)).join('\n') : '',
199
+ ].filter(Boolean).join('\n\n')
200
+ return { hits: 命中.slice(0, limit), text }
201
+ }
202
+
203
+ export function growFiles(cwd, cfg, 块, items) {
204
+ const p = paths(cwd, cfg)
205
+ const 档案 = readJson(p.files, { 关于你: [], 关于我: [], 我们之间: [] })
206
+ const 合法 = ['关于你', '关于我', '我们之间']
207
+ if (!合法.includes(块)) return { ok: false, text: `块名只能是 ${合法.join(' / ')}` }
208
+ if (!Array.isArray(items) || !items.length) return { ok: false, text: '没给条目' }
209
+ const arr = 档案[块] || (档案[块] = [])
210
+ let 加 = 0, 跳 = 0
211
+ for (const it of items) {
212
+ const t = String((it && (it.text || it)) || '').trim().slice(0, cfg.grow.maxCharsPerItem || 120)
213
+ if (!t) continue
214
+ if (arr.some(x => String(x.text || '').trim() === t)) { 跳++; continue }
215
+ arr.push({ text: t, from: 'chat', at: ymd(new Date()) })
216
+ 加++
217
+ }
218
+ while (arr.length > (cfg.grow.maxPerBlock || 14)) arr.shift()
219
+ writeJson(p.files, 档案)
220
+ const st = readJson(p.state, { pending: 0, lastGrow: '', turns: 0 })
221
+ if (加) { st.pending = 0; st.lastGrow = ymd(new Date()) }
222
+ writeJson(p.state, st)
223
+ return { ok: true, text: `${块}:加 ${加} 条,重复跳过 ${跳} 条(现在 ${arr.length} 条)` }
224
+ }
225
+
226
+ const 人格追加 = /-人格编辑追加[::]?\s*([\s\S]*?)-人格编辑结束/g
227
+ const 人格替换 = /-人格编辑替换[::]?\s*([\s\S]*?)-人格编辑结束/g
228
+
229
+ /** 聊天里现场改人设:-人格编辑追加:…-人格编辑结束 / -人格编辑替换…-人格编辑结束 */
230
+ export function editPersona(cwd, cfg, text) {
231
+ const raw = String(text || '')
232
+ const 任务 = []
233
+ for (const m of raw.matchAll(人格追加)) 任务.push({ 模式: '追加', 内容: m[1].trim() })
234
+ for (const m of raw.matchAll(人格替换)) 任务.push({ 模式: '替换', 内容: m[1].trim() })
235
+ if (!任务.length) return { 动了: false, 条数: 0, 模式: '' }
236
+ const p = paths(cwd, cfg)
237
+ const 标 = '## 用户改的'
238
+ let ps = readIf(p.persona)
239
+ if (!ps) ps = 人设模板
240
+ if (!ps.includes(标)) ps = ps.trimEnd() + '\n\n' + 标 + '\n'
241
+ let [头, 尾] = ps.split(标)
242
+ let 几条 = 0, 最近模式 = ''
243
+ for (const t of 任务) {
244
+ if (!t.内容) continue
245
+ const 条目 = `- [${ymd(new Date())}] ${t.内容.replace(/\n/g, ' ') }`
246
+ if (t.模式 === '追加') {
247
+ 尾 = (尾 || '').trim() && !(尾 || '').includes('(还没改过)') ? (尾.trim() + '\n' + 条目) : 条目
248
+ } else {
249
+ 尾 = 条目
250
+ }
251
+ 几条++; 最近模式 = t.模式
252
+ }
253
+ writeAtomic(p.persona, (头 + 标 + '\n\n' + 尾.trim() + '\n'))
254
+ const st = readJson(p.state, { pending: 0, lastGrow: '', turns: 0 })
255
+ st.lastPersona = ymd(new Date())
256
+ writeJson(p.state, st)
257
+ return { 动了: true, 条数: 几条, 模式: 最近模式 }
258
+ }
259
+
260
+ export function writeSnapshot(cwd, cfg, sessionId = '') {
261
+ const p = paths(cwd, cfg)
262
+ const 现在 = new Date()
263
+ const 日 = diaryDays(p)
264
+ const canon = readIf(p.canon) || ''
265
+ const 行 = [
266
+ '',
267
+ `## 机制落款 ${ymd(现在)} ${hm(现在)}`,
268
+ `- 工作区:${resolve(cwd)}`,
269
+ `- 会话:${sessionId || '(不知道)'}`,
270
+ `- 存档:${canon ? canon.length + ' 字' : '没有'}`,
271
+ `- 日记:${日.length} 篇,今天${日.includes(ymd(现在) + '.md') ? '已写' : '还没写'}`,
272
+ ].join('\n')
273
+ try { writeFileSync(p.handoff, 行 + '\n', { flag: 'a' }) } catch { return false }
274
+ return true
275
+ }
276
+
277
+ function eventText(event) {
278
+ try {
279
+ const d = (event && event.data) || {}
280
+ const parts = (d.content || []).filter(c => c && c.type === 'text').map(c => c.text || '')
281
+ if (parts.length) return parts.join('\n')
282
+ if (typeof d.text === 'string') return d.text
283
+ if (typeof event.text === 'string') return event.text
284
+ } catch {}
285
+ return ''
286
+ }
287
+
288
+ export function apply(ctx, config = {}) {
289
+ const cfg = merge(DEFAULTS, config)
290
+ const cwdBySession = new Map()
291
+ let lastCwd = ''
292
+
293
+ const noteCwd = (session) => {
294
+ if (!session) return lastCwd
295
+ const c = cfg.cwd ? resolve(cfg.cwd) : (session.cwd ? resolve(session.cwd) : '')
296
+ if (!c) return lastCwd
297
+ const id = String(session.id || session.sessionId || '')
298
+ if (id) cwdBySession.set(id, c)
299
+ lastCwd = c
300
+ return c
301
+ }
302
+ const cwdFor = (scope) => {
303
+ try {
304
+ const key = scope && (scope.sessionId || scope.session || scope.id || scope.key)
305
+ if (key && cwdBySession.has(String(key))) return cwdBySession.get(String(key))
306
+ } catch {}
307
+ return cfg.cwd ? resolve(cfg.cwd) : (lastCwd || process.cwd())
308
+ }
309
+
310
+ // 1) 开局索引
311
+ try {
312
+ if (cfg.index.enabled && ctx.systemPrompt && typeof ctx.systemPrompt.context === 'function') {
313
+ ctx.effect(() => ctx.systemPrompt.context({
314
+ name: 'memory-garden-index',
315
+ order: Number(cfg.index.order) || 240,
316
+ text: (assembly) => {
317
+ try { return buildIndex(cwdFor(assembly && assembly.scope), cfg) }
318
+ catch (e) { return '[记忆花园] 索引读不出来:' + (e && e.message) }
319
+ },
320
+ }))
321
+ }
322
+ } catch (e) { console.error('[garden] 索引没挂上:', e && e.message) }
323
+
324
+ // 2) 计数 + 压缩前落款
325
+ try {
326
+ if (typeof ctx.on === 'function') {
327
+ ctx.on('session/created', (s) => { try { noteCwd(s) } catch {} })
328
+ ctx.on('session/event', (session, event) => {
329
+ try {
330
+ const cwd = noteCwd(session)
331
+ if (!cwd) return
332
+ if (event && event.type === 'compaction/start' && cfg.snapshot.enabled) {
333
+ writeSnapshot(cwd, cfg, String((session && (session.id || session.sessionId)) || ''))
334
+ console.error('[garden] 压缩前落款:', cwd)
335
+ }
336
+ if (event && (event.type === 'user/message' || event.type === 'assistant/message')) {
337
+ const p = paths(cwd, cfg)
338
+ const st = readJson(p.state, { pending: 0, lastGrow: '', turns: 0 })
339
+ st.pending = (st.pending || 0) + 1
340
+ st.turns = (st.turns || 0) + 1
341
+ writeJson(p.state, st)
342
+ if (event.type === 'user/message') {
343
+ const 文 = eventText(event)
344
+ if (文 && 文.includes('-人格编辑')) {
345
+ const r = editPersona(cwd, cfg, 文)
346
+ if (r.动了) console.error(`[garden] 人设${r.模式}:${r.条数} 条`)
347
+ }
348
+ }
349
+ }
350
+ } catch (e) { if (cfg.debug) console.error('[garden] 事件处理失败:', e && e.message) }
351
+ })
352
+ }
353
+ } catch (e) { console.error('[garden] 钩子没挂上:', e && e.message) }
354
+
355
+ const resolveCwdFromExec = (exec) => {
356
+ try {
357
+ const id = exec && exec.agent && String(exec.agent.id || '')
358
+ if (id && cwdBySession.has(id)) return cwdBySession.get(id)
359
+ const c = exec && exec.agent && (exec.agent.cwd || (exec.agent.session && exec.agent.session.cwd))
360
+ if (c) return resolve(c)
361
+ } catch {}
362
+ return cfg.cwd ? resolve(cfg.cwd) : (lastCwd || process.cwd())
363
+ }
364
+
365
+ const whenReady = (deps, fn) => {
366
+ const run = (c) => { try { fn(c || ctx) } catch (e) { console.error('[garden] 挂载失败:', e && e.message) } }
367
+ try { if (typeof ctx.inject === 'function') return ctx.inject(deps, (c) => run(c)) } catch {}
368
+ run(ctx)
369
+ }
370
+
371
+ const textOut = (v) => [{ type: 'text', text: String((v && v.text) || '') }]
372
+ const sch = { type: 'object', additionalProperties: false, properties: { ok: { type: 'boolean' }, text: { type: 'string' } } }
373
+
374
+ const registerTools = (c) => {
375
+ try {
376
+ const tools = typeof c.get === 'function' ? c.get('tools') : undefined
377
+ if (!tools || typeof tools.register !== 'function') return
378
+
379
+ tools.register({
380
+ name: 'memory_init',
381
+ description: '在当前工作区铺一份记忆花园的骨架(人设/档案/存档/交接/日记/原文/索引/纠错)。默认不覆盖已有文件。',
382
+ parameters: { type: 'object', additionalProperties: false, properties: { force: { type: 'boolean' } } },
383
+ output: { schema: sch, render: (_a, v) => textOut(v) },
384
+ async execute(args, exec) {
385
+ try {
386
+ const cwd = resolveCwdFromExec(exec)
387
+ const r = initSkeleton(cwd, cfg, Boolean(args && args.force))
388
+ return { ok: true, text: `工作区:${cwd}\n新建:${r.created.join('、') || '无'}\n跳过:${r.skipped.join('、') || '无'}` }
389
+ } catch (e) { return { ok: false, text: '铺骨架失败:' + (e && e.message) } }
390
+ },
391
+ })
392
+
393
+ tools.register({
394
+ name: 'memory_status',
395
+ description: '看一眼记忆花园的状态:档案几条、日记几篇、积压多少、今天写没写。只读。',
396
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
397
+ output: { schema: sch, render: (_a, v) => textOut(v) },
398
+ async execute(_a, exec) {
399
+ try { return { ok: true, text: buildIndex(resolveCwdFromExec(exec), cfg) } }
400
+ catch (e) { return { ok: false, text: '读不出来:' + (e && e.message) } }
401
+ },
402
+ })
403
+
404
+ tools.register({
405
+ name: 'memory_search',
406
+ description: '按关键词或日期(「11月19」)翻旧日记和纠错记录,返回命中的片段。查不到就明说。',
407
+ parameters: {
408
+ type: 'object', additionalProperties: false,
409
+ properties: { q: { type: 'string', description: '关键词或日期' } },
410
+ required: ['q'],
411
+ },
412
+ output: { schema: sch, render: (_a, v) => textOut(v) },
413
+ async execute(args, exec) {
414
+ try {
415
+ const r = searchGarden(resolveCwdFromExec(exec), cfg, args && args.q)
416
+ return { ok: true, text: r.text }
417
+ } catch (e) { return { ok: false, text: '搜失败:' + (e && e.message) } }
418
+ },
419
+ })
420
+
421
+ tools.register({
422
+ name: 'memory_grow',
423
+ description: '把新认识写进三块档案之一。块名只会是「关于你 / 关于我 / 我们之间」,条目是短句,重复会自动跳过,写完积压清零。',
424
+ parameters: {
425
+ type: 'object', additionalProperties: false,
426
+ properties: {
427
+ 块: { type: 'string', enum: ['关于你', '关于我', '我们之间'] },
428
+ items: { type: 'array', items: { type: 'string' }, description: '要加的短句' },
429
+ },
430
+ required: ['块', 'items'],
431
+ },
432
+ output: { schema: sch, render: (_a, v) => textOut(v) },
433
+ async execute(args, exec) {
434
+ try {
435
+ const r = growFiles(resolveCwdFromExec(exec), cfg, args && args.块, args && args.items)
436
+ return { ok: Boolean(r.ok), text: r.text }
437
+ } catch (e) { return { ok: false, text: '写档案失败:' + (e && e.message) } }
438
+ },
439
+ })
440
+ } catch (e) { console.error('[garden] 工具没挂上:', e && e.message) }
441
+ }
442
+
443
+ const registerCommands = (c) => {
444
+ try {
445
+ const commands = typeof c.get === 'function' ? c.get('commands') : undefined
446
+ if (!commands || typeof commands.register !== 'function') return
447
+ const dispose = commands.register({
448
+ name: 'memory',
449
+ description: '记忆花园:init 铺骨架 / status 看状态 / search 关键词',
450
+ handler: async (调用) => {
451
+ try {
452
+ const cwd = resolveCwdFromExec(调用)
453
+ const arg = String((调用 && (调用.args || 调用.arguments || '')) || '').trim()
454
+ if (arg.startsWith('init')) {
455
+ const r = initSkeleton(cwd, cfg, false)
456
+ return { kind: 'success', text: `铺好了:新建 ${r.created.join('、') || '无'};跳过 ${r.skipped.join('、') || '无'}` }
457
+ }
458
+ if (arg.startsWith('search')) {
459
+ const q = arg.replace(/^search\s*/, '')
460
+ return { kind: 'success', text: searchGarden(cwd, cfg, q).text }
461
+ }
462
+ return { kind: 'success', text: buildIndex(cwd, cfg) }
463
+ } catch (e) { return { kind: 'error', text: '失败:' + (e && e.message) } }
464
+ },
465
+ })
466
+ if (typeof dispose === 'function') ctx.effect(() => dispose)
467
+ } catch (e) { console.error('[garden] 命令没挂上:', e && e.message) }
468
+ }
469
+
470
+ whenReady(['tools'], registerTools)
471
+ whenReady(['commands'], registerCommands)
472
+ }
473
+
474
+ export const __test = { merge, initSkeleton, buildIndex, searchGarden, growFiles, writeSnapshot, editPersona, paths, ymd }
package/package.json CHANGED
@@ -1,6 +1,19 @@
1
1
  {
2
2
  "name": "dsh-memory-garden",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "记忆花园:给 DeepSeek Harness 用的自生长记忆——骨架默认空,靠聊天长出「关于你 / 关于我 / 我们之间」,配日记、原文、索引、纠错,全是能读能拷的 md。",
5
+ "author": "泡泡",
6
+ "type": "module",
7
+ "main": "index.mjs",
8
+ "exports": {
9
+ ".": "./index.mjs",
10
+ "./cordis.patch.yml": "./cordis.patch.yml",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": ["index.mjs", "cordis.patch.yml", "README.md"],
14
+ "scripts": { "test": "node --test test/" },
15
+ "engines": { "node": ">=22" },
16
+ "keywords": ["deepseek-harness", "dsh-plugin", "memory", "self-growing", "markdown"],
17
+ "license": "MIT",
18
+ "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
19
+ }