dsh-workbuddy-shared-memory 0.0.0-stage → 0.1.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 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.0",
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,93 @@
1
+ /**
2
+ * WorkBuddy 共享记忆 —— Host 插件入口。
3
+ *
4
+ * 两个注入通道:
5
+ * - 策略(静态规则)走 systemPrompt.section,文本稳定,保持 KV 缓存前缀;
6
+ * - 内容(两个 XML 快照)走 systemPrompt.context,每次装配重新读文件,
7
+ * 内容不变时 DSH 不追加新快照,变化时作为 sourced user-role 快照进入历史。
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(['.git']),
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: ['.git'],
44
+ }
45
+
46
+ /** 组装本轮要注入的记忆快照;任何一层失败都只告警,不影响对话。 */
47
+ function 注入记忆内容(ctx, 配置, 上下文, 告警) {
48
+ const 块 = []
49
+ try {
50
+ const 文本 = 用户记忆注入块(用户记忆目录(配置), 配置.userMemoryLimit, 告警)
51
+ if (文本) 块.push(文本)
52
+ } catch (错误) {
53
+ 告警(`用户级记忆注入失败:${错误?.message ?? 错误}`)
54
+ }
55
+ try {
56
+ const agent = 上下文?.agent
57
+ if (agent?.session !== undefined) {
58
+ const cwd = ctx.workingDirectory.get(agent.session)
59
+ const 文本 = 项目记忆注入块(项目记忆目录(cwd, 配置), 配置.projectMemoryLimit, 告警)
60
+ if (文本) 块.push(文本)
61
+ }
62
+ } catch (错误) {
63
+ 告警(`项目记忆注入失败:${错误?.message ?? 错误}`)
64
+ }
65
+ return 块.join('\n\n')
66
+ }
67
+
68
+ export function apply(ctx, 用户配置 = {}) {
69
+ const 配置 = { ...默认配置, ...用户配置 }
70
+ if (!配置.enabled) return
71
+ const 告警 = (文本) => ctx.logger.warn(`[WorkBuddy 记忆] ${文本}`)
72
+
73
+ if (配置.injectPolicy) {
74
+ ctx.systemPrompt.section({
75
+ name: 'workbuddy-memory:policy',
76
+ order: 8600,
77
+ interpolate: false,
78
+ text: () => 策略文本(配置),
79
+ })
80
+ }
81
+
82
+ if (配置.injectContent) {
83
+ ctx.systemPrompt.context({
84
+ name: 'workbuddy-memory:content',
85
+ order: 300,
86
+ required: true,
87
+ interpolate: false,
88
+ text: (上下文) => 注入记忆内容(ctx, 配置, 上下文, 告警),
89
+ })
90
+ }
91
+
92
+ for (const 工具 of 创建工具({ ctx, 配置 })) ctx.tools.register(工具)
93
+ }
@@ -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,219 @@
1
+ /**
2
+ * 模型侧工具:memory_read / memory_write。
3
+ * 工具名遵循 DSH 命名契约使用英文;读写路径与 WorkBuddy 桌面应用保持一致(互操作所需)。
4
+ */
5
+ import { join } from 'node:path'
6
+ import { defineTool } from '@deepseek-ai/dsh-tools'
7
+ import {
8
+ 项目记忆目录, 用户记忆目录, 项目根目录, 数据目录名,
9
+ 今天日期, 是合法日期, 用户记忆文件名, 项目记忆文件名,
10
+ } from './路径.js'
11
+ import {
12
+ 读取本地文本, 日志清单, 读取记忆文本, 写入记忆文本,
13
+ 拼接追加, 规整替换, 原地替换,
14
+ } from './记忆文件.js'
15
+
16
+ /** 同一文件的写入在进程内串行,避免并行工具调用互相覆盖。 */
17
+ const 写入队列 = new Map()
18
+ function 串行写入(路径, 任务) {
19
+ const 前序 = 写入队列.get(路径) ?? Promise.resolve()
20
+ const 当前 = 前序.then(任务, 任务)
21
+ 写入队列.set(路径, 当前)
22
+ const 清理 = () => { if (写入队列.get(路径) === 当前) 写入队列.delete(路径) }
23
+ 当前.then(清理, 清理)
24
+ return 当前
25
+ }
26
+
27
+ function 文本输出(_参数, 值) {
28
+ return [{ type: 'text', text: 值 }]
29
+ }
30
+
31
+ function 分页(文本, offset, limit) {
32
+ const 起点 = Number.isInteger(offset) && offset > 0 ? offset : 0
33
+ const 上限 = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 20000) : 12000
34
+ const 片段 = 文本.slice(起点, 起点 + 上限)
35
+ const 下一段 = 起点 + 片段.length < 文本.length ? 起点 + 片段.length : null
36
+ return { 片段, 下一段, 起点 }
37
+ }
38
+
39
+ export function 创建工具(环境) {
40
+ const { ctx, 配置 } = 环境
41
+
42
+ async function 会话目录(exec) {
43
+ if (exec.agent === undefined) throw new Error('记忆工具需要在活动的 DSH 会话中使用')
44
+ return ctx.workingDirectory.ensure(exec.agent, exec.signal)
45
+ }
46
+
47
+ function 文件系统() {
48
+ const fs = ctx.get('fs')
49
+ if (fs === undefined) throw new Error('当前部署没有可用的文件系统服务(ctx.fs),无法读写记忆文件')
50
+ return fs
51
+ }
52
+
53
+ /** 会话当前的沙箱策略(含模式与工作区根);与 dsh-tool-fs 不提权时的取值一致。 */
54
+ function 沙箱策略(exec) {
55
+ const 服务 = ctx.get('sandboxPolicy')
56
+ return 服务?.resolve({ ...(exec.agent ? { session: exec.agent.session } : {}) })
57
+ }
58
+
59
+ function 目标路径(target, cwd, date) {
60
+ if (target === 'user') return join(用户记忆目录(配置), 用户记忆文件名)
61
+ const 目录 = 项目记忆目录(cwd, 配置)
62
+ if (target === 'project') return join(目录, 项目记忆文件名)
63
+ return join(目录, `${date ?? 今天日期()}.md`)
64
+ }
65
+
66
+ function 长度说明(文本, 上限) {
67
+ const 长度 = 文本.trim().length
68
+ const 超限 = 长度 > 上限
69
+ return { 长度, 超限, 描述: `${长度} / 注入上限 ${上限} UTF-16 字符${超限 ? '(已超限,注入时会被截断)' : ''}` }
70
+ }
71
+
72
+ const memoryRead = defineTool({
73
+ name: 'memory_read',
74
+ description: '读取与 WorkBuddy 共享的记忆文件。target=user 为跨项目用户记忆,project 为当前项目长期笔记,daily 为某一天的项目日志,recent 为最近若干天日志,status 报告两层路径、长度、注入上限与待蒸馏日志。daily/recent 不会自动注入提示词,需要历史背景时主动读取。',
75
+ parameters: {
76
+ target: { type: 'string', required: true, enum: ['user', 'project', 'daily', 'recent', 'status'], description: '读取对象:user 用户级 MEMORY.md;project 项目 MEMORY.md;daily 单日日志;recent 最近日志;status 状态报告' },
77
+ date: { type: 'string', description: 'daily 用,YYYY-MM-DD,缺省为今天(本地时区)' },
78
+ days: { type: 'number', description: 'recent 用,返回最近几篇日志,默认 3,最大 30' },
79
+ offset: { type: 'number', description: 'user/project/daily 的字符偏移,从 0 开始,用于分页读取长文件' },
80
+ limit: { type: 'number', description: '单次最多返回的字符数,默认 12000,最大 20000' },
81
+ },
82
+ output: { schema: { type: 'string' }, render: 文本输出 },
83
+ async execute(args, exec) {
84
+ const cwd = await 会话目录(exec)
85
+ const target = args.target
86
+
87
+ if (target === 'status') {
88
+ const 用户目录 = 用户记忆目录(配置)
89
+ const 用户路径 = join(用户目录, 用户记忆文件名)
90
+ const 项目目录 = 项目记忆目录(cwd, 配置)
91
+ const 项目路径 = join(项目目录, 项目记忆文件名)
92
+ const 行 = ['WorkBuddy 共享记忆状态', '']
93
+ 行.push(`数据目录名:${数据目录名(配置)}`)
94
+ 行.push(`用户级目录:${用户目录}`)
95
+ const 用户读取 = 读取本地文本(用户路径)
96
+ if (用户读取.状态 === 'ok') {
97
+ 行.push(` MEMORY.md:存在,${长度说明(用户读取.文本, 配置.userMemoryLimit).描述}`)
98
+ } else if (用户读取.状态 === 'missing') {
99
+ 行.push(' MEMORY.md:不存在(不注入用户级记忆)')
100
+ } else {
101
+ 行.push(` MEMORY.md:读取失败(${用户读取.错误?.message ?? 用户读取.错误})`)
102
+ }
103
+ const 根 = 项目根目录(cwd, 配置.projectRootMarkers)
104
+ 行.push(`会话工作目录:${cwd}`)
105
+ 行.push(`项目根:${根}`)
106
+ 行.push(`项目记忆目录:${项目目录}`)
107
+ const 项目读取 = 读取本地文本(项目路径)
108
+ if (项目读取.状态 === 'ok') {
109
+ 行.push(` MEMORY.md:存在,${长度说明(项目读取.文本, 配置.projectMemoryLimit).描述}`)
110
+ } else if (项目读取.状态 === 'missing') {
111
+ 行.push(' MEMORY.md:不存在(不注入项目记忆)')
112
+ } else {
113
+ 行.push(` MEMORY.md:读取失败(${项目读取.错误?.message ?? 项目读取.错误})`)
114
+ }
115
+ const 今日 = 今天日期()
116
+ const 日志 = 日志清单(项目目录)
117
+ 行.push(`今日日期:${今日};今日日志:${日志.some(项 => 项.日期 === 今日) ? '已存在' : '不存在'}`)
118
+ if (日志.length === 0) {
119
+ 行.push('每日日志:暂无')
120
+ } else {
121
+ 行.push(`每日日志(共 ${日志.length} 篇,新到旧):`)
122
+ for (const 项 of 日志) 行.push(` ${项.日期}:${项.长度} UTF-16 字符`)
123
+ const 截止 = new Date()
124
+ 截止.setDate(截止.getDate() - 配置.distillAfterDays)
125
+ const 待蒸馏 = 日志.filter(项 => new Date(`${项.日期}T00:00:00`) < 截止)
126
+ 行.push(待蒸馏.length > 0
127
+ ? `待蒸馏(早于 ${配置.distillAfterDays} 天前):${待蒸馏.map(项 => 项.日期).join('、')};请按主题并入项目 MEMORY.md 后删除旧文件`
128
+ : `没有超过 ${配置.distillAfterDays} 天的待蒸馏日志`)
129
+ }
130
+ return 行.join('\n')
131
+ }
132
+
133
+ if (target === 'recent') {
134
+ const 目录 = 项目记忆目录(cwd, 配置)
135
+ const 日志 = 日志清单(目录)
136
+ if (日志.length === 0) return `项目记忆目录 ${目录} 下还没有每日日志。`
137
+ const 篇数 = Number.isInteger(args.days) && args.days > 0 ? Math.min(args.days, 30) : 3
138
+ const 选取 = 日志.slice(0, 篇数)
139
+ const 正文 = 选取.map(项 => `## ${项.日期}(${项.长度} UTF-16 字符)\n路径:${项.路径}\n\n${项.文本.trim() || '(空文件)'}`).join('\n\n')
140
+ const { 片段, 下一段 } = 分页(正文, args.offset, args.limit)
141
+ const 提示 = 下一段 === null ? '' : `\n\n[输出已截断;用 offset=${下一段} 继续读取]`
142
+ return `项目记忆目录:${目录}\n最近 ${选取.length} 篇日志(新到旧,共 ${日志.length} 篇):\n\n${片段}${提示}`
143
+ }
144
+
145
+ const date = args.date ?? 今天日期()
146
+ if (target === 'daily' && !是合法日期(date)) throw new Error('date 必须是 YYYY-MM-DD 格式')
147
+ const 路径 = 目标路径(target, cwd, date)
148
+ const 读取 = 读取本地文本(路径)
149
+ if (读取.状态 === 'missing') return `文件不存在:${路径}\n(尚未记录${target === 'user' ? '用户级' : target === 'project' ? '项目' : '该日'}记忆;可用 memory_write 创建。)`
150
+ if (读取.状态 === 'error') throw new Error(`读取失败:${读取.错误?.message ?? 读取.错误}`)
151
+ const 头部 = [`路径:${路径}`]
152
+ if (target === 'user') 头部.push(`长度:${长度说明(读取.文本, 配置.userMemoryLimit).描述}`)
153
+ if (target === 'project') 头部.push(`长度:${长度说明(读取.文本, 配置.projectMemoryLimit).描述}`)
154
+ if (target === 'daily') 头部.push(`长度:${读取.文本.trim().length} UTF-16 字符(日志不自动注入,只追加)`)
155
+ const { 片段, 下一段, 起点 } = 分页(读取.文本, args.offset, args.limit)
156
+ if (起点 > 0) 头部.push(`分页:从字符 ${起点} 开始`)
157
+ const 提示 = 下一段 === null ? '' : `\n\n[文件未读完;用 offset=${下一段} 继续读取]`
158
+ return `${头部.join('\n')}\n\n${片段}${提示}`
159
+ },
160
+ })
161
+
162
+ const memoryWrite = defineTool({
163
+ name: 'memory_write',
164
+ description: '写入与 WorkBuddy 共享的记忆文件,另一边(WorkBuddy 或 DSH)下一轮即可读到。target=user 写跨项目用户 MEMORY.md,project 写当前项目 MEMORY.md,daily 写项目每日日志(只允许 append)。mode=append 追加到末尾,replace 覆盖全文(先 trim 再补尾部换行);replace 时提供 old_string/new_string 可原地编辑唯一片段。写入不会自动删减内容,但超过注入上限的记忆在注入时会被截断。',
165
+ parameters: {
166
+ target: { type: 'string', required: true, enum: ['user', 'project', 'daily'], description: '写入对象:user 用户级 MEMORY.md;project 项目 MEMORY.md;daily 每日日志(仅 append)' },
167
+ mode: { type: 'string', required: true, enum: ['append', 'replace'], description: 'append 追加到文件末尾;replace 覆盖全文,或配合 old_string 做原地编辑' },
168
+ content: { type: 'string', required: true, description: 'append/replace 时写入的 Markdown 文本;原地编辑时作为 new_string 的缺省(也可用 new_string 显式给出)' },
169
+ date: { type: 'string', description: 'daily 用,YYYY-MM-DD,缺省为今天(本地时区)' },
170
+ old_string: { type: 'string', description: '仅 target=user/project 且 mode=replace:要在现有文件中替换的唯一文本片段' },
171
+ new_string: { type: 'string', description: '配合 old_string 的替换文本;缺省使用 content' },
172
+ },
173
+ output: { schema: { type: 'string' }, render: 文本输出 },
174
+ async execute(args, exec) {
175
+ const cwd = await 会话目录(exec)
176
+ const { target, mode } = args
177
+ if (target === 'daily' && mode !== 'append') {
178
+ throw new Error('每日日志为 append-only:请使用 mode=append,不要覆盖历史日志')
179
+ }
180
+ if (target === 'daily' && args.old_string !== undefined) {
181
+ throw new Error('每日日志不支持 old_string 原地编辑;请用 mode=append 追加新记录')
182
+ }
183
+ if (args.old_string !== undefined && mode !== 'replace') {
184
+ throw new Error('old_string 仅适用于 mode=replace 的原地编辑')
185
+ }
186
+ const date = args.date ?? 今天日期()
187
+ if (target === 'daily' && !是合法日期(date)) throw new Error('date 必须是 YYYY-MM-DD 格式')
188
+ const 路径 = 目标路径(target, cwd, date)
189
+ const fs = 文件系统()
190
+
191
+ return 串行写入(路径, async () => {
192
+ const 现有 = await 读取记忆文本(fs, 路径, exec.signal)
193
+ let 新文本
194
+ let 操作
195
+ if (args.old_string !== undefined) {
196
+ if (!现有.存在) throw new Error(`文件不存在:${路径},无法原地编辑;请先用 mode=replace 创建`)
197
+ 新文本 = 原地替换(现有.文本, args.old_string, args.new_string ?? args.content)
198
+ 操作 = '原地编辑'
199
+ } else if (mode === 'append') {
200
+ 新文本 = 拼接追加(现有.文本, args.content)
201
+ 操作 = 现有.存在 ? '追加' : '新建并写入'
202
+ } else {
203
+ 新文本 = 规整替换(args.content)
204
+ 操作 = 现有.存在 ? '覆盖' : '新建'
205
+ }
206
+ await 写入记忆文本(fs, 路径, 新文本, exec.signal, 沙箱策略(exec))
207
+ const 行 = [`已${操作}:${路径}`, `文件长度:${新文本.trim().length} UTF-16 字符`]
208
+ const 上限 = target === 'user' ? 配置.userMemoryLimit : target === 'project' ? 配置.projectMemoryLimit : null
209
+ if (上限 !== null && 新文本.trim().length > 上限) {
210
+ 行.push(`注意:已超过注入上限 ${上限},注入提示词时会被截断;请尽快合并去重、精简该文件。`)
211
+ }
212
+ if (target === 'daily') 行.push('日志已保存为 append-only;如需长期沉淀,请把要点提炼到项目 MEMORY.md。')
213
+ return 行.join('\n')
214
+ })
215
+ },
216
+ })
217
+
218
+ return [memoryRead, memoryWrite]
219
+ }
@@ -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,55 @@
1
+ /**
2
+ * 记忆策略提示词:与 WorkBuddy 记忆层的规则保持一致(但不含其云端记忆层),
3
+ * 作为静态系统提示词章节注入,文本稳定以保持 KV 缓存前缀。
4
+ *
5
+ * 文案为本项目自行撰写,不复制对方提示词原文;规则条目与被注入的路径、
6
+ * 上限、标记则必须与真实行为一致,否则模型会按错误的约定写文件。
7
+ */
8
+ import { 数据目录名, 用户记忆目录 } from './路径.js'
9
+
10
+ /** 生成策略文本;每次装配重新解析用户目录,账号切换后路径随之更新。 */
11
+ export function 策略文本(配置) {
12
+ const 用户目录 = 用户记忆目录(配置)
13
+ const 标记说明 = 配置.projectRootMarkers.join(' / ')
14
+ 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 turn.
15
+ <memory_system>
16
+
17
+ # Layer 1 — User-level Local Memory (read/write)
18
+
19
+ File: ${用户目录}/MEMORY.md | Scope: all projects | Injected limit: ${配置.userMemoryLimit} UTF-16 chars
20
+
21
+ 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.
22
+ Treat the file as explicitly written: precise, mandatory rules belong here — environment paths, standing conventions, cross-project preferences.
23
+ Only the injected copy is truncated past the limit; the file itself never gets truncated.
24
+
25
+ # Layer 2 — Workspace Memory (read/write)
26
+
27
+ Directory: <project root>/${数据目录名(配置)}/memory/ | Scope: the current project only
28
+ The project root is the nearest ancestor of the session working directory that contains ${标记说明}; if no ancestor does, the session working directory is the project root. The memory tools resolve it for you.
29
+
30
+ Files:
31
+ - YYYY-MM-DD.md — daily work log. Append-only: never overwrite it.
32
+ - MEMORY.md — curated long-term notes for this project. Limit: ${配置.sessionWriteBudget} chars per session.
33
+ - If today's file is absent, create the directory and the dated file first (memory_write does this automatically).
34
+
35
+ Reading history: pick the source you need instead of reading everything.
36
+ - Work this project did before → recent daily logs first, then MEMORY.md.
37
+ - Nothing depends on history → skip the memory files entirely.
38
+
39
+ Scope of responsibility: workspace memory is supplementary only. It never replaces your reply, your final answer, or any deliverable the user asked for.
40
+
41
+ **When to write (mandatory):** right after you finish substantive work, append a short entry to today's log. Substantive work means:
42
+ - built or changed a website or application
43
+ - fixed a bug
44
+ - wrote or generated a report or document
45
+ - refactored code or changed architecture
46
+ - chose a technical approach (framework, design pattern, ...)
47
+ - the user stated project conventions or preferences → also update MEMORY.md in place
48
+
49
+ Daily logs are append-only. Do not record transient things (search results, temporary paths, tool errors). Keep only what stays useful in later sessions.
50
+
51
+ 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.
52
+
53
+ 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 same paths work too.
54
+ </memory_system>`
55
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * 记忆文件的读取、注入模板与写入语义。
3
+ *
4
+ * 注入标记、截断算法、空文件处理按 WorkBuddy 5.11.3 的可观察行为实现:
5
+ * - 读取后 trim;文件不存在或内容为空时不注入任何标签
6
+ * - 用户级上限 4,000、项目级上限 10,000,均按 UTF-16 码元计数
7
+ * - 注入是同步的(DSH 的 context provider 同步求值),因此读取用 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,94 @@
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.0`,或在 Web 界面的 Plugins 页面安装。要求 DSH `0.2.2-rc.5`(`engines.dsh: ^0.2.2-rc.5`)与 Node `>=22`。装完**新开会话**生效。
16
+
17
+ ## 共享的文件
18
+
19
+ | 层 | 路径 | 作用 |
20
+ | ------ | ----------------------------------------------------- | --------------------- |
21
+ | 用户级记忆 | `~/.workbuddy/user-<uid>-<entId\|personal>/MEMORY.md` | 跨项目、长期强制规则(环境路径、个人约定) |
22
+ | 项目长期笔记 | `<项目根>/.workbuddy/memory/MEMORY.md` | 当前项目的精选笔记 |
23
+ | 项目每日日志 | `<项目根>/.workbuddy/memory/YYYY-MM-DD.md` | 只追加的工作日志 |
24
+
25
+ - 项目根 = 从 DSH 会话工作目录向上找到的最近一个含 `.git` 的祖先(标记可配置,默认 `['.git']`);没有标记时会话目录本身就是项目根。
26
+ - 未登录 WorkBuddy 时,用户级目录回退为 `~/.workbuddy/` 本身;插件自动探测账号目录,也可以用 `userDir` 显式指定。
27
+ - 只要 DSH 会话落在 WorkBuddy 的同一工作区里,项目记忆就是同一份,不需要复制。
28
+
29
+ ## 注入方式
30
+
31
+ - 策略(静态规则)走 `systemPrompt.section`(`workbuddy-memory:policy`),文本稳定,保持 KV 缓存前缀。
32
+ - 内容(两份快照)走 `systemPrompt.context`(`workbuddy-memory:content`):每次装配重新读文件,内容没变就不追加新快照,变了才作为 sourced user-role 快照进入历史。
33
+ - 用户级以 `<user_memory>` 包裹,上限 **4,000 UTF-16 字符**;项目级以 `<working_memory_content>` 包裹,上限 **10,000 UTF-16 字符**。截断按 UTF-16 码元计算,切口落到代理对中间时回退一个码元,不会切碎 emoji。
34
+ - 文件不存在或内容为空就完全不注入;读取失败只告警,不影响对话。
35
+ - 项目记忆超限时附带「先清理 MEMORY.md 再继续任务」的指令。
36
+ - 写入规则注入系统提示词:用户明确要求长期记住时更新用户级文件;完成实质性工作后追加当日日志;用户分享项目约定时更新项目笔记;超过 30 天的日志蒸馏进项目笔记后删除。
37
+
38
+ ## 工具
39
+
40
+ | 工具 | 用途 |
41
+ | -------------- | ---------------------------------------------------------------------------------------------------------------- |
42
+ | `memory_read` | `target=user/project/daily/recent/status`;读单层记忆、某日日志、最近日志或状态报告(路径、长度、注入上限、待蒸馏清单),长文件支持 `offset/limit` 分页 |
43
+ | `memory_write` | `target=user/project/daily`,`mode=append/replace`;`daily` 强制只追加;`replace` 可配 `old_string`/`new_string` 做唯一片段原地编辑 |
44
+
45
+ 直接使用 DSH 自带的 `read`/`edit` 操作上述路径也可以,两条路并不冲突。
46
+
47
+ ## 配置
48
+
49
+ 在 `cordis.patch.yml` 的 `workbuddy-memory` 行里写 config:
50
+
51
+ | 字段 | 默认 | 含义 |
52
+ | -------------------------------- | ---------- | --------------------------------------------------------- |
53
+ | `enabled` | `true` | 总开关 |
54
+ | `dataFolderName` | `''` | 数据目录名,缺省读 `WORKBUDDY_DATA_FOLDER_NAME` 或 `.workbuddy` |
55
+ | `workbuddyRoot` | `''` | WorkBuddy 配置根,缺省读 `WORKBUDDY_CONFIG_DIR` 或 `~/.workbuddy` |
56
+ | `userDir` | `''` | 显式指定用户级记忆目录,缺省自动探测 |
57
+ | `userMemoryLimit` | `4000` | 用户级注入上限(UTF-16 字符) |
58
+ | `projectMemoryLimit` | `10000` | 项目级注入上限(UTF-16 字符) |
59
+ | `sessionWriteBudget` | `3000` | 写进提示词的项目笔记每会话预算 |
60
+ | `distillAfterDays` | `30` | 超过该天数的日志进入待蒸馏清单 |
61
+ | `injectPolicy` / `injectContent` | `true` | 分别控制策略提示词与记忆内容注入 |
62
+ | `projectRootMarkers` | `['.git']` | 项目根标记 |
63
+
64
+ ## 限制
65
+
66
+ - **没有云端记忆层**:WorkBuddy 的服务端画像与 `conversation_search` 依赖腾讯服务端,本插件不涉及。
67
+ - **沙箱**:写入走 DSH 的 `ctx.fs`。`workspace-write` 下位于工作区之外的用户级目录会被宿主拒绝(返回明确错误),`danger-full-access` 下正常。
68
+ - **跨进程并发**:没有跨进程文件锁,WorkBuddy 与 DSH 同时写同一文件时后写者覆盖先写者;进程内的并行工具调用已串行化。
69
+ - **项目根判定**:跨工作区不共享项目记忆(与 WorkBuddy 语义一致)。
70
+ - **无自动化测试**:当前靠真机联调验证(见下)。补测试是待办。
71
+
72
+ ## 真机验证
73
+
74
+ 1. 新会话里 `memory_read`(`target=status`),确认两层路径与实际目录一致。
75
+ 2. `memory_write` 往当日日志追加一条,在 WorkBuddy 打开同一工作区问「今天做了什么」,应能看到。
76
+ 3. 反向在 WorkBuddy 里让它记住一条规则,回 DSH 新会话 `memory_read target=user` 应能读到,且上下文快照中已包含。
77
+
78
+ ## 开发
79
+
80
+ ```bash
81
+ npm install
82
+ npm run check # 五个运行时文件逐个 node --check
83
+ npm pack --dry-run # 看发布内容
84
+ ```
85
+
86
+ 纯 JavaScript,无构建步骤:`exports` 直接指向包根的 `入口.js`。
87
+
88
+ ## 包内文件
89
+
90
+ `入口.js`(插件入口与配置)、`路径.js`(记忆目录解析)、`记忆文件.js`(注入模板/截断/写入语义)、`策略.js`(记忆策略提示词)、`工具.js`(两个模型工具)、`cordis.patch.yml`(bundle 补丁)、`图标.svg`、`文档/preview.svg`。
91
+
92
+ ## 许可
93
+
94
+ MIT,见 [LICENSE](LICENSE)。
@@ -0,0 +1,89 @@
1
+ /**
2
+ * WorkBuddy 记忆路径解析。
3
+ *
4
+ * 按 WorkBuddy 5.11.3 的实际目录布局实现:
5
+ * - 数据目录名:WORKBUDDY_DATA_FOLDER_NAME 或 '.workbuddy'
6
+ * - 配置根目录:WORKBUDDY_CONFIG_DIR 或 ~/.workbuddy
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
+ /** 从会话工作目录向上寻找项目根;没有任何标记时以会话目录本身为项目根。 */
57
+ export function 项目根目录(工作目录, 标记列表) {
58
+ const 起点 = resolve(工作目录)
59
+ let 当前 = 起点
60
+ while (true) {
61
+ for (const 标记 of 标记列表) {
62
+ try { if (existsSync(join(当前, 标记))) return 当前 } catch { /* 忽略不可读目录 */ }
63
+ }
64
+ const 父级 = dirname(当前)
65
+ if (父级 === 当前) return 起点
66
+ 当前 = 父级
67
+ }
68
+ }
69
+
70
+ /** 项目级记忆目录:<项目根>/<数据目录名>/memory。 */
71
+ export function 项目记忆目录(工作目录, 配置) {
72
+ const 根 = 项目根目录(工作目录, 配置.projectRootMarkers)
73
+ return join(根, 数据目录名(配置), 'memory')
74
+ }
75
+
76
+ /** 本地时区的 YYYY-MM-DD,与每日日志文件名一致。 */
77
+ export function 今天日期(此刻 = new Date()) {
78
+ const 年 = 此刻.getFullYear()
79
+ const 月 = String(此刻.getMonth() + 1).padStart(2, '0')
80
+ const 日 = String(此刻.getDate()).padStart(2, '0')
81
+ return `${年}-${月}-${日}`
82
+ }
83
+
84
+ export function 是合法日期(文本) {
85
+ return typeof 文本 === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(文本)
86
+ }
87
+
88
+ export const 用户记忆文件名 = 'MEMORY.md'
89
+ 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.