dsh-workbuddy-shared-memory 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shawenbin
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.
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: workbuddy-memory
3
+ name: dsh-workbuddy-shared-memory
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "dsh-workbuddy-shared-memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "WorkBuddy 共享记忆:让 DSH 与 WorkBuddy 桌面应用读写同一份用户级与项目级记忆文件,任一方写入另一方下一轮即可读到。",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./入口.js",
8
+ "./icon": "./图标.svg",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "files": [
12
+ "入口.js",
13
+ "路径.js",
14
+ "记忆文件.js",
15
+ "策略.js",
16
+ "工具.js",
17
+ "cordis.patch.yml",
18
+ "文档/preview.svg",
19
+ "图标.svg",
20
+ "读我.md",
21
+ "LICENSE"
22
+ ],
23
+ "scripts": {
24
+ "check": "node --check 入口.js && node --check 路径.js && node --check 记忆文件.js && node --check 策略.js && node --check 工具.js"
25
+ },
26
+ "license": "MIT",
27
+ "author": "shawenbin",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/shawenbin/dsh-plugins.git",
31
+ "directory": "共享WorkBuddy记忆"
32
+ },
33
+ "homepage": "https://github.com/shawenbin/dsh-plugins#readme",
34
+ "bugs": {
35
+ "url": "https://github.com/shawenbin/dsh-plugins/issues"
36
+ },
37
+ "keywords": [
38
+ "dsh",
39
+ "dsh-plugin",
40
+ "deepseek-harness",
41
+ "plugin",
42
+ "memory",
43
+ "shared-memory",
44
+ "agent-memory",
45
+ "workbuddy"
46
+ ],
47
+ "engines": {
48
+ "node": ">=22",
49
+ "dsh": "^0.2.2-rc.5"
50
+ },
51
+ "dsh": {
52
+ "bundle": {
53
+ "patch": "./cordis.patch.yml"
54
+ }
55
+ },
56
+ "peerDependencies": {
57
+ "@deepseek-ai/dsh-tools": "^0.2.2-rc.5",
58
+ "@deepseek-ai/schemastery": "^3.19.0"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "@deepseek-ai/dsh-tools": {
62
+ "optional": true
63
+ },
64
+ "@deepseek-ai/schemastery": {
65
+ "optional": true
66
+ }
67
+ },
68
+ "devDependencies": {
69
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.5",
70
+ "@deepseek-ai/schemastery": "3.19.0"
71
+ },
72
+ "publishConfig": {
73
+ "access": "public"
74
+ }
6
75
  }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * WorkBuddy 共享记忆 —— Host 插件入口。
3
+ *
4
+ * 注入位置与触发时机对齐 WorkBuddy:策略和两层记忆都进入 system prompt,
5
+ * 每次系统提示词装配时重新读取文件。WorkBuddy 把项目级记忆放在
6
+ * <会话工作区>/.workbuddy/memory(分组目录即工作区目录);DSH 工作区
7
+ * 会话也按同一个目录读写,不再向上寻找 .git。
8
+ */
9
+ import z from '@deepseek-ai/schemastery'
10
+ import { 项目根目录, 项目记忆目录由根, 用户记忆目录 } from './路径.js'
11
+ import { 用户记忆注入块, 项目记忆注入块 } from './记忆文件.js'
12
+ import { 策略文本 } from './策略.js'
13
+ import { 创建工具 } from './工具.js'
14
+
15
+ export const name = 'workbuddy-memory'
16
+ export const inject = ['tools', 'systemPrompt', 'workingDirectory']
17
+
18
+ export const Config = z.object({
19
+ enabled: z.boolean().default(true),
20
+ dataFolderName: z.string().default(''),
21
+ workbuddyRoot: z.string().default(''),
22
+ userDir: z.string().default(''),
23
+ userMemoryLimit: z.number().step(1).min(1).default(4000),
24
+ projectMemoryLimit: z.number().step(1).min(1).default(10000),
25
+ sessionWriteBudget: z.number().step(1).min(1).default(3000),
26
+ distillAfterDays: z.number().step(1).min(1).default(30),
27
+ injectPolicy: z.boolean().default(true),
28
+ injectContent: z.boolean().default(true),
29
+ projectRootMarkers: z.array(z.string()).default([]),
30
+ })
31
+
32
+ const 默认配置 = {
33
+ enabled: true,
34
+ dataFolderName: '',
35
+ workbuddyRoot: '',
36
+ userDir: '',
37
+ userMemoryLimit: 4000,
38
+ projectMemoryLimit: 10000,
39
+ sessionWriteBudget: 3000,
40
+ distillAfterDays: 30,
41
+ injectPolicy: true,
42
+ injectContent: true,
43
+ projectRootMarkers: [],
44
+ }
45
+
46
+ /** 解析当前会话的项目根;无活动 agent(如标题生成)时不注入项目级内容。 */
47
+ function 当前项目根(ctx, 配置, 上下文) {
48
+ const agent = 上下文?.agent
49
+ const session = agent?.session
50
+ if (session === undefined) return undefined
51
+ try {
52
+ const 固定目录 = session.header?.cwd?.trim()
53
+ const 工作目录 = 固定目录 || ctx.workingDirectory.get(session)
54
+ return 项目根目录(工作目录, 配置.projectRootMarkers)
55
+ } catch {
56
+ return undefined
57
+ }
58
+ }
59
+
60
+ /** 组装本轮要注入的记忆快照;任何一层失败都只告警,不影响对话。 */
61
+ function 注入记忆内容(配置, 项目根, 告警) {
62
+ const 块 = []
63
+ try {
64
+ const 文本 = 用户记忆注入块(用户记忆目录(配置), 配置.userMemoryLimit, 告警)
65
+ if (文本) 块.push(文本)
66
+ } catch (错误) {
67
+ 告警(`用户级记忆注入失败:${错误?.message ?? 错误}`)
68
+ }
69
+ if (项目根 !== undefined) {
70
+ try {
71
+ const 文本 = 项目记忆注入块(项目记忆目录由根(项目根, 配置), 配置.projectMemoryLimit, 告警)
72
+ if (文本) 块.push(文本)
73
+ } catch (错误) {
74
+ 告警(`项目记忆注入失败:${错误?.message ?? 错误}`)
75
+ }
76
+ }
77
+ return 块.join('\n\n')
78
+ }
79
+
80
+ export function apply(ctx, 用户配置 = {}) {
81
+ const 配置 = { ...默认配置, ...用户配置 }
82
+ if (!配置.enabled) return
83
+ const 告警 = (文本) => ctx.logger.warn(`[WorkBuddy 记忆] ${文本}`)
84
+
85
+ if (配置.injectPolicy) {
86
+ ctx.systemPrompt.section({
87
+ name: 'workbuddy-memory:policy',
88
+ order: 8600,
89
+ interpolate: false,
90
+ text: (上下文) => 策略文本(配置, 当前项目根(ctx, 配置, 上下文)),
91
+ })
92
+ }
93
+
94
+ if (配置.injectContent) {
95
+ ctx.systemPrompt.section({
96
+ name: 'workbuddy-memory:content',
97
+ order: 8601,
98
+ interpolate: false,
99
+ text: (上下文) => {
100
+ const 项目根 = 当前项目根(ctx, 配置, 上下文)
101
+ if (项目根 === undefined) return ''
102
+ return 注入记忆内容(配置, 项目根, 告警)
103
+ },
104
+ })
105
+ }
106
+
107
+ for (const 工具 of 创建工具({ ctx, 配置 })) ctx.tools.register(工具)
108
+ }
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">
2
+ <rect x="3" y="3" width="90" height="90" rx="22" fill="#141a2e"/>
3
+ <circle cx="37" cy="41" r="21" fill="none" stroke="#5b9dff" stroke-width="6"/>
4
+ <circle cx="59" cy="41" r="21" fill="none" stroke="#b78bff" stroke-width="6"/>
5
+ <path d="M33 66h30M33 76h20" fill="none" stroke="#e8ecf8" stroke-width="6" stroke-linecap="round"/>
6
+ </svg>
@@ -0,0 +1,245 @@
1
+ /**
2
+ * 模型侧工具:memory_read / memory_write。
3
+ * 工具名遵循 DSH 命名契约使用英文;读写路径与 WorkBuddy 桌面应用保持一致(互操作所需)。
4
+ */
5
+ import { join } from 'node:path'
6
+ import { existsSync } from 'node:fs'
7
+ import { defineTool } from '@deepseek-ai/dsh-tools'
8
+ import {
9
+ 项目记忆目录, 用户记忆目录, 项目根目录, 数据目录名, 配置根目录,
10
+ 今天日期, 是合法日期, 用户记忆文件名, 项目记忆文件名,
11
+ } from './路径.js'
12
+ import {
13
+ 读取本地文本, 日志清单, 读取记忆文本, 写入记忆文本,
14
+ 拼接追加, 规整替换, 原地替换,
15
+ } from './记忆文件.js'
16
+
17
+ /** 同一文件的写入在进程内串行,避免并行工具调用互相覆盖。 */
18
+ const 写入队列 = new Map()
19
+ function 串行写入(路径, 任务) {
20
+ const 前序 = 写入队列.get(路径) ?? Promise.resolve()
21
+ const 当前 = 前序.then(任务, 任务)
22
+ 写入队列.set(路径, 当前)
23
+ const 清理 = () => { if (写入队列.get(路径) === 当前) 写入队列.delete(路径) }
24
+ 当前.then(清理, 清理)
25
+ return 当前
26
+ }
27
+
28
+ function 文本输出(_参数, 值) {
29
+ return [{ type: 'text', text: 值 }]
30
+ }
31
+
32
+ function 分页(文本, offset, limit) {
33
+ const 起点 = Number.isInteger(offset) && offset > 0 ? offset : 0
34
+ const 上限 = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 20000) : 12000
35
+ const 片段 = 文本.slice(起点, 起点 + 上限)
36
+ const 下一段 = 起点 + 片段.length < 文本.length ? 起点 + 片段.length : null
37
+ return { 片段, 下一段, 起点 }
38
+ }
39
+
40
+ export function 创建工具(环境) {
41
+ const { ctx, 配置 } = 环境
42
+
43
+ async function 会话目录(exec) {
44
+ if (exec.agent === undefined) throw new Error('记忆工具需要在活动的 DSH 会话中使用')
45
+ /** 工作区根固定在会话头里;会话内 cd 到子目录时仍按原工作区读写。 */
46
+ const 固定目录 = exec.agent.session?.header?.cwd
47
+ if (typeof 固定目录 === 'string' && 固定目录.trim().length > 0) return 固定目录
48
+ return ctx.workingDirectory.ensure(exec.agent, exec.signal)
49
+ }
50
+
51
+ function 文件系统() {
52
+ const fs = ctx.get('fs')
53
+ if (fs === undefined) throw new Error('当前部署没有可用的文件系统服务(ctx.fs),无法读写记忆文件')
54
+ return fs
55
+ }
56
+
57
+ /** 会话当前的沙箱策略(含模式与工作区根);与 dsh-tool-fs 不提权时的取值一致。 */
58
+ function 沙箱策略(exec) {
59
+ const 服务 = ctx.get('sandboxPolicy')
60
+ return 服务?.resolve({ ...(exec.agent ? { session: exec.agent.session } : {}) })
61
+ }
62
+
63
+ /**
64
+ * 用户级记忆位于会话工作区之外;workspace-write 下先为该会话登记一个
65
+ * 可写根(已存在的用户级目录,否则配置根)。read-only 仍然拒绝,
66
+ * danger-full-access 不需要这一步。
67
+ */
68
+ const 已授权用户目录 = new WeakSet()
69
+ function 启用用户目录写入(exec) {
70
+ const 服务 = ctx.get('sandboxPolicy')
71
+ const session = exec.agent?.session
72
+ if (服务 === undefined || session === undefined || 已授权用户目录.has(session)) return
73
+ try {
74
+ const 用户目录 = 用户记忆目录(配置)
75
+ const 根 = existsSync(用户目录) ? 用户目录 : 配置根目录(配置)
76
+ if (!existsSync(根)) return
77
+ 服务.registerWritableRoot(session, 根)
78
+ 已授权用户目录.add(session)
79
+ } catch (错误) {
80
+ ctx.logger.warn(`[WorkBuddy 记忆] 用户级目录可写根注册失败:${错误?.message ?? 错误}`)
81
+ }
82
+ }
83
+
84
+ function 目标路径(target, cwd, date) {
85
+ if (target === 'user') return join(用户记忆目录(配置), 用户记忆文件名)
86
+ const 目录 = 项目记忆目录(cwd, 配置)
87
+ if (target === 'project') return join(目录, 项目记忆文件名)
88
+ return join(目录, `${date ?? 今天日期()}.md`)
89
+ }
90
+
91
+ function 长度说明(文本, 上限) {
92
+ const 长度 = 文本.trim().length
93
+ const 超限 = 长度 > 上限
94
+ return { 长度, 超限, 描述: `${长度} / 注入上限 ${上限} UTF-16 字符${超限 ? '(已超限,注入时会被截断)' : ''}` }
95
+ }
96
+
97
+ const memoryRead = defineTool({
98
+ name: 'memory_read',
99
+ description: '读取与 WorkBuddy 共享的记忆文件。target=user 为跨项目用户记忆,project 为当前项目长期笔记,daily 为某一天的项目日志,recent 为最近若干天日志,status 报告两层路径、长度、注入上限与待蒸馏日志。daily/recent 不会自动注入提示词,需要历史背景时主动读取。',
100
+ parameters: {
101
+ target: { type: 'string', required: true, enum: ['user', 'project', 'daily', 'recent', 'status'], description: '读取对象:user 用户级 MEMORY.md;project 项目 MEMORY.md;daily 单日日志;recent 最近日志;status 状态报告' },
102
+ date: { type: 'string', description: 'daily 用,YYYY-MM-DD,缺省为今天(本地时区)' },
103
+ days: { type: 'number', description: 'recent 用,返回最近几篇日志,默认 3,最大 30' },
104
+ offset: { type: 'number', description: 'user/project/daily 的字符偏移,从 0 开始,用于分页读取长文件' },
105
+ limit: { type: 'number', description: '单次最多返回的字符数,默认 12000,最大 20000' },
106
+ },
107
+ output: { schema: { type: 'string' }, render: 文本输出 },
108
+ async execute(args, exec) {
109
+ const cwd = await 会话目录(exec)
110
+ const target = args.target
111
+
112
+ if (target === 'status') {
113
+ const 用户目录 = 用户记忆目录(配置)
114
+ const 用户路径 = join(用户目录, 用户记忆文件名)
115
+ const 项目目录 = 项目记忆目录(cwd, 配置)
116
+ const 项目路径 = join(项目目录, 项目记忆文件名)
117
+ const 行 = ['WorkBuddy 共享记忆状态', '']
118
+ 行.push(`数据目录名:${数据目录名(配置)}`)
119
+ 行.push(`用户级目录:${用户目录}`)
120
+ const 用户读取 = 读取本地文本(用户路径)
121
+ if (用户读取.状态 === 'ok') {
122
+ 行.push(` MEMORY.md:存在,${长度说明(用户读取.文本, 配置.userMemoryLimit).描述}`)
123
+ } else if (用户读取.状态 === 'missing') {
124
+ 行.push(' MEMORY.md:不存在(不注入用户级记忆)')
125
+ } else {
126
+ 行.push(` MEMORY.md:读取失败(${用户读取.错误?.message ?? 用户读取.错误})`)
127
+ }
128
+ const 根 = 项目根目录(cwd, 配置.projectRootMarkers)
129
+ 行.push(`工作区目录:${cwd}`)
130
+ 行.push(`项目根:${根}`)
131
+ 行.push(`项目记忆目录:${项目目录}`)
132
+ const 项目读取 = 读取本地文本(项目路径)
133
+ if (项目读取.状态 === 'ok') {
134
+ 行.push(` MEMORY.md:存在,${长度说明(项目读取.文本, 配置.projectMemoryLimit).描述}`)
135
+ } else if (项目读取.状态 === 'missing') {
136
+ 行.push(' MEMORY.md:不存在(不注入项目记忆)')
137
+ } else {
138
+ 行.push(` MEMORY.md:读取失败(${项目读取.错误?.message ?? 项目读取.错误})`)
139
+ }
140
+ const 今日 = 今天日期()
141
+ const 日志 = 日志清单(项目目录)
142
+ 行.push(`今日日期:${今日};今日日志:${日志.some(项 => 项.日期 === 今日) ? '已存在' : '不存在'}`)
143
+ if (日志.length === 0) {
144
+ 行.push('每日日志:暂无')
145
+ } else {
146
+ 行.push(`每日日志(共 ${日志.length} 篇,新到旧):`)
147
+ for (const 项 of 日志) 行.push(` ${项.日期}:${项.长度} UTF-16 字符`)
148
+ const 截止 = new Date()
149
+ 截止.setDate(截止.getDate() - 配置.distillAfterDays)
150
+ const 待蒸馏 = 日志.filter(项 => new Date(`${项.日期}T00:00:00`) < 截止)
151
+ 行.push(待蒸馏.length > 0
152
+ ? `待蒸馏(早于 ${配置.distillAfterDays} 天前):${待蒸馏.map(项 => 项.日期).join('、')};请按主题并入项目 MEMORY.md 后删除旧文件`
153
+ : `没有超过 ${配置.distillAfterDays} 天的待蒸馏日志`)
154
+ }
155
+ return 行.join('\n')
156
+ }
157
+
158
+ if (target === 'recent') {
159
+ const 目录 = 项目记忆目录(cwd, 配置)
160
+ const 日志 = 日志清单(目录)
161
+ if (日志.length === 0) return `项目记忆目录 ${目录} 下还没有每日日志。`
162
+ const 篇数 = Number.isInteger(args.days) && args.days > 0 ? Math.min(args.days, 30) : 3
163
+ const 选取 = 日志.slice(0, 篇数)
164
+ const 正文 = 选取.map(项 => `## ${项.日期}(${项.长度} UTF-16 字符)\n路径:${项.路径}\n\n${项.文本.trim() || '(空文件)'}`).join('\n\n')
165
+ const { 片段, 下一段 } = 分页(正文, args.offset, args.limit)
166
+ const 提示 = 下一段 === null ? '' : `\n\n[输出已截断;用 offset=${下一段} 继续读取]`
167
+ return `项目记忆目录:${目录}\n最近 ${选取.length} 篇日志(新到旧,共 ${日志.length} 篇):\n\n${片段}${提示}`
168
+ }
169
+
170
+ const date = args.date ?? 今天日期()
171
+ if (target === 'daily' && !是合法日期(date)) throw new Error('date 必须是 YYYY-MM-DD 格式')
172
+ const 路径 = 目标路径(target, cwd, date)
173
+ const 读取 = 读取本地文本(路径)
174
+ if (读取.状态 === 'missing') return `文件不存在:${路径}\n(尚未记录${target === 'user' ? '用户级' : target === 'project' ? '项目' : '该日'}记忆;可用 memory_write 创建。)`
175
+ if (读取.状态 === 'error') throw new Error(`读取失败:${读取.错误?.message ?? 读取.错误}`)
176
+ const 头部 = [`路径:${路径}`]
177
+ if (target === 'user') 头部.push(`长度:${长度说明(读取.文本, 配置.userMemoryLimit).描述}`)
178
+ if (target === 'project') 头部.push(`长度:${长度说明(读取.文本, 配置.projectMemoryLimit).描述}`)
179
+ if (target === 'daily') 头部.push(`长度:${读取.文本.trim().length} UTF-16 字符(日志不自动注入,只追加)`)
180
+ const { 片段, 下一段, 起点 } = 分页(读取.文本, args.offset, args.limit)
181
+ if (起点 > 0) 头部.push(`分页:从字符 ${起点} 开始`)
182
+ const 提示 = 下一段 === null ? '' : `\n\n[文件未读完;用 offset=${下一段} 继续读取]`
183
+ return `${头部.join('\n')}\n\n${片段}${提示}`
184
+ },
185
+ })
186
+
187
+ const memoryWrite = defineTool({
188
+ name: 'memory_write',
189
+ description: '写入与 WorkBuddy 共享的记忆文件,另一边(WorkBuddy 或 DSH)下一轮即可读到。target=user 写跨项目用户 MEMORY.md,project 写当前项目 MEMORY.md,daily 写项目每日日志(只允许 append)。mode=append 追加到末尾,replace 覆盖全文(先 trim 再补尾部换行);replace 时提供 old_string/new_string 可原地编辑唯一片段。写入不会自动删减内容,但超过注入上限的记忆在注入时会被截断。',
190
+ parameters: {
191
+ target: { type: 'string', required: true, enum: ['user', 'project', 'daily'], description: '写入对象:user 用户级 MEMORY.md;project 项目 MEMORY.md;daily 每日日志(仅 append)' },
192
+ mode: { type: 'string', required: true, enum: ['append', 'replace'], description: 'append 追加到文件末尾;replace 覆盖全文,或配合 old_string 做原地编辑' },
193
+ content: { type: 'string', required: true, description: 'append/replace 时写入的 Markdown 文本;原地编辑时作为 new_string 的缺省(也可用 new_string 显式给出)' },
194
+ date: { type: 'string', description: 'daily 用,YYYY-MM-DD,缺省为今天(本地时区)' },
195
+ old_string: { type: 'string', description: '仅 target=user/project 且 mode=replace:要在现有文件中替换的唯一文本片段' },
196
+ new_string: { type: 'string', description: '配合 old_string 的替换文本;缺省使用 content' },
197
+ },
198
+ output: { schema: { type: 'string' }, render: 文本输出 },
199
+ async execute(args, exec) {
200
+ const cwd = await 会话目录(exec)
201
+ const { target, mode } = args
202
+ if (target === 'daily' && mode !== 'append') {
203
+ throw new Error('每日日志为 append-only:请使用 mode=append,不要覆盖历史日志')
204
+ }
205
+ if (target === 'daily' && args.old_string !== undefined) {
206
+ throw new Error('每日日志不支持 old_string 原地编辑;请用 mode=append 追加新记录')
207
+ }
208
+ if (args.old_string !== undefined && mode !== 'replace') {
209
+ throw new Error('old_string 仅适用于 mode=replace 的原地编辑')
210
+ }
211
+ const date = args.date ?? 今天日期()
212
+ if (target === 'daily' && !是合法日期(date)) throw new Error('date 必须是 YYYY-MM-DD 格式')
213
+ const 路径 = 目标路径(target, cwd, date)
214
+ const fs = 文件系统()
215
+
216
+ return 串行写入(路径, async () => {
217
+ const 现有 = await 读取记忆文本(fs, 路径, exec.signal)
218
+ let 新文本
219
+ let 操作
220
+ if (args.old_string !== undefined) {
221
+ if (!现有.存在) throw new Error(`文件不存在:${路径},无法原地编辑;请先用 mode=replace 创建`)
222
+ 新文本 = 原地替换(现有.文本, args.old_string, args.new_string ?? args.content)
223
+ 操作 = '原地编辑'
224
+ } else if (mode === 'append') {
225
+ 新文本 = 拼接追加(现有.文本, args.content)
226
+ 操作 = 现有.存在 ? '追加' : '新建并写入'
227
+ } else {
228
+ 新文本 = 规整替换(args.content)
229
+ 操作 = 现有.存在 ? '覆盖' : '新建'
230
+ }
231
+ if (target === 'user') 启用用户目录写入(exec)
232
+ await 写入记忆文本(fs, 路径, 新文本, exec.signal, 沙箱策略(exec))
233
+ const 行 = [`已${操作}:${路径}`, `文件长度:${新文本.trim().length} UTF-16 字符`]
234
+ const 上限 = target === 'user' ? 配置.userMemoryLimit : target === 'project' ? 配置.projectMemoryLimit : null
235
+ if (上限 !== null && 新文本.trim().length > 上限) {
236
+ 行.push(`注意:已超过注入上限 ${上限},注入提示词时会被截断;请尽快合并去重、精简该文件。`)
237
+ }
238
+ if (target === 'daily') 行.push('日志已保存为 append-only;如需长期沉淀,请把要点提炼到项目 MEMORY.md。')
239
+ return 行.join('\n')
240
+ })
241
+ },
242
+ })
243
+
244
+ return [memoryRead, memoryWrite]
245
+ }
@@ -0,0 +1,25 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="640" height="300" viewBox="0 0 640 300">
2
+ <g fill="none" stroke-linecap="round" stroke-linejoin="round">
3
+ <rect x="42" y="86" width="150" height="128" rx="20" fill="#22345c" stroke="#5b9dff" stroke-width="4"/>
4
+ <circle cx="86" cy="126" r="14" stroke="#9cc2ff" stroke-width="5"/>
5
+ <circle cx="148" cy="126" r="14" stroke="#9cc2ff" stroke-width="5"/>
6
+ <path d="M72 172h90M72 190h60" stroke="#9cc2ff" stroke-width="6"/>
7
+ <rect x="448" y="86" width="150" height="128" rx="20" fill="#3a2a5e" stroke="#b78bff" stroke-width="4"/>
8
+ <circle cx="492" cy="126" r="14" stroke="#d3baff" stroke-width="5"/>
9
+ <circle cx="554" cy="126" r="14" stroke="#d3baff" stroke-width="5"/>
10
+ <path d="M478 172h90M478 190h60" stroke="#d3baff" stroke-width="6"/>
11
+ <path d="M262 52h84l28 28v104H262z" fill="#f4f7ff" stroke="#8fa3c8" stroke-width="4"/>
12
+ <path d="M346 52v30h28" stroke="#8fa3c8" stroke-width="4"/>
13
+ <path d="M282 104h72M282 126h72M282 148h46" stroke="#4a6db3" stroke-width="7"/>
14
+ <path d="M278 196h96v62h-96z" fill="#e9edfb" stroke="#8fa3c8" stroke-width="4"/>
15
+ <path d="M292 218h68M292 238h44" stroke="#7a5fb0" stroke-width="6"/>
16
+ <path d="M200 122h52" stroke="#5b9dff" stroke-width="6"/>
17
+ <path d="M240 110l14 12-14 12" stroke="#5b9dff" stroke-width="6"/>
18
+ <path d="M252 168h-52" stroke="#5b9dff" stroke-width="6"/>
19
+ <path d="M212 156l-14 12 14 12" stroke="#5b9dff" stroke-width="6"/>
20
+ <path d="M384 122h56" stroke="#b78bff" stroke-width="6"/>
21
+ <path d="M428 110l14 12-14 12" stroke="#b78bff" stroke-width="6"/>
22
+ <path d="M440 168h-56" stroke="#b78bff" stroke-width="6"/>
23
+ <path d="M396 156l-14 12 14 12" stroke="#b78bff" stroke-width="6"/>
24
+ </g>
25
+ </svg>
@@ -0,0 +1,62 @@
1
+ /**
2
+ * 记忆策略提示词:与 WorkBuddy 记忆层的规则保持一致(但不含其云端记忆层),
3
+ * 作为系统提示词章节注入。项目路径必须是当前会话解析出的绝对路径,
4
+ * 否则模型直接 Read/Edit 时会找不到文件。
5
+ *
6
+ * 文案为本项目自行撰写,不复制对方提示词原文;规则条目与被注入的路径、
7
+ * 上限、标记则必须与真实行为一致,否则模型会按错误的约定写文件。
8
+ */
9
+ import { 数据目录名, 用户记忆目录, 项目记忆目录由根 } from './路径.js'
10
+
11
+ /** 生成策略文本;项目根由当前会话解析,用户目录每次重新解析以跟随账号切换。 */
12
+ export function 策略文本(配置, 项目根) {
13
+ const 用户目录 = 用户记忆目录(配置)
14
+ const 目录名 = 数据目录名(配置)
15
+ const 项目目录 = 项目根 ? 项目记忆目录由根(项目根, 配置) : `<workspace>/${目录名}/memory`
16
+ const 标记 = (配置.projectRootMarkers ?? []).filter((项) => typeof 项 === 'string' && 项.length > 0)
17
+ const 根说明 = 标记.length > 0
18
+ ? `The project root is the nearest ancestor of the session workspace directory that contains ${标记.join(' / ')}; if no ancestor does, the workspace directory itself is the project root.`
19
+ : `The project root is exactly the session workspace directory (the DSH workspace folder, which is also the WorkBuddy group folder). It is never derived from an enclosing git repository.`
20
+ return `IMPORTANT: You have access to two independent local memory layers with different scopes and different write rules. Both are plain Markdown files that the WorkBuddy desktop app shares with you: whichever side writes, the other one reads the same file on its next prompt build.
21
+ <memory_system>
22
+
23
+ # Layer 1 — User-level Local Memory (read/write)
24
+
25
+ File: ${用户目录}/MEMORY.md | Scope: all projects | Injected limit: ${配置.userMemoryLimit} UTF-16 chars
26
+
27
+ Update this file in place when the user asks you to remember something long-term that is not tied to one project. Keep it short.
28
+ Treat the file as explicitly written: precise, mandatory rules belong here — environment paths, standing conventions, cross-project preferences.
29
+ Only the injected copy is truncated past the limit; the file itself never gets truncated.
30
+
31
+ # Layer 2 — Workspace Memory (read/write)
32
+
33
+ Directory: ${项目目录} | Scope: this DSH workspace only
34
+ ${根说明}
35
+ This workspace folder is the same folder WorkBuddy uses for this project group. Both sides read and write ${目录名}/memory under it, so a write from either side is visible to the other side's next session.
36
+
37
+ Files:
38
+ - YYYY-MM-DD.md — daily work log. Append-only: never overwrite it.
39
+ - MEMORY.md — curated long-term notes for this workspace. Limit: ${配置.sessionWriteBudget} chars per session.
40
+ - If today's file is absent, create the directory and the dated file first (memory_write does this automatically).
41
+
42
+ Reading history: pick the source you need instead of reading everything.
43
+ - Work this workspace did before → recent daily logs first, then MEMORY.md.
44
+ - Nothing depends on history → skip the memory files entirely.
45
+
46
+ Scope of responsibility: workspace memory is supplementary only. It never replaces your reply, your final answer, or any deliverable the user asked for.
47
+
48
+ **When to write (mandatory):** right after you finish substantive work, append a short entry to today's log. Substantive work means:
49
+ - built or changed a website or application
50
+ - fixed a bug
51
+ - wrote or generated a report or document
52
+ - refactored code or changed architecture
53
+ - chose a technical approach (framework, design pattern, ...)
54
+ - the user stated workspace conventions or preferences → also update MEMORY.md in place
55
+
56
+ Daily logs are append-only. Do not record transient things (search results, temporary paths, tool errors). Keep only what stays useful in later sessions.
57
+
58
+ Maintenance: distill daily logs older than ${配置.distillAfterDays} days into MEMORY.md by topic, then delete the old files. Never store secrets unless the user asks you to.
59
+
60
+ Tools: memory_read looks at these files (one layer, one day's log, recent days, or a status report); memory_write appends or replaces them, and enforces append-only for daily logs. Plain read/edit calls on the exact absolute paths above work too.
61
+ </memory_system>`
62
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * 记忆文件的读取、注入模板与写入语义。
3
+ *
4
+ * 注入标记、截断算法、空文件处理按 WorkBuddy 5.11.3 的可观察行为实现:
5
+ * - 读取后 trim;文件不存在或内容为空时不注入任何标签
6
+ * - 用户级上限 4,000、项目级上限 10,000,均按 UTF-16 码元计数
7
+ * - 注入是同步的(DSH 的 system prompt section 同步求值),因此读取用 node:fs;
8
+ * 工具写入走 ctx.fs,沿用宿主的原子写与沙箱策略。
9
+ */
10
+ import { readFileSync, readdirSync } from 'node:fs'
11
+ import { join } from 'node:path'
12
+ import { 用户记忆文件名, 项目记忆文件名, 是合法日期 } from './路径.js'
13
+
14
+ /**
15
+ * 按 UTF-16 码元截断,切口落在高位代理时回退一个码元,避免切开代理对。
16
+ * 与 WorkBuddy 的 UTF-16 截断语义一致;JS 的 length 本身就是 UTF-16 码元数。
17
+ */
18
+ export function 截断Utf16(文本, 上限) {
19
+ if (上限 <= 0) return ''
20
+ if (文本.length <= 上限) return 文本
21
+ let 终点 = 上限
22
+ const 码元 = 文本.charCodeAt(终点 - 1)
23
+ if (码元 >= 0xd800 && 码元 <= 0xdbff) --终点
24
+ return 终点 <= 0 ? '' : 文本.slice(0, 终点)
25
+ }
26
+
27
+ /** 同步读取本地文本,区分不存在、读取失败两种情形。 */
28
+ export function 读取本地文本(路径) {
29
+ try {
30
+ return { 状态: 'ok', 文本: readFileSync(路径, 'utf8') }
31
+ } catch (错误) {
32
+ if (错误?.code === 'ENOENT' || 错误?.code === 'ENOTDIR') return { 状态: 'missing', 文本: '' }
33
+ return { 状态: 'error', 文本: '', 错误 }
34
+ }
35
+ }
36
+
37
+ /** 用户级记忆注入块:&lt;user_memory&gt; 包裹,超上限附截断提示。 */
38
+ export function 用户记忆注入块(目录, 上限, 告警 = () => {}) {
39
+ const 路径 = join(目录, 用户记忆文件名)
40
+ const 读取 = 读取本地文本(路径)
41
+ if (读取.状态 === 'error') {
42
+ 告警(`读取用户级 MEMORY.md 失败(${路径}):${读取.错误?.message ?? 读取.错误}`)
43
+ return ''
44
+ }
45
+ if (读取.状态 !== 'ok') return ''
46
+ const 体 = 读取.文本.trim()
47
+ if (体.length === 0) return ''
48
+ const 正文 = 体.length <= 上限 ? 体 : `${截断Utf16(体, 上限)}\n... (user memory truncated)`
49
+ return `<user_memory>
50
+ The following is your long-term user-level memory, persisted across all projects and sessions.
51
+ Use it to understand user preferences, habits, and cross-project conventions.
52
+
53
+ ${正文}
54
+ </user_memory>`
55
+ }
56
+
57
+ /** 项目记忆注入块:&lt;working_memory_content&gt; 包裹,超上限附 WorkBuddy 的清理指令。 */
58
+ export function 项目记忆注入块(目录, 上限, 告警 = () => {}) {
59
+ const 路径 = join(目录, 项目记忆文件名)
60
+ const 读取 = 读取本地文本(路径)
61
+ if (读取.状态 === 'error') {
62
+ 告警(`读取项目 MEMORY.md 失败(${路径}):${读取.错误?.message ?? 读取.错误}`)
63
+ return ''
64
+ }
65
+ if (读取.状态 !== 'ok') return ''
66
+ const 体 = 读取.文本.trim()
67
+ if (体.length === 0) return ''
68
+ if (体.length <= 上限) {
69
+ return `<working_memory_content>
70
+ The following is the existing working memory for this project. Use it as context.
71
+
72
+ ${体}
73
+ </working_memory_content>`
74
+ }
75
+ const 清理指令 = `**ACTION REQUIRED**: Your MEMORY.md has exceeded the size limit and was truncated during injection.
76
+ Before proceeding with the user's task, you MUST first clean up MEMORY.md:
77
+ 1. Read the full \`${目录}/MEMORY.md\`
78
+ 2. Consolidate and deduplicate: merge related entries, remove outdated or redundant information, keep only what's still relevant
79
+ 3. Rewrite it in place to be concise and well-organized
80
+ 4. Then proceed with the user's request`
81
+ return `<working_memory_content>
82
+ The following is the existing working memory for this project. Use it as context.
83
+
84
+ ${截断Utf16(体, 上限)}
85
+ ... (memory truncated — MEMORY.md is too large)
86
+
87
+ ${清理指令}
88
+ </working_memory_content>`
89
+ }
90
+
91
+ /** 项目记忆目录下的每日日志清单,按日期降序。 */
92
+ export function 日志清单(目录) {
93
+ try {
94
+ const 结果 = []
95
+ for (const 项 of readdirSync(目录, { withFileTypes: true })) {
96
+ if (!项.isFile()) continue
97
+ const 日期 = 项.name.replace(/\.md$/i, '')
98
+ if (!是合法日期(日期) || 项.name !== `${日期}.md`) continue
99
+ const 读取 = 读取本地文本(join(目录, 项.name))
100
+ if (读取.状态 !== 'ok') continue
101
+ 结果.push({ 日期, 路径: join(目录, 项.name), 文本: 读取.文本, 长度: 读取.文本.trim().length })
102
+ }
103
+ return 结果.sort((甲, 乙) => 乙.日期.localeCompare(甲.日期))
104
+ } catch {
105
+ return []
106
+ }
107
+ }
108
+
109
+ /** 通过 ctx.fs 读取记忆文件,不存在时返回空文本。 */
110
+ export async function 读取记忆文本(文件系统, 路径, signal) {
111
+ const 目标 = await 文件系统.resolve(路径, { signal })
112
+ const 信息 = await 文件系统.stat(目标, signal)
113
+ if (信息 === undefined) return { 存在: false, 文本: '' }
114
+ const 文本 = await 文件系统.readText(目标, signal)
115
+ return { 存在: true, 文本 }
116
+ }
117
+
118
+ /**
119
+ * 通过 ctx.fs 原子写入(后端自动创建父目录)。
120
+ * 必须传入会话当前的沙箱策略:受限后端的默认模式是 workspace-write,
121
+ * 省略策略会绕过会话的 danger-full-access 设定而被默认模式拒绝。
122
+ */
123
+ export async function 写入记忆文本(文件系统, 路径, 文本, signal, 沙箱策略) {
124
+ const 目标 = await 文件系统.resolve(路径, { signal })
125
+ await 文件系统.writeText(目标, 文本, undefined, signal, 沙箱策略)
126
+ }
127
+
128
+ /** 追加语义:保留已有内容,追加块去尾空白,块之间保证换行,文件以换行结尾。 */
129
+ export function 拼接追加(现有, 内容) {
130
+ const 块 = String(内容 ?? '').replace(/\s+$/u, '')
131
+ if (块.trim().length === 0) throw new Error('追加内容为空')
132
+ if (现有.trim().length === 0) return `${块}\n`
133
+ return `${现有.endsWith('\n') ? 现有 : `${现有}\n`}${块}\n`
134
+ }
135
+
136
+ /** 覆盖语义与 WorkBuddy 设置页一致:先 trim,非空则补一个尾部换行。 */
137
+ export function 规整替换(内容) {
138
+ const 体 = String(内容 ?? '').trim()
139
+ return 体.length === 0 ? '' : `${体}\n`
140
+ }
141
+
142
+ /** 原地编辑:旧文本必须唯一出现,与 WorkBuddy 模型使用 Edit 工具的习惯一致。 */
143
+ export function 原地替换(现有, 旧文本, 新文本) {
144
+ if (typeof 旧文本 !== 'string' || 旧文本.length === 0) throw new Error('old_string 不能为空')
145
+ const 首次 = 现有.indexOf(旧文本)
146
+ if (首次 < 0) throw new Error('未找到 old_string 指定的文本;请先读取文件确认现有内容')
147
+ if (现有.indexOf(旧文本, 首次 + 旧文本.length) >= 0) {
148
+ throw new Error('old_string 在文件中出现多次,请提供更长的唯一片段')
149
+ }
150
+ return 现有.slice(0, 首次) + String(新文本 ?? '') + 现有.slice(首次 + 旧文本.length)
151
+ }
@@ -0,0 +1,109 @@
1
+ # 共享WorkBuddy记忆(dsh-workbuddy-shared-memory)
2
+
3
+ 让 DSH 与 WorkBuddy 桌面应用读写**同一份记忆文件**:任一方写入,另一方下一轮对话就能读到,不需要导入导出、后台同步或重启。
4
+
5
+ ![两个 Agent 共同连接同一组记忆文档,双向读写同一份文件](文档/preview.svg)
6
+
7
+ 共享的载体是磁盘上的 Markdown 文件,不是任何 API。插件遵循 WorkBuddy 5.11.3 已经落盘的文件布局、注入标记与截断上限,而不是另建一套记忆体系——这样两边才真的共用同一份文件。
8
+
9
+ > 本插件与腾讯公司及 WorkBuddy 产品**无任何关联**,未获授权或背书。它不含对方的源代码或资源文件,只遵循对方已经落盘的文件位置、注入标记与截断上限(互操作所必需的事实性约定)。详见仓库根的 [THIRD-PARTY-NOTICES.md](../THIRD-PARTY-NOTICES.md)。
10
+
11
+ > 另有第三方包 `dsh-workbuddy-memory`(作者 Jasery),功能相近但不是本项目,安装时请核对包名。
12
+
13
+ ## 安装
14
+
15
+ 让 DSH 调用 `plugin_manager install_bundle`,target 填 `dsh-workbuddy-shared-memory@0.1.1`,或在 Web 界面的 Plugins 页面安装。要求 DSH `0.2.2-rc.5`(`engines.dsh: ^0.2.2-rc.5`)与 Node `>=22`。装完需要**重启 DSH**(Host 插件在启动时加载),然后**新开会话**。
16
+
17
+ ## 目录对应
18
+
19
+ | 层 | 位置 | 作用 |
20
+ | --- | --- | --- |
21
+ | 用户级记忆 | `~/.workbuddy/user-<uid>-<entId\|personal>/MEMORY.md` | 跨项目、长期强制规则(环境路径、个人约定) |
22
+ | 项目长期笔记 | `<DSH 工作区>/.workbuddy/memory/MEMORY.md` | 当前工作区的精选笔记 |
23
+ | 项目每日日志 | `<DSH 工作区>/.workbuddy/memory/YYYY-MM-DD.md` | 只追加的工作日志 |
24
+
25
+ 核心对应关系:**DSH 工作区目录就是 WorkBuddy 的分组目录**。DSH 会话在哪个工作区,项目级记忆就在该工作区的 `.workbuddy/memory` 下;WorkBuddy 用同一个文件夹作为分组目录时,两边看到的完全是同一批文件。
26
+
27
+ - 项目根**不再向上寻找 `.git`**。默认 `projectRootMarkers: []`,即项目根 = 会话固定的工作区目录(`session.header.cwd`)。会话内 `cd` 到子目录不会改变记忆位置。
28
+ - 只有显式配置了 `projectRootMarkers`(例如 `['.git']`)才会向上找标记;这是 opt-in 的旧行为,不是默认值。
29
+ - 未登录 WorkBuddy 时,用户级目录回退为配置根本身;插件会在配置根下探测 `user-*` 账号目录,也可以用 `userDir` 显式指定。
30
+ - DSH 工作区与 WorkBuddy 分组如果不是同一个文件夹,项目记忆不会自动共享——需要把 DSH 工作区开在分组目录上,或用 `workbuddyRoot` / 路径配置对齐。
31
+
32
+ ## 注入方式
33
+
34
+ 策略和两层记忆内容**都进入 system prompt**,与 WorkBuddy 的注入位置一致:
35
+
36
+ - 策略(静态规则)走 `systemPrompt.section`(`workbuddy-memory:policy`,order `8600`)。路径按当前会话实时解析成**绝对路径**,不再出现 `<项目根>` 占位符。
37
+ - 内容(`<user_memory>` + `<working_memory_content>`)走 `systemPrompt.section`(`workbuddy-memory:content`,order `8601`):每次系统提示词装配都重新读文件。
38
+ - 不再使用 `systemPrompt.context`,因此记忆不会作为 user-role 快照追加进会话历史。代价是:记忆文件变化时 system prompt 文本会变化,DSH 会原地替换该文本,相关前缀缓存可能失效;这是为了让注入位置与 WorkBuddy 对齐而接受的取舍。
39
+ - 用户级上限 **4,000 UTF-16 字符**,项目级上限 **10,000 UTF-16 字符**。截断按 UTF-16 码元计算,切口落到代理对中间时回退一个码元,不会切碎 emoji。用户级超限附加 `... (user memory truncated)`;项目级超限附加 WorkBuddy legacy 的强制清理指令。
40
+ - 文件不存在、内容 trim 后为空就完全不注入;读取失败只告警,不影响对话。
41
+ - 写入规则随策略注入:用户明确要求长期记住时更新用户级文件;完成实质性工作后追加当日日志;用户分享项目约定时更新项目笔记;超过 30 天的日志蒸馏进项目笔记后删除。
42
+
43
+ ## 工具
44
+
45
+ | 工具 | 用途 |
46
+ | --- | --- |
47
+ | `memory_read` | `target=user/project/daily/recent/status`;读单层记忆、某日日志、最近日志或状态报告(路径、长度、注入上限、待蒸馏清单),长文件支持 `offset/limit` 分页 |
48
+ | `memory_write` | `target=user/project/daily`,`mode=append/replace`;`daily` 强制只追加;`replace` 可配 `old_string`/`new_string` 做唯一片段原地编辑 |
49
+
50
+ 直接使用 DSH 自带的 `read`/`edit` 操作上述绝对路径也可以,两条路并不冲突。
51
+
52
+ ## 配置
53
+
54
+ 在 `cordis.patch.yml` 的 `workbuddy-memory` 行里写 config:
55
+
56
+ | 字段 | 默认 | 含义 |
57
+ | --- | --- | --- |
58
+ | `enabled` | `true` | 总开关 |
59
+ | `dataFolderName` | `''` | 数据目录名,缺省读 `WORKBUDDY_DATA_FOLDER_NAME` 或 `.workbuddy` |
60
+ | `workbuddyRoot` | `''` | WorkBuddy 配置根,缺省读 `WORKBUDDY_CONFIG_DIR` 或 `~/<数据目录名>` |
61
+ | `userDir` | `''` | 显式指定用户级记忆目录,缺省自动探测 `user-*` |
62
+ | `userMemoryLimit` | `4000` | 用户级注入上限(UTF-16 字符) |
63
+ | `projectMemoryLimit` | `10000` | 项目级注入上限(UTF-16 字符) |
64
+ | `sessionWriteBudget` | `3000` | 写进提示词的项目笔记每会话预算 |
65
+ | `distillAfterDays` | `30` | 超过该天数的日志进入待蒸馏清单 |
66
+ | `injectPolicy` / `injectContent` | `true` | 分别控制策略提示词与记忆内容注入 |
67
+ | `projectRootMarkers` | `[]` | 项目根标记;空 = 直接用会话工作区目录,非空才向上找 |
68
+
69
+ ## 沙箱与写入
70
+
71
+ - 项目级记忆在 DSH 工作区内,`workspace-write` 下可直接写。
72
+ - 用户级记忆在工作区外。`memory_write` 的 `target=user` 会在写入前为该**会话**懒注册可写根:优先注册已存在的用户级目录,否则注册配置根;每个会话只注册一次。`read-only` 仍然拒绝,`danger-full-access` 不需要注册。
73
+ - 这个可写根是 DSH 运行时状态,只对当前会话有效;resume / fork 后的新会话首次写入会重新注册。
74
+ - 直接用 `read`/`edit` 工具改用户级文件不会触发注册;在 `workspace-write` 下仍会被宿主拒绝,此时请用 `memory_write target=user`。
75
+ - 显式 `userDir` 指向配置根之外且尚未创建的目录时,懒注册会退回配置根,可能仍覆盖不到该目录;请先创建 `userDir`。
76
+
77
+ ## 限制
78
+
79
+ - **没有云端记忆层**:WorkBuddy 的服务端画像与 `conversation_search` 依赖腾讯服务端,本插件不涉及;策略只描述用户级与项目级两层本地记忆。
80
+ - **对齐的是 legacy 本地记忆布局**:不针对 WorkBuddy 的 platform 模式(服务端云记忆 + 本地缓存)做适配。
81
+ - **用户账号目录仍是启发式**:多个 `user-*` 目录并存时按 `MEMORY.md` 的 mtime 选择,可能选错;请用 `userDir` 固定。
82
+ - **跨进程并发**:没有跨进程文件锁,WorkBuddy 与 DSH 同时写同一文件时后写者覆盖先写者;进程内的并行工具调用已串行化。
83
+ - **项目根语义**:默认不做任何上溯,所以 DSH 工作区必须就是 WorkBuddy 分组目录;跨工作区不共享项目记忆。
84
+ - **无提交的自动化测试**:当前靠合成工作区脚本与本机联调验证;补正式测试是待办。
85
+
86
+ ## 真机验证
87
+
88
+ 1. 重启 DSH 后新开会话,`memory_read`(`target=status`),确认「用户级目录 / 工作区目录 / 项目根 / 项目记忆目录」符合预期。
89
+ 2. `memory_write` 往当日日志追加一条,检查 `<DSH 工作区>/.workbuddy/memory/YYYY-MM-DD.md`;在 WorkBuddy 打开同一分组问「今天做了什么」,应能看到。
90
+ 3. 反向在 WorkBuddy 里让它记住一条规则,回 DSH **新开会话**(让 system prompt 重新装配)后 `memory_read target=user` 应能读到,且模型回答能引用它。
91
+ 4. 在 `workspace-write` 下测试 `memory_write target=user`,应成功;直接 `edit` 用户级文件则应被宿主拒绝,这符合预期。
92
+
93
+ ## 开发
94
+
95
+ ```bash
96
+ pnpm install --offline
97
+ pnpm run check # 五个运行时文件逐个 node --check
98
+ npm pack --dry-run # 看发布内容
99
+ ```
100
+
101
+ 纯 JavaScript,无构建步骤:`exports` 直接指向包根的 `入口.js`。本地 `node_modules` 里的 peer 依赖是 pnpm 链接;如果目录被改名,需要重新 `pnpm install` 修复链接。
102
+
103
+ ## 包内文件
104
+
105
+ `入口.js`(插件入口与配置)、`路径.js`(记忆目录解析)、`记忆文件.js`(注入模板/截断/写入语义)、`策略.js`(记忆策略提示词)、`工具.js`(两个模型工具)、`cordis.patch.yml`(bundle 补丁)、`图标.svg`、`文档/preview.svg`。
106
+
107
+ ## 许可
108
+
109
+ MIT,见 [LICENSE](LICENSE)。
@@ -0,0 +1,95 @@
1
+ /**
2
+ * WorkBuddy 记忆路径解析。
3
+ *
4
+ * 按 WorkBuddy 5.11.3 的实际目录布局实现:
5
+ * - 数据目录名:WORKBUDDY_DATA_FOLDER_NAME 或 '.workbuddy'
6
+ * - 配置根目录:WORKBUDDY_CONFIG_DIR 或 ~/<数据目录名>
7
+ * - 用户级目录:user-<uid>-<enterpriseId|personal>,未登录时回退到配置根
8
+ * - 项目级目录:<项目根>/<数据目录名>/memory
9
+ */
10
+ import { homedir } from 'node:os'
11
+ import { dirname, join, resolve } from 'node:path'
12
+ import { existsSync, readdirSync, statSync } from 'node:fs'
13
+
14
+ export const 默认数据目录名 = '.workbuddy'
15
+
16
+ /** WorkBuddy 的数据目录名(项目级记忆与配置根共用此约定)。 */
17
+ export function 数据目录名(配置) {
18
+ return 配置.dataFolderName?.trim()
19
+ || process.env.WORKBUDDY_DATA_FOLDER_NAME?.trim()
20
+ || 默认数据目录名
21
+ }
22
+
23
+ /** WorkBuddy 的配置根目录,用户级记忆存放在这里。 */
24
+ export function 配置根目录(配置) {
25
+ return 配置.workbuddyRoot?.trim()
26
+ || process.env.WORKBUDDY_CONFIG_DIR?.trim()
27
+ || join(homedir(), 数据目录名(配置))
28
+ }
29
+
30
+ /**
31
+ * 解析用户级记忆目录。
32
+ * 优先使用显式配置;否则在配置根下挑选账号目录:含有 MEMORY.md 的优先,
33
+ * 多个候选取最近修改者;没有任何账号目录时回退到配置根本身(未登录形态)。
34
+ */
35
+ export function 用户记忆目录(配置) {
36
+ const 指定 = 配置.userDir?.trim()
37
+ if (指定) return 指定
38
+ const 根 = 配置根目录(配置)
39
+ try {
40
+ const 账号目录 = []
41
+ for (const 项 of readdirSync(根, { withFileTypes: true })) {
42
+ if (!项.isDirectory() || !项.name.startsWith('user-')) continue
43
+ const 目录 = join(根, 项.name)
44
+ let 时间 = -1
45
+ try { 时间 = statSync(join(目录, 'MEMORY.md')).mtimeMs } catch { /* 没有记忆文件也算候选 */ }
46
+ 账号目录.push({ 目录, 时间 })
47
+ }
48
+ if (账号目录.length > 0) {
49
+ 账号目录.sort((甲, 乙) => 乙.时间 - 甲.时间)
50
+ return 账号目录[0].目录
51
+ }
52
+ } catch { /* 配置根不可读时按未登录处理 */ }
53
+ return 根
54
+ }
55
+
56
+ /** 从会话工作目录向上寻找项目根;标记列表为空时直接以会话目录为项目根(WorkBuddy 分组语义)。 */
57
+ export function 项目根目录(工作目录, 标记列表) {
58
+ const 起点 = resolve(工作目录)
59
+ const 标记 = (标记列表 ?? []).filter((项) => typeof 项 === 'string' && 项.length > 0)
60
+ if (标记.length === 0) return 起点
61
+ let 当前 = 起点
62
+ while (true) {
63
+ for (const 标记项 of 标记) {
64
+ try { if (existsSync(join(当前, 标记项))) return 当前 } catch { /* 忽略不可读目录 */ }
65
+ }
66
+ const 父级 = dirname(当前)
67
+ if (父级 === 当前) return 起点
68
+ 当前 = 父级
69
+ }
70
+ }
71
+
72
+ /** 项目级记忆目录:<项目根>/<数据目录名>/memory。 */
73
+ export function 项目记忆目录由根(根, 配置) {
74
+ return join(根, 数据目录名(配置), 'memory')
75
+ }
76
+
77
+ export function 项目记忆目录(工作目录, 配置) {
78
+ const 根 = 项目根目录(工作目录, 配置.projectRootMarkers)
79
+ return 项目记忆目录由根(根, 配置)
80
+ }
81
+
82
+ /** 本地时区的 YYYY-MM-DD,与每日日志文件名一致。 */
83
+ export function 今天日期(此刻 = new Date()) {
84
+ const 年 = 此刻.getFullYear()
85
+ const 月 = String(此刻.getMonth() + 1).padStart(2, '0')
86
+ const 日 = String(此刻.getDate()).padStart(2, '0')
87
+ return `${年}-${月}-${日}`
88
+ }
89
+
90
+ export function 是合法日期(文本) {
91
+ return typeof 文本 === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(文本)
92
+ }
93
+
94
+ export const 用户记忆文件名 = 'MEMORY.md'
95
+ export const 项目记忆文件名 = 'MEMORY.md'
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.